book.tex 711 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481
  1. \documentclass[7x10,nocrop]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \definecolor{lightgray}{gray}{1}
  19. \newcommand{\black}[1]{{\color{black} #1}}
  20. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  21. \newcommand{\gray}[1]{{\color{gray} #1}}
  22. \def\racketEd{0}
  23. \def\pythonEd{1}
  24. \def\edition{0}
  25. % material that is specific to the Racket edition of the book
  26. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  27. % would like a command for: \if\edition\racketEd\color{olive}
  28. % and : \fi\color{black}
  29. % material that is specific to the Python edition of the book
  30. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  31. %% For multiple indices:
  32. \usepackage{multind}
  33. \makeindex{subject}
  34. \makeindex{authors}
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \if\edition\racketEd
  37. \lstset{%
  38. language=Lisp,
  39. basicstyle=\ttfamily\small,
  40. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  41. deletekeywords={read,mapping,vector},
  42. escapechar=|,
  43. columns=flexible,
  44. moredelim=[is][\color{red}]{~}{~},
  45. showstringspaces=false
  46. }
  47. \fi
  48. \if\edition\pythonEd
  49. \lstset{%
  50. language=Python,
  51. basicstyle=\ttfamily\small,
  52. morekeywords={match,case,bool,int,let},
  53. deletekeywords={},
  54. escapechar=|,
  55. columns=flexible,
  56. moredelim=[is][\color{red}]{~}{~},
  57. showstringspaces=false
  58. }
  59. \fi
  60. %%% Any shortcut own defined macros place here
  61. %% sample of author macro:
  62. \input{defs}
  63. \newtheorem{exercise}[theorem]{Exercise}
  64. % Adjusted settings
  65. \setlength{\columnsep}{4pt}
  66. %% \begingroup
  67. %% \setlength{\intextsep}{0pt}%
  68. %% \setlength{\columnsep}{0pt}%
  69. %% \begin{wrapfigure}{r}{0.5\textwidth}
  70. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  71. %% \caption{Basic layout}
  72. %% \end{wrapfigure}
  73. %% \lipsum[1]
  74. %% \endgroup
  75. \newbox\oiintbox
  76. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  77. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  78. \def\oiint{\copy\oiintbox}
  79. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  80. %\usepackage{showframe}
  81. \def\ShowFrameLinethickness{0.125pt}
  82. \addbibresource{book.bib}
  83. \begin{document}
  84. \frontmatter
  85. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  86. \halftitlepage
  87. \Title{Essentials of Compilation}
  88. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  89. %\edition{First Edition}
  90. \BookAuthor{Jeremy G. Siek}
  91. \imprint{The MIT Press\\
  92. Cambridge, Massachusetts\\
  93. London, England}
  94. \begin{copyrightpage}
  95. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  96. or personal downloading under the
  97. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  98. license.
  99. Copyright in this monograph has been licensed exclusively to The MIT
  100. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  101. version to the public in 2022. All inquiries regarding rights should
  102. be addressed to The MIT Press, Rights and Permissions Department.
  103. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  104. %% All rights reserved. No part of this book may be reproduced in any
  105. %% form by any electronic or mechanical means (including photocopying,
  106. %% recording, or information storage and retrieval) without permission in
  107. %% writing from the publisher.
  108. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  109. %% United States of America.
  110. %% Library of Congress Cataloging-in-Publication Data is available.
  111. %% ISBN:
  112. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  113. \end{copyrightpage}
  114. \dedication{This book is dedicated to the programming language wonks
  115. at Indiana University.}
  116. %% \begin{epigraphpage}
  117. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  118. %% \textit{Book Name if any}}
  119. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  120. %% \end{epigraphpage}
  121. \tableofcontents
  122. %\listoffigures
  123. %\listoftables
  124. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  125. \chapter*{Preface}
  126. \addcontentsline{toc}{fmbm}{Preface}
  127. There is a magical moment when a programmer presses the ``run'' button
  128. and the software begins to execute. Somehow a program written in a
  129. high-level language is running on a computer that is only capable of
  130. shuffling bits. Here we reveal the wizardry that makes that moment
  131. possible. Beginning with the groundbreaking work of Backus and
  132. colleagues in the 1950s, computer scientists discovered techniques for
  133. constructing programs, called \emph{compilers}, that automatically
  134. translate high-level programs into machine code.
  135. We take you on a journey of constructing your own compiler for a small
  136. but powerful language. Along the way we explain the essential
  137. concepts, algorithms, and data structures that underlie compilers. We
  138. develop your understanding of how programs are mapped onto computer
  139. hardware, which is helpful when reasoning about properties at the
  140. junction between hardware and software such as execution time,
  141. software errors, and security vulnerabilities. For those interested
  142. in pursuing compiler construction as a career, our goal is to provide a
  143. stepping-stone to advanced topics such as just-in-time compilation,
  144. program analysis, and program optimization. For those interested in
  145. designing and implementing programming languages, we connect
  146. language design choices to their impact on the compiler and the generated
  147. code.
  148. A compiler is typically organized as a sequence of stages that
  149. progressively translate a program to the code that runs on
  150. hardware. We take this approach to the extreme by partitioning our
  151. compiler into a large number of \emph{nanopasses}, each of which
  152. performs a single task. This enables the testing of each pass in
  153. isolation and focuses our attention, making the compiler far easier to
  154. understand.
  155. The most familiar approach to describing compilers is with each
  156. chapter dedicated to one pass. The problem with that approach is it
  157. obfuscates how language features motivate design choices in a
  158. compiler. We instead take an \emph{incremental} approach in which we
  159. build a complete compiler in each chapter, starting with a small input
  160. language that includes only arithmetic and variables. We add new
  161. language features in subsequent chapters, extending the compiler as
  162. necessary.
  163. Our choice of language features is designed to elicit fundamental
  164. concepts and algorithms used in compilers.
  165. \begin{itemize}
  166. \item We begin with integer arithmetic and local variables in
  167. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  168. the fundamental tools of compiler construction: \emph{abstract
  169. syntax trees} and \emph{recursive functions}.
  170. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  171. \emph{graph coloring} to assign variables to machine registers.
  172. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  173. motivates an elegant recursive algorithm for translating them into
  174. conditional \code{goto}'s.
  175. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  176. variables}. This elicits the need for \emph{dataflow
  177. analysis} in the register allocator.
  178. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  179. \emph{garbage collection}.
  180. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  181. without lexical scoping, similar to functions in the C programming
  182. language~\citep{Kernighan:1988nx}. The reader learns about the
  183. procedure call stack and \emph{calling conventions} and how they interact
  184. with register allocation and garbage collection. The chapter also
  185. describes how to generate efficient tail calls.
  186. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  187. scoping, i.e., \emph{lambda} expressions. The reader learns about
  188. \emph{closure conversion}, in which lambdas are translated into a
  189. combination of functions and tuples.
  190. % Chapter about classes and objects?
  191. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  192. point the input languages are statically typed. The reader extends
  193. the statically typed language with an \code{Any} type which serves
  194. as a target for compiling the dynamically typed language.
  195. {\if\edition\pythonEd
  196. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  197. \emph{classes}.
  198. \fi}
  199. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  200. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  201. in which different regions of a program may be static or dynamically
  202. typed. The reader implements runtime support for \emph{proxies} that
  203. allow values to safely move between regions.
  204. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  205. leveraging the \code{Any} type and type casts developed in Chapters
  206. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  207. \end{itemize}
  208. There are many language features that we do not include. Our choices
  209. balance the incidental complexity of a feature versus the fundamental
  210. concepts that it exposes. For example, we include tuples and not
  211. records because they both elicit the study of heap allocation and
  212. garbage collection but records come with more incidental complexity.
  213. Since 2009 drafts of this book have served as the textbook for 16-week
  214. compiler courses for upper-level undergraduates and first-year
  215. graduate students at the University of Colorado and Indiana
  216. University.
  217. %
  218. Students come into the course having learned the basics of
  219. programming, data structures and algorithms, and discrete
  220. mathematics.
  221. %
  222. At the beginning of the course, students form groups of 2-4 people.
  223. The groups complete one chapter every two weeks, starting with
  224. Chapter~\ref{ch:Lvar} and finishing with
  225. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  226. that we assign to the graduate students. The last two weeks of the
  227. course involve a final project in which students design and implement
  228. a compiler extension of their choosing. The later chapters can be
  229. used in support of these projects. For compiler courses at
  230. universities on the quarter system (about 10 weeks in length), we
  231. recommend completing up through Chapter~\ref{ch:Lvec} or
  232. Chapter~\ref{ch:Lfun} and providing some scafolding code to the
  233. students for each compiler pass.
  234. %
  235. The course can be adapted to emphasize functional languages by
  236. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  237. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  238. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  239. %
  240. \python{A course that emphasizes object-oriented languages would
  241. include Chapter~\ref{ch:Lobject}.}
  242. %
  243. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  244. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  245. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  246. tail calls.
  247. This book has been used in compiler courses at California Polytechnic
  248. State University, Portland State University, Rose–Hulman Institute of
  249. Technology, University of Freiburg, University of Massachusetts
  250. Lowell, and the University of Vermont.
  251. \begin{figure}[tp]
  252. {\if\edition\racketEd
  253. \begin{tikzpicture}[baseline=(current bounding box.center)]
  254. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  255. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  256. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  257. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  258. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  259. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  260. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  261. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  262. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  263. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  264. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  265. \path[->] (C1) edge [above] node {} (C2);
  266. \path[->] (C2) edge [above] node {} (C3);
  267. \path[->] (C3) edge [above] node {} (C4);
  268. \path[->] (C4) edge [above] node {} (C5);
  269. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  270. \path[->] (C5) edge [above] node {} (C7);
  271. \path[->] (C6) edge [above] node {} (C7);
  272. \path[->] (C4) edge [above] node {} (C8);
  273. \path[->] (C4) edge [above] node {} (C9);
  274. \path[->] (C7) edge [above] node {} (C10);
  275. \path[->] (C8) edge [above] node {} (C10);
  276. \path[->] (C10) edge [above] node {} (C11);
  277. \end{tikzpicture}
  278. \fi}
  279. {\if\edition\pythonEd
  280. \begin{tikzpicture}[baseline=(current bounding box.center)]
  281. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  282. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  283. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  284. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  285. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  286. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  287. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  288. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  289. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  290. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  291. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  292. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  293. \path[->] (C1) edge [above] node {} (C2);
  294. \path[->] (C2) edge [above] node {} (C3);
  295. \path[->] (C3) edge [above] node {} (C4);
  296. \path[->] (C4) edge [above] node {} (C5);
  297. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  298. \path[->] (C5) edge [above] node {} (C7);
  299. \path[->] (C6) edge [above] node {} (C7);
  300. \path[->] (C4) edge [above] node {} (C8);
  301. \path[->] (C4) edge [above] node {} (C9);
  302. \path[->] (C7) edge [above] node {} (C10);
  303. \path[->] (C8) edge [above] node {} (C10);
  304. \path[->] (C8) edge [above] node {} (CO);
  305. \path[->] (C10) edge [above] node {} (C11);
  306. \end{tikzpicture}
  307. \fi}
  308. \caption{Diagram of chapter dependencies.}
  309. \label{fig:chapter-dependences}
  310. \end{figure}
  311. \racket{
  312. We use the \href{https://racket-lang.org/}{Racket} language both for
  313. the implementation of the compiler and for the input language, so the
  314. reader should be proficient with Racket or Scheme. There are many
  315. excellent resources for learning Scheme and
  316. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  317. }
  318. \python{
  319. This edition of the book uses \href{https://www.python.org/}{Python}
  320. both for the implementation of the compiler and for the input language, so the
  321. reader should be proficient with Python. There are many
  322. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  323. }
  324. The support code for this book is in the github repository at
  325. the following location:
  326. \if\edition\racketEd
  327. \begin{center}\small
  328. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  329. \end{center}
  330. \fi
  331. \if\edition\pythonEd
  332. \begin{center}\small
  333. \url{https://github.com/IUCompilerCourse/}
  334. \end{center}
  335. \fi
  336. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  337. is helpful but not necessary for the reader to have taken a computer
  338. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  339. assembly language that are needed in the compiler.
  340. %
  341. We follow the System V calling
  342. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  343. that we generate works with the runtime system (written in C) when it
  344. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  345. operating systems on Intel hardware.
  346. %
  347. On the Windows operating system, \code{gcc} uses the Microsoft x64
  348. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  349. assembly code that we generate does \emph{not} work with the runtime
  350. system on Windows. One workaround is to use a virtual machine with
  351. Linux as the guest operating system.
  352. \section*{Acknowledgments}
  353. The tradition of compiler construction at Indiana University goes back
  354. to research and courses on programming languages by Daniel Friedman in
  355. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  356. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  357. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  358. the compiler course and continued the development of Chez Scheme.
  359. %
  360. The compiler course evolved to incorporate novel pedagogical ideas
  361. while also including elements of real-world compilers. One of
  362. Friedman's ideas was to split the compiler into many small
  363. passes. Another idea, called ``the game'', was to test the code
  364. generated by each pass using interpreters.
  365. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  366. developed infrastructure to support this approach and evolved the
  367. course to use even smaller
  368. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  369. design decisions in this book are inspired by the assignment
  370. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  371. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  372. organization of the course made it difficult for students to
  373. understand the rationale for the compiler design. Ghuloum proposed the
  374. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  375. on.
  376. We thank the many students who served as teaching assistants for the
  377. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  378. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  379. garbage collector and x86 interpreter, Michael Vollmer for work on
  380. efficient tail calls, and Michael Vitousek for help with the first
  381. offering of the incremental compiler course at IU.
  382. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  383. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  384. Michael Wollowski for teaching courses based on drafts of this book
  385. and for their feedback.
  386. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  387. course in the early 2000's and especially for finding the bug that
  388. sent our garbage collector on a wild goose chase!
  389. \mbox{}\\
  390. \noindent Jeremy G. Siek \\
  391. Bloomington, Indiana
  392. \mainmatter
  393. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  394. \chapter{Preliminaries}
  395. \label{ch:trees-recur}
  396. In this chapter we review the basic tools that are needed to implement
  397. a compiler. Programs are typically input by a programmer as text,
  398. i.e., a sequence of characters. The program-as-text representation is
  399. called \emph{concrete syntax}. We use concrete syntax to concisely
  400. write down and talk about programs. Inside the compiler, we use
  401. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  402. that efficiently supports the operations that the compiler needs to
  403. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  404. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  405. from concrete syntax to abstract syntax is a process called
  406. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  407. implementation of parsing in this book.
  408. %
  409. \racket{A parser is provided in the support code for translating from
  410. concrete to abstract syntax.}
  411. %
  412. \python{We use Python's \code{ast} module to translate from concrete
  413. to abstract syntax.}
  414. ASTs can be represented in many different ways inside the compiler,
  415. depending on the programming language used to write the compiler.
  416. %
  417. \racket{We use Racket's
  418. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  419. feature to represent ASTs (Section~\ref{sec:ast}).}
  420. %
  421. \python{We use Python classes and objects to represent ASTs, especially the
  422. classes defined in the standard \code{ast} module for the Python
  423. source language.}
  424. %
  425. We use grammars to define the abstract syntax of programming languages
  426. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  427. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  428. recursive functions to construct and deconstruct ASTs
  429. (Section~\ref{sec:recursion}). This chapter provides an brief
  430. introduction to these ideas.
  431. \racket{\index{subject}{struct}}
  432. \python{\index{subject}{class}\index{subject}{object}}
  433. \section{Abstract Syntax Trees}
  434. \label{sec:ast}
  435. Compilers use abstract syntax trees to represent programs because they
  436. often need to ask questions like: for a given part of a program, what
  437. kind of language feature is it? What are its sub-parts? Consider the
  438. program on the left and its AST on the right. This program is an
  439. addition operation and it has two sub-parts, a
  440. \racket{read}\python{input} operation and a negation. The negation has
  441. another sub-part, the integer constant \code{8}. By using a tree to
  442. represent the program, we can easily follow the links to go from one
  443. part of a program to its sub-parts.
  444. \begin{center}
  445. \begin{minipage}{0.4\textwidth}
  446. \if\edition\racketEd
  447. \begin{lstlisting}
  448. (+ (read) (- 8))
  449. \end{lstlisting}
  450. \fi
  451. \if\edition\pythonEd
  452. \begin{lstlisting}
  453. input_int() + -8
  454. \end{lstlisting}
  455. \fi
  456. \end{minipage}
  457. \begin{minipage}{0.4\textwidth}
  458. \begin{equation}
  459. \begin{tikzpicture}
  460. \node[draw] (plus) at (0 , 0) {\key{+}};
  461. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  462. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  463. \node[draw] (8) at (1 , -3) {\key{8}};
  464. \draw[->] (plus) to (read);
  465. \draw[->] (plus) to (minus);
  466. \draw[->] (minus) to (8);
  467. \end{tikzpicture}
  468. \label{eq:arith-prog}
  469. \end{equation}
  470. \end{minipage}
  471. \end{center}
  472. We use the standard terminology for trees to describe ASTs: each
  473. rectangle above is called a \emph{node}. The arrows connect a node to its
  474. \emph{children} (which are also nodes). The top-most node is the
  475. \emph{root}. Every node except for the root has a \emph{parent} (the
  476. node it is the child of). If a node has no children, it is a
  477. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  478. \index{subject}{node}
  479. \index{subject}{children}
  480. \index{subject}{root}
  481. \index{subject}{parent}
  482. \index{subject}{leaf}
  483. \index{subject}{internal node}
  484. %% Recall that an \emph{symbolic expression} (S-expression) is either
  485. %% \begin{enumerate}
  486. %% \item an atom, or
  487. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  488. %% where $e_1$ and $e_2$ are each an S-expression.
  489. %% \end{enumerate}
  490. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  491. %% null value \code{'()}, etc. We can create an S-expression in Racket
  492. %% simply by writing a backquote (called a quasi-quote in Racket)
  493. %% followed by the textual representation of the S-expression. It is
  494. %% quite common to use S-expressions to represent a list, such as $a, b
  495. %% ,c$ in the following way:
  496. %% \begin{lstlisting}
  497. %% `(a . (b . (c . ())))
  498. %% \end{lstlisting}
  499. %% Each element of the list is in the first slot of a pair, and the
  500. %% second slot is either the rest of the list or the null value, to mark
  501. %% the end of the list. Such lists are so common that Racket provides
  502. %% special notation for them that removes the need for the periods
  503. %% and so many parenthesis:
  504. %% \begin{lstlisting}
  505. %% `(a b c)
  506. %% \end{lstlisting}
  507. %% The following expression creates an S-expression that represents AST
  508. %% \eqref{eq:arith-prog}.
  509. %% \begin{lstlisting}
  510. %% `(+ (read) (- 8))
  511. %% \end{lstlisting}
  512. %% When using S-expressions to represent ASTs, the convention is to
  513. %% represent each AST node as a list and to put the operation symbol at
  514. %% the front of the list. The rest of the list contains the children. So
  515. %% in the above case, the root AST node has operation \code{`+} and its
  516. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  517. %% diagram \eqref{eq:arith-prog}.
  518. %% To build larger S-expressions one often needs to splice together
  519. %% several smaller S-expressions. Racket provides the comma operator to
  520. %% splice an S-expression into a larger one. For example, instead of
  521. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  522. %% we could have first created an S-expression for AST
  523. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  524. %% S-expression.
  525. %% \begin{lstlisting}
  526. %% (define ast1.4 `(- 8))
  527. %% (define ast1_1 `(+ (read) ,ast1.4))
  528. %% \end{lstlisting}
  529. %% In general, the Racket expression that follows the comma (splice)
  530. %% can be any expression that produces an S-expression.
  531. {\if\edition\racketEd
  532. We define a Racket \code{struct} for each kind of node. For this
  533. chapter we require just two kinds of nodes: one for integer constants
  534. and one for primitive operations. The following is the \code{struct}
  535. definition for integer constants.\footnote{All of the AST structures are
  536. defined in the file \code{utilities.rkt} in the support code.}
  537. \begin{lstlisting}
  538. (struct Int (value))
  539. \end{lstlisting}
  540. An integer node includes just one thing: the integer value.
  541. To create an AST node for the integer $8$, we write \INT{8}.
  542. \begin{lstlisting}
  543. (define eight (Int 8))
  544. \end{lstlisting}
  545. We say that the value created by \INT{8} is an
  546. \emph{instance} of the
  547. \code{Int} structure.
  548. The following is the \code{struct} definition for primitive operations.
  549. \begin{lstlisting}
  550. (struct Prim (op args))
  551. \end{lstlisting}
  552. A primitive operation node includes an operator symbol \code{op} and a
  553. list of child \code{args}. For example, to create an AST that negates
  554. the number $8$, we write the following.
  555. \begin{lstlisting}
  556. (define neg-eight (Prim '- (list eight)))
  557. \end{lstlisting}
  558. Primitive operations may have zero or more children. The \code{read}
  559. operator has zero:
  560. \begin{lstlisting}
  561. (define rd (Prim 'read '()))
  562. \end{lstlisting}
  563. The addition operator has two children:
  564. \begin{lstlisting}
  565. (define ast1_1 (Prim '+ (list rd neg-eight)))
  566. \end{lstlisting}
  567. We have made a design choice regarding the \code{Prim} structure.
  568. Instead of using one structure for many different operations
  569. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  570. structure for each operation, as follows.
  571. \begin{lstlisting}
  572. (struct Read ())
  573. (struct Add (left right))
  574. (struct Neg (value))
  575. \end{lstlisting}
  576. The reason we choose to use just one structure is that in many parts
  577. of the compiler the code for the different primitive operators is the
  578. same, so we might as well just write that code once, which is enabled
  579. by using a single structure.
  580. \fi}
  581. {\if\edition\pythonEd
  582. We use a Python \code{class} for each kind of node.
  583. The following is the class definition for constants.
  584. \begin{lstlisting}
  585. class Constant:
  586. def __init__(self, value):
  587. self.value = value
  588. \end{lstlisting}
  589. An integer constant node includes just one thing: the integer value.
  590. To create an AST node for the integer $8$, we write \INT{8}.
  591. \begin{lstlisting}
  592. eight = Constant(8)
  593. \end{lstlisting}
  594. We say that the value created by \INT{8} is an
  595. \emph{instance} of the \code{Constant} class.
  596. The following is the class definition for unary operators.
  597. \begin{lstlisting}
  598. class UnaryOp:
  599. def __init__(self, op, operand):
  600. self.op = op
  601. self.operand = operand
  602. \end{lstlisting}
  603. The specific operation is specified by the \code{op} parameter. For
  604. example, the class \code{USub} is for unary subtraction. (More unary
  605. operators are introduced in later chapters.) To create an AST that
  606. negates the number $8$, we write the following.
  607. \begin{lstlisting}
  608. neg_eight = UnaryOp(USub(), eight)
  609. \end{lstlisting}
  610. The call to the \code{input\_int} function is represented by the
  611. \code{Call} and \code{Name} classes.
  612. \begin{lstlisting}
  613. class Call:
  614. def __init__(self, func, args):
  615. self.func = func
  616. self.args = args
  617. class Name:
  618. def __init__(self, id):
  619. self.id = id
  620. \end{lstlisting}
  621. To create an AST node that calls \code{input\_int}, we write
  622. \begin{lstlisting}
  623. read = Call(Name('input_int'), [])
  624. \end{lstlisting}
  625. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  626. the \code{BinOp} class for binary operators.
  627. \begin{lstlisting}
  628. class BinOp:
  629. def __init__(self, left, op, right):
  630. self.op = op
  631. self.left = left
  632. self.right = right
  633. \end{lstlisting}
  634. Similar to \code{UnaryOp}, the specific operation is specified by the
  635. \code{op} parameter, which for now is just an instance of the
  636. \code{Add} class. So to create the AST node that adds negative eight
  637. to some user input, we write the following.
  638. \begin{lstlisting}
  639. ast1_1 = BinOp(read, Add(), neg_eight)
  640. \end{lstlisting}
  641. \fi}
  642. When compiling a program such as \eqref{eq:arith-prog}, we need to
  643. know that the operation associated with the root node is addition and
  644. we need to be able to access its two children. \racket{Racket}\python{Python}
  645. provides pattern matching to support these kinds of queries, as we see in
  646. Section~\ref{sec:pattern-matching}.
  647. We often write down the concrete syntax of a program even when we
  648. really have in mind the AST because the concrete syntax is more
  649. concise. We recommend that, in your mind, you always think of
  650. programs as abstract syntax trees.
  651. \section{Grammars}
  652. \label{sec:grammar}
  653. \index{subject}{integer}
  654. \index{subject}{literal}
  655. \index{subject}{constant}
  656. A programming language can be thought of as a \emph{set} of programs.
  657. The set is typically infinite (one can always create larger and larger
  658. programs) so one cannot simply describe a language by listing all of
  659. the programs in the language. Instead we write down a set of rules, a
  660. \emph{grammar}, for building programs. Grammars are often used to
  661. define the concrete syntax of a language but they can also be used to
  662. describe the abstract syntax. We write our rules in a variant of
  663. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  664. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  665. As an example, we describe a small language, named \LangInt{}, that consists of
  666. integers and arithmetic operations.
  667. \index{subject}{grammar}
  668. The first grammar rule for the abstract syntax of \LangInt{} says that an
  669. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  670. \begin{equation}
  671. \Exp ::= \INT{\Int} \label{eq:arith-int}
  672. \end{equation}
  673. %
  674. Each rule has a left-hand-side and a right-hand-side.
  675. If you have an AST node that matches the
  676. right-hand-side, then you can categorize it according to the
  677. left-hand-side.
  678. %
  679. Symbols in typewriter font are \emph{terminal} symbols and must
  680. literally appear in the program for the rule to be applicable.
  681. \index{subject}{terminal}
  682. %
  683. Our grammars do not mention \emph{white-space}, that is, separating characters
  684. like spaces, tabulators, and newlines. White-space may be inserted
  685. between symbols for disambiguation and to improve readability.
  686. \index{subject}{white-space}
  687. %
  688. A name such as $\Exp$ that is defined by the grammar rules is a
  689. \emph{non-terminal}. \index{subject}{non-terminal}
  690. %
  691. The name $\Int$ is also a non-terminal, but instead of defining it
  692. with a grammar rule, we define it with the following explanation. An
  693. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  694. $-$ (for negative integers), such that the sequence of decimals
  695. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  696. the representation of integers using 63 bits, which simplifies several
  697. aspects of compilation. \racket{Thus, these integers correspond to
  698. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  699. \python{In contrast, integers in Python have unlimited precision, but
  700. the techniques needed to handle unlimited precision fall outside the
  701. scope of this book.}
  702. The second grammar rule is the \READOP{} operation that receives an
  703. input integer from the user of the program.
  704. \begin{equation}
  705. \Exp ::= \READ{} \label{eq:arith-read}
  706. \end{equation}
  707. The third rule categorizes the negation of an $\Exp$ node as an
  708. $\Exp$.
  709. \begin{equation}
  710. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  711. \end{equation}
  712. We can apply these rules to categorize the ASTs that are in the
  713. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  714. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  715. following AST is an $\Exp$.
  716. \begin{center}
  717. \begin{minipage}{0.5\textwidth}
  718. \NEG{\INT{\code{8}}}
  719. \end{minipage}
  720. \begin{minipage}{0.25\textwidth}
  721. \begin{equation}
  722. \begin{tikzpicture}
  723. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  724. \node[draw, circle] (8) at (0, -1.2) {$8$};
  725. \draw[->] (minus) to (8);
  726. \end{tikzpicture}
  727. \label{eq:arith-neg8}
  728. \end{equation}
  729. \end{minipage}
  730. \end{center}
  731. The next grammar rules are for addition and subtraction expressions:
  732. \begin{align}
  733. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  734. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  735. \end{align}
  736. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  737. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  738. \eqref{eq:arith-read} and we have already categorized
  739. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  740. to show that
  741. \[
  742. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  743. \]
  744. is an $\Exp$ in the \LangInt{} language.
  745. If you have an AST for which the above rules do not apply, then the
  746. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  747. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  748. because there is no rule for the \key{*} operator. Whenever we
  749. define a language with a grammar, the language only includes those
  750. programs that are justified by the grammar rules.
  751. {\if\edition\pythonEd
  752. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  753. There is a statement for printing the value of an expression
  754. \[
  755. \Stmt{} ::= \PRINT{\Exp}
  756. \]
  757. and a statement that evaluates an expression but ignores the result.
  758. \[
  759. \Stmt{} ::= \EXPR{\Exp}
  760. \]
  761. \fi}
  762. {\if\edition\racketEd
  763. The last grammar rule for \LangInt{} states that there is a
  764. \code{Program} node to mark the top of the whole program:
  765. \[
  766. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  767. \]
  768. The \code{Program} structure is defined as follows
  769. \begin{lstlisting}
  770. (struct Program (info body))
  771. \end{lstlisting}
  772. where \code{body} is an expression. In later chapters, the \code{info}
  773. part will be used to store auxiliary information but for now it is
  774. just the empty list.
  775. \fi}
  776. {\if\edition\pythonEd
  777. The last grammar rule for \LangInt{} states that there is a
  778. \code{Module} node to mark the top of the whole program:
  779. \[
  780. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  781. \]
  782. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  783. this case, a list of statements.
  784. %
  785. The \code{Module} class is defined as follows
  786. \begin{lstlisting}
  787. class Module:
  788. def __init__(self, body):
  789. self.body = body
  790. \end{lstlisting}
  791. where \code{body} is a list of statements.
  792. \fi}
  793. It is common to have many grammar rules with the same left-hand side
  794. but different right-hand sides, such as the rules for $\Exp$ in the
  795. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  796. combine several right-hand-sides into a single rule.
  797. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  798. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  799. defined in Figure~\ref{fig:r0-concrete-syntax}.
  800. \racket{The \code{read-program} function provided in
  801. \code{utilities.rkt} of the support code reads a program in from a
  802. file (the sequence of characters in the concrete syntax of Racket)
  803. and parses it into an abstract syntax tree. See the description of
  804. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  805. details.}
  806. \python{The \code{parse} function in Python's \code{ast} module
  807. converts the concrete syntax (represented as a string) into an
  808. abstract syntax tree.}
  809. \newcommand{\LintGrammarRacket}{
  810. \begin{array}{rcl}
  811. \Type &::=& \key{Integer} \\
  812. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  813. \MID \CSUB{\Exp}{\Exp}
  814. \end{array}
  815. }
  816. \newcommand{\LintASTRacket}{
  817. \begin{array}{rcl}
  818. \Type &::=& \key{Integer} \\
  819. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  820. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  821. \end{array}
  822. }
  823. \newcommand{\LintGrammarPython}{
  824. \begin{array}{rcl}
  825. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  826. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  827. \end{array}
  828. }
  829. \newcommand{\LintASTPython}{
  830. \begin{array}{rcl}
  831. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  832. \itm{unaryop} &::= & \code{USub()} \\
  833. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  834. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  835. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  836. \end{array}
  837. }
  838. \begin{figure}[tp]
  839. \fbox{
  840. \begin{minipage}{0.96\textwidth}
  841. {\if\edition\racketEd
  842. \[
  843. \begin{array}{l}
  844. \LintGrammarRacket \\
  845. \begin{array}{rcl}
  846. \LangInt{} &::=& \Exp
  847. \end{array}
  848. \end{array}
  849. \]
  850. \fi}
  851. {\if\edition\pythonEd
  852. \[
  853. \begin{array}{l}
  854. \LintGrammarPython \\
  855. \begin{array}{rcl}
  856. \LangInt{} &::=& \Stmt^{*}
  857. \end{array}
  858. \end{array}
  859. \]
  860. \fi}
  861. \end{minipage}
  862. }
  863. \caption{The concrete syntax of \LangInt{}.}
  864. \label{fig:r0-concrete-syntax}
  865. \end{figure}
  866. \begin{figure}[tp]
  867. \fbox{
  868. \begin{minipage}{0.96\textwidth}
  869. {\if\edition\racketEd
  870. \[
  871. \begin{array}{l}
  872. \LintASTRacket{} \\
  873. \begin{array}{rcl}
  874. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  875. \end{array}
  876. \end{array}
  877. \]
  878. \fi}
  879. {\if\edition\pythonEd
  880. \[
  881. \begin{array}{l}
  882. \LintASTPython\\
  883. \begin{array}{rcl}
  884. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  885. \end{array}
  886. \end{array}
  887. \]
  888. \fi}
  889. \end{minipage}
  890. }
  891. \caption{The abstract syntax of \LangInt{}.}
  892. \label{fig:r0-syntax}
  893. \end{figure}
  894. \section{Pattern Matching}
  895. \label{sec:pattern-matching}
  896. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  897. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  898. \texttt{match} feature to access the parts of a value.
  899. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  900. \begin{center}
  901. \begin{minipage}{0.5\textwidth}
  902. {\if\edition\racketEd
  903. \begin{lstlisting}
  904. (match ast1_1
  905. [(Prim op (list child1 child2))
  906. (print op)])
  907. \end{lstlisting}
  908. \fi}
  909. {\if\edition\pythonEd
  910. \begin{lstlisting}
  911. match ast1_1:
  912. case BinOp(child1, op, child2):
  913. print(op)
  914. \end{lstlisting}
  915. \fi}
  916. \end{minipage}
  917. \end{center}
  918. {\if\edition\racketEd
  919. %
  920. In the above example, the \texttt{match} form checks whether the AST
  921. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  922. three pattern variables \texttt{op}, \texttt{child1}, and
  923. \texttt{child2}. In general, a match clause consists of a
  924. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  925. recursively defined to be either a pattern variable, a structure name
  926. followed by a pattern for each of the structure's arguments, or an
  927. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  928. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  929. and Chapter 9 of The Racket
  930. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  931. for complete descriptions of \code{match}.)
  932. %
  933. The body of a match clause may contain arbitrary Racket code. The
  934. pattern variables can be used in the scope of the body, such as
  935. \code{op} in \code{(print op)}.
  936. %
  937. \fi}
  938. %
  939. %
  940. {\if\edition\pythonEd
  941. %
  942. In the above example, the \texttt{match} form checks whether the AST
  943. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  944. three pattern variables \texttt{child1}, \texttt{op}, and
  945. \texttt{child2}, and then prints out the operator. In general, each
  946. \code{case} consists of a \emph{pattern} and a
  947. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  948. to be either a pattern variable, a class name followed by a pattern
  949. for each of its constructor's arguments, or other literals such as
  950. strings, lists, etc.
  951. %
  952. The body of each \code{case} may contain arbitrary Python code. The
  953. pattern variables can be used in the body, such as \code{op} in
  954. \code{print(op)}.
  955. %
  956. \fi}
  957. A \code{match} form may contain several clauses, as in the following
  958. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  959. the AST. The \code{match} proceeds through the clauses in order,
  960. checking whether the pattern can match the input AST. The body of the
  961. first clause that matches is executed. The output of \code{leaf} for
  962. several ASTs is shown on the right.
  963. \begin{center}
  964. \begin{minipage}{0.6\textwidth}
  965. {\if\edition\racketEd
  966. \begin{lstlisting}
  967. (define (leaf arith)
  968. (match arith
  969. [(Int n) #t]
  970. [(Prim 'read '()) #t]
  971. [(Prim '- (list e1)) #f]
  972. [(Prim '+ (list e1 e2)) #f]
  973. [(Prim '- (list e1 e2)) #f]))
  974. (leaf (Prim 'read '()))
  975. (leaf (Prim '- (list (Int 8))))
  976. (leaf (Int 8))
  977. \end{lstlisting}
  978. \fi}
  979. {\if\edition\pythonEd
  980. \begin{lstlisting}
  981. def leaf(arith):
  982. match arith:
  983. case Constant(n):
  984. return True
  985. case Call(Name('input_int'), []):
  986. return True
  987. case UnaryOp(USub(), e1):
  988. return False
  989. case BinOp(e1, Add(), e2):
  990. return False
  991. case BinOp(e1, Sub(), e2):
  992. return False
  993. print(leaf(Call(Name('input_int'), [])))
  994. print(leaf(UnaryOp(USub(), eight)))
  995. print(leaf(Constant(8)))
  996. \end{lstlisting}
  997. \fi}
  998. \end{minipage}
  999. \vrule
  1000. \begin{minipage}{0.25\textwidth}
  1001. {\if\edition\racketEd
  1002. \begin{lstlisting}
  1003. #t
  1004. #f
  1005. #t
  1006. \end{lstlisting}
  1007. \fi}
  1008. {\if\edition\pythonEd
  1009. \begin{lstlisting}
  1010. True
  1011. False
  1012. True
  1013. \end{lstlisting}
  1014. \fi}
  1015. \end{minipage}
  1016. \end{center}
  1017. When constructing a \code{match} expression, we refer to the grammar
  1018. definition to identify which non-terminal we are expecting to match
  1019. against, then we make sure that 1) we have one
  1020. \racket{clause}\python{case} for each alternative of that non-terminal
  1021. and 2) that the pattern in each \racket{clause}\python{case}
  1022. corresponds to the corresponding right-hand side of a grammar
  1023. rule. For the \code{match} in the \code{leaf} function, we refer to
  1024. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1025. non-terminal has 4 alternatives, so the \code{match} has 4
  1026. \racket{clauses}\python{cases}. The pattern in each
  1027. \racket{clause}\python{case} corresponds to the right-hand side of a
  1028. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1029. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1030. translating from grammars to patterns, replace non-terminals such as
  1031. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1032. \code{e2}).
  1033. \section{Recursive Functions}
  1034. \label{sec:recursion}
  1035. \index{subject}{recursive function}
  1036. Programs are inherently recursive. For example, an expression is often
  1037. made of smaller expressions. Thus, the natural way to process an
  1038. entire program is with a recursive function. As a first example of
  1039. such a recursive function, we define the function \code{is\_exp} in
  1040. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1041. determines whether or not it is an expression in \LangInt{}.
  1042. %
  1043. We say that a function is defined by \emph{structural recursion} when
  1044. it is defined using a sequence of match \racket{clauses}\python{cases}
  1045. that correspond to a grammar, and the body of each
  1046. \racket{clause}\python{case} makes a recursive call on each child
  1047. node.\footnote{This principle of structuring code according to the
  1048. data definition is advocated in the book \emph{How to Design
  1049. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1050. second function, named \code{stmt}, that recognizes whether a value
  1051. is a \LangInt{} statement.} \python{Finally, }
  1052. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1053. which determines whether an AST is a program in \LangInt{}. In
  1054. general we can write one recursive function to handle each
  1055. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1056. two examples at the bottom of the figure, the first is in
  1057. \LangInt{} and the second is not.
  1058. \begin{figure}[tp]
  1059. {\if\edition\racketEd
  1060. \begin{lstlisting}
  1061. (define (is_exp ast)
  1062. (match ast
  1063. [(Int n) #t]
  1064. [(Prim 'read '()) #t]
  1065. [(Prim '- (list e)) (is_exp e)]
  1066. [(Prim '+ (list e1 e2))
  1067. (and (is_exp e1) (is_exp e2))]
  1068. [(Prim '- (list e1 e2))
  1069. (and (is_exp e1) (is_exp e2))]
  1070. [else #f]))
  1071. (define (is_Lint ast)
  1072. (match ast
  1073. [(Program '() e) (is_exp e)]
  1074. [else #f]))
  1075. (is_Lint (Program '() ast1_1)
  1076. (is_Lint (Program '()
  1077. (Prim '* (list (Prim 'read '())
  1078. (Prim '+ (list (Int 8)))))))
  1079. \end{lstlisting}
  1080. \fi}
  1081. {\if\edition\pythonEd
  1082. \begin{lstlisting}
  1083. def is_exp(e):
  1084. match e:
  1085. case Constant(n):
  1086. return True
  1087. case Call(Name('input_int'), []):
  1088. return True
  1089. case UnaryOp(USub(), e1):
  1090. return is_exp(e1)
  1091. case BinOp(e1, Add(), e2):
  1092. return is_exp(e1) and is_exp(e2)
  1093. case BinOp(e1, Sub(), e2):
  1094. return is_exp(e1) and is_exp(e2)
  1095. case _:
  1096. return False
  1097. def stmt(s):
  1098. match s:
  1099. case Expr(Call(Name('print'), [e])):
  1100. return is_exp(e)
  1101. case Expr(e):
  1102. return is_exp(e)
  1103. case _:
  1104. return False
  1105. def is_Lint(p):
  1106. match p:
  1107. case Module(body):
  1108. return all([stmt(s) for s in body])
  1109. case _:
  1110. return False
  1111. print(is_Lint(Module([Expr(ast1_1)])))
  1112. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1113. UnaryOp(Add(), Constant(8))))])))
  1114. \end{lstlisting}
  1115. \fi}
  1116. \caption{Example of recursive functions for \LangInt{}. These functions
  1117. recognize whether an AST is in \LangInt{}.}
  1118. \label{fig:exp-predicate}
  1119. \end{figure}
  1120. %% You may be tempted to merge the two functions into one, like this:
  1121. %% \begin{center}
  1122. %% \begin{minipage}{0.5\textwidth}
  1123. %% \begin{lstlisting}
  1124. %% (define (Lint ast)
  1125. %% (match ast
  1126. %% [(Int n) #t]
  1127. %% [(Prim 'read '()) #t]
  1128. %% [(Prim '- (list e)) (Lint e)]
  1129. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1130. %% [(Program '() e) (Lint e)]
  1131. %% [else #f]))
  1132. %% \end{lstlisting}
  1133. %% \end{minipage}
  1134. %% \end{center}
  1135. %% %
  1136. %% Sometimes such a trick will save a few lines of code, especially when
  1137. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1138. %% \emph{not} recommended because it can get you into trouble.
  1139. %% %
  1140. %% For example, the above function is subtly wrong:
  1141. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1142. %% returns true when it should return false.
  1143. \section{Interpreters}
  1144. \label{sec:interp_Lint}
  1145. \index{subject}{interpreter}
  1146. The behavior of a program is defined by the specification of the
  1147. programming language.
  1148. %
  1149. \racket{For example, the Scheme language is defined in the report by
  1150. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1151. reference manual~\citep{plt-tr}.}
  1152. %
  1153. \python{For example, the Python language is defined in the Python
  1154. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1155. %
  1156. In this book we use interpreters to specify each language that we
  1157. consider. An interpreter that is designated as the definition of a
  1158. language is called a \emph{definitional
  1159. interpreter}~\citep{reynolds72:_def_interp}.
  1160. \index{subject}{definitional interpreter} We warm up by creating a
  1161. definitional interpreter for the \LangInt{} language. This interpreter
  1162. serves as a second example of structural recursion. The
  1163. \code{interp\_Lint} function is defined in
  1164. Figure~\ref{fig:interp_Lint}.
  1165. %
  1166. \racket{The body of the function is a match on the input program
  1167. followed by a call to the \lstinline{interp_exp} helper function,
  1168. which in turn has one match clause per grammar rule for \LangInt{}
  1169. expressions.}
  1170. %
  1171. \python{The body of the function matches on the \code{Module} AST node
  1172. and then invokes \code{interp\_stmt} on each statement in the
  1173. module. The \code{interp\_stmt} function includes a case for each
  1174. grammar rule of the \Stmt{} non-terminal and it calls
  1175. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1176. function includes a case for each grammar rule of the \Exp{}
  1177. non-terminal.}
  1178. \begin{figure}[tp]
  1179. {\if\edition\racketEd
  1180. \begin{lstlisting}
  1181. (define (interp_exp e)
  1182. (match e
  1183. [(Int n) n]
  1184. [(Prim 'read '())
  1185. (define r (read))
  1186. (cond [(fixnum? r) r]
  1187. [else (error 'interp_exp "read expected an integer" r)])]
  1188. [(Prim '- (list e))
  1189. (define v (interp_exp e))
  1190. (fx- 0 v)]
  1191. [(Prim '+ (list e1 e2))
  1192. (define v1 (interp_exp e1))
  1193. (define v2 (interp_exp e2))
  1194. (fx+ v1 v2)]
  1195. [(Prim '- (list e1 e2))
  1196. (define v1 ((interp-exp env) e1))
  1197. (define v2 ((interp-exp env) e2))
  1198. (fx- v1 v2)]))
  1199. (define (interp_Lint p)
  1200. (match p
  1201. [(Program '() e) (interp_exp e)]))
  1202. \end{lstlisting}
  1203. \fi}
  1204. {\if\edition\pythonEd
  1205. \begin{lstlisting}
  1206. def interp_exp(e):
  1207. match e:
  1208. case BinOp(left, Add(), right):
  1209. l = interp_exp(left); r = interp_exp(right)
  1210. return l + r
  1211. case BinOp(left, Sub(), right):
  1212. l = interp_exp(left); r = interp_exp(right)
  1213. return l - r
  1214. case UnaryOp(USub(), v):
  1215. return - interp_exp(v)
  1216. case Constant(value):
  1217. return value
  1218. case Call(Name('input_int'), []):
  1219. return int(input())
  1220. def interp_stmt(s):
  1221. match s:
  1222. case Expr(Call(Name('print'), [arg])):
  1223. print(interp_exp(arg))
  1224. case Expr(value):
  1225. interp_exp(value)
  1226. def interp_Lint(p):
  1227. match p:
  1228. case Module(body):
  1229. for s in body:
  1230. interp_stmt(s)
  1231. \end{lstlisting}
  1232. \fi}
  1233. \caption{Interpreter for the \LangInt{} language.}
  1234. \label{fig:interp_Lint}
  1235. \end{figure}
  1236. Let us consider the result of interpreting a few \LangInt{} programs. The
  1237. following program adds two integers.
  1238. {\if\edition\racketEd
  1239. \begin{lstlisting}
  1240. (+ 10 32)
  1241. \end{lstlisting}
  1242. \fi}
  1243. {\if\edition\pythonEd
  1244. \begin{lstlisting}
  1245. print(10 + 32)
  1246. \end{lstlisting}
  1247. \fi}
  1248. %
  1249. \noindent The result is \key{42}, the answer to life, the universe,
  1250. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1251. the Galaxy} by Douglas Adams.}
  1252. %
  1253. We wrote the above program in concrete syntax whereas the parsed
  1254. abstract syntax is:
  1255. {\if\edition\racketEd
  1256. \begin{lstlisting}
  1257. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1258. \end{lstlisting}
  1259. \fi}
  1260. {\if\edition\pythonEd
  1261. \begin{lstlisting}
  1262. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1263. \end{lstlisting}
  1264. \fi}
  1265. The next example demonstrates that expressions may be nested within
  1266. each other, in this case nesting several additions and negations.
  1267. {\if\edition\racketEd
  1268. \begin{lstlisting}
  1269. (+ 10 (- (+ 12 20)))
  1270. \end{lstlisting}
  1271. \fi}
  1272. {\if\edition\pythonEd
  1273. \begin{lstlisting}
  1274. print(10 + -(12 + 20))
  1275. \end{lstlisting}
  1276. \fi}
  1277. %
  1278. \noindent What is the result of the above program?
  1279. {\if\edition\racketEd
  1280. As mentioned previously, the \LangInt{} language does not support
  1281. arbitrarily-large integers, but only $63$-bit integers, so we
  1282. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1283. in Racket.
  1284. Suppose
  1285. \[
  1286. n = 999999999999999999
  1287. \]
  1288. which indeed fits in $63$-bits. What happens when we run the
  1289. following program in our interpreter?
  1290. \begin{lstlisting}
  1291. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1292. \end{lstlisting}
  1293. It produces an error:
  1294. \begin{lstlisting}
  1295. fx+: result is not a fixnum
  1296. \end{lstlisting}
  1297. We establish the convention that if running the definitional
  1298. interpreter on a program produces an error then the meaning of that
  1299. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1300. error is a \code{trapped-error}. A compiler for the language is under
  1301. no obligations regarding programs with unspecified behavior; it does
  1302. not have to produce an executable, and if it does, that executable can
  1303. do anything. On the other hand, if the error is a
  1304. \code{trapped-error}, then the compiler must produce an executable and
  1305. it is required to report that an error occurred. To signal an error,
  1306. exit with a return code of \code{255}. The interpreters in chapters
  1307. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1308. \code{trapped-error}.
  1309. \fi}
  1310. % TODO: how to deal with too-large integers in the Python interpreter?
  1311. %% This convention applies to the languages defined in this
  1312. %% book, as a way to simplify the student's task of implementing them,
  1313. %% but this convention is not applicable to all programming languages.
  1314. %%
  1315. Moving on to the last feature of the \LangInt{} language, the
  1316. \READOP{} operation prompts the user of the program for an integer.
  1317. Recall that program \eqref{eq:arith-prog} requests an integer input
  1318. and then subtracts \code{8}. So if we run
  1319. {\if\edition\racketEd
  1320. \begin{lstlisting}
  1321. (interp_Lint (Program '() ast1_1))
  1322. \end{lstlisting}
  1323. \fi}
  1324. {\if\edition\pythonEd
  1325. \begin{lstlisting}
  1326. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1327. \end{lstlisting}
  1328. \fi}
  1329. \noindent and if the input is \code{50}, the result is \code{42}.
  1330. We include the \READOP{} operation in \LangInt{} so a clever student
  1331. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1332. during compilation to obtain the output and then generates the trivial
  1333. code to produce the output.\footnote{Yes, a clever student did this in the
  1334. first instance of this course!}
  1335. The job of a compiler is to translate a program in one language into a
  1336. program in another language so that the output program behaves the
  1337. same way as the input program. This idea is depicted in the
  1338. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1339. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1340. Given a compiler that translates from language $\mathcal{L}_1$ to
  1341. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1342. compiler must translate it into some program $P_2$ such that
  1343. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1344. same input $i$ yields the same output $o$.
  1345. \begin{equation} \label{eq:compile-correct}
  1346. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1347. \node (p1) at (0, 0) {$P_1$};
  1348. \node (p2) at (3, 0) {$P_2$};
  1349. \node (o) at (3, -2.5) {$o$};
  1350. \path[->] (p1) edge [above] node {compile} (p2);
  1351. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1352. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1353. \end{tikzpicture}
  1354. \end{equation}
  1355. In the next section we see our first example of a compiler.
  1356. \section{Example Compiler: a Partial Evaluator}
  1357. \label{sec:partial-evaluation}
  1358. In this section we consider a compiler that translates \LangInt{}
  1359. programs into \LangInt{} programs that may be more efficient. The
  1360. compiler eagerly computes the parts of the program that do not depend
  1361. on any inputs, a process known as \emph{partial
  1362. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1363. For example, given the following program
  1364. {\if\edition\racketEd
  1365. \begin{lstlisting}
  1366. (+ (read) (- (+ 5 3)))
  1367. \end{lstlisting}
  1368. \fi}
  1369. {\if\edition\pythonEd
  1370. \begin{lstlisting}
  1371. print(input_int() + -(5 + 3) )
  1372. \end{lstlisting}
  1373. \fi}
  1374. \noindent our compiler translates it into the program
  1375. {\if\edition\racketEd
  1376. \begin{lstlisting}
  1377. (+ (read) -8)
  1378. \end{lstlisting}
  1379. \fi}
  1380. {\if\edition\pythonEd
  1381. \begin{lstlisting}
  1382. print(input_int() + -8)
  1383. \end{lstlisting}
  1384. \fi}
  1385. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1386. evaluator for the \LangInt{} language. The output of the partial evaluator
  1387. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1388. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1389. whereas the code for partially evaluating the negation and addition
  1390. operations is factored into three auxiliary functions:
  1391. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1392. functions is the output of partially evaluating the children.
  1393. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1394. arguments are integers and if they are, perform the appropriate
  1395. arithmetic. Otherwise, they create an AST node for the arithmetic
  1396. operation.
  1397. \begin{figure}[tp]
  1398. {\if\edition\racketEd
  1399. \begin{lstlisting}
  1400. (define (pe_neg r)
  1401. (match r
  1402. [(Int n) (Int (fx- 0 n))]
  1403. [else (Prim '- (list r))]))
  1404. (define (pe_add r1 r2)
  1405. (match* (r1 r2)
  1406. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1407. [(_ _) (Prim '+ (list r1 r2))]))
  1408. (define (pe_sub r1 r2)
  1409. (match* (r1 r2)
  1410. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1411. [(_ _) (Prim '- (list r1 r2))]))
  1412. (define (pe_exp e)
  1413. (match e
  1414. [(Int n) (Int n)]
  1415. [(Prim 'read '()) (Prim 'read '())]
  1416. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1417. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1418. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1419. (define (pe_Lint p)
  1420. (match p
  1421. [(Program '() e) (Program '() (pe_exp e))]))
  1422. \end{lstlisting}
  1423. \fi}
  1424. {\if\edition\pythonEd
  1425. \begin{lstlisting}
  1426. def pe_neg(r):
  1427. match r:
  1428. case Constant(n):
  1429. return Constant(-n)
  1430. case _:
  1431. return UnaryOp(USub(), r)
  1432. def pe_add(r1, r2):
  1433. match (r1, r2):
  1434. case (Constant(n1), Constant(n2)):
  1435. return Constant(n1 + n2)
  1436. case _:
  1437. return BinOp(r1, Add(), r2)
  1438. def pe_sub(r1, r2):
  1439. match (r1, r2):
  1440. case (Constant(n1), Constant(n2)):
  1441. return Constant(n1 - n2)
  1442. case _:
  1443. return BinOp(r1, Sub(), r2)
  1444. def pe_exp(e):
  1445. match e:
  1446. case BinOp(left, Add(), right):
  1447. return pe_add(pe_exp(left), pe_exp(right))
  1448. case BinOp(left, Sub(), right):
  1449. return pe_sub(pe_exp(left), pe_exp(right))
  1450. case UnaryOp(USub(), v):
  1451. return pe_neg(pe_exp(v))
  1452. case Constant(value):
  1453. return e
  1454. case Call(Name('input_int'), []):
  1455. return e
  1456. def pe_stmt(s):
  1457. match s:
  1458. case Expr(Call(Name('print'), [arg])):
  1459. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1460. case Expr(value):
  1461. return Expr(pe_exp(value))
  1462. def pe_P_int(p):
  1463. match p:
  1464. case Module(body):
  1465. new_body = [pe_stmt(s) for s in body]
  1466. return Module(new_body)
  1467. \end{lstlisting}
  1468. \fi}
  1469. \caption{A partial evaluator for \LangInt{}.}
  1470. \label{fig:pe-arith}
  1471. \end{figure}
  1472. To gain some confidence that the partial evaluator is correct, we can
  1473. test whether it produces programs that produce the same result as the
  1474. input programs. That is, we can test whether it satisfies Diagram
  1475. \ref{eq:compile-correct}.
  1476. %
  1477. {\if\edition\racketEd
  1478. The following code runs the partial evaluator on several examples and
  1479. tests the output program. The \texttt{parse-program} and
  1480. \texttt{assert} functions are defined in
  1481. Appendix~\ref{appendix:utilities}.\\
  1482. \begin{minipage}{1.0\textwidth}
  1483. \begin{lstlisting}
  1484. (define (test_pe p)
  1485. (assert "testing pe_Lint"
  1486. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1487. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1488. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1489. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1490. \end{lstlisting}
  1491. \end{minipage}
  1492. \fi}
  1493. % TODO: python version of testing the PE
  1494. \begin{exercise}\normalfont\normalsize
  1495. Create three programs in the \LangInt{} language and test whether
  1496. partially evaluating them with \code{pe\_Lint} and then
  1497. interpreting them with \code{interp\_Lint} gives the same result
  1498. as directly interpreting them with \code{interp\_Lint}.
  1499. \end{exercise}
  1500. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1501. \chapter{Integers and Variables}
  1502. \label{ch:Lvar}
  1503. This chapter is about compiling a subset of
  1504. \racket{Racket}\python{Python} to x86-64 assembly
  1505. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1506. integer arithmetic and local variables. We often refer to x86-64
  1507. simply as x86. The chapter begins with a description of the
  1508. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1509. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1510. large so we discuss only the instructions needed for compiling
  1511. \LangVar{}. We introduce more x86 instructions in later chapters.
  1512. After introducing \LangVar{} and x86, we reflect on their differences
  1513. and come up with a plan to break down the translation from \LangVar{}
  1514. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1515. rest of the sections in this chapter give detailed hints regarding
  1516. each step. We hope to give enough hints that the well-prepared
  1517. reader, together with a few friends, can implement a compiler from
  1518. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1519. the scale of this first compiler, the instructor solution for the
  1520. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1521. code.
  1522. \section{The \LangVar{} Language}
  1523. \label{sec:s0}
  1524. \index{subject}{variable}
  1525. The \LangVar{} language extends the \LangInt{} language with
  1526. variables. The concrete syntax of the \LangVar{} language is defined
  1527. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1528. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1529. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1530. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1531. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1532. syntax of \LangVar{} includes the \racket{\key{Program}
  1533. struct}\python{\key{Module} instance} to mark the top of the
  1534. program.
  1535. %% The $\itm{info}$
  1536. %% field of the \key{Program} structure contains an \emph{association
  1537. %% list} (a list of key-value pairs) that is used to communicate
  1538. %% auxiliary data from one compiler pass the next.
  1539. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1540. exhibit several compilation techniques.
  1541. \newcommand{\LvarGrammarRacket}{
  1542. \begin{array}{rcl}
  1543. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1544. \end{array}
  1545. }
  1546. \newcommand{\LvarASTRacket}{
  1547. \begin{array}{rcl}
  1548. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1549. \end{array}
  1550. }
  1551. \newcommand{\LvarGrammarPython}{
  1552. \begin{array}{rcl}
  1553. \Exp &::=& \Var{} \\
  1554. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1555. \end{array}
  1556. }
  1557. \newcommand{\LvarASTPython}{
  1558. \begin{array}{rcl}
  1559. \Exp{} &::=& \VAR{\Var{}} \\
  1560. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1561. \end{array}
  1562. }
  1563. \begin{figure}[tp]
  1564. \centering
  1565. \fbox{
  1566. \begin{minipage}{0.96\textwidth}
  1567. {\if\edition\racketEd
  1568. \[
  1569. \begin{array}{l}
  1570. \gray{\LintGrammarRacket{}} \\ \hline
  1571. \LvarGrammarRacket{} \\
  1572. \begin{array}{rcl}
  1573. \LangVarM{} &::=& \Exp
  1574. \end{array}
  1575. \end{array}
  1576. \]
  1577. \fi}
  1578. {\if\edition\pythonEd
  1579. \[
  1580. \begin{array}{l}
  1581. \gray{\LintGrammarPython} \\ \hline
  1582. \LvarGrammarPython \\
  1583. \begin{array}{rcl}
  1584. \LangVarM{} &::=& \Stmt^{*}
  1585. \end{array}
  1586. \end{array}
  1587. \]
  1588. \fi}
  1589. \end{minipage}
  1590. }
  1591. \caption{The concrete syntax of \LangVar{}.}
  1592. \label{fig:Lvar-concrete-syntax}
  1593. \end{figure}
  1594. \begin{figure}[tp]
  1595. \centering
  1596. \fbox{
  1597. \begin{minipage}{0.96\textwidth}
  1598. {\if\edition\racketEd
  1599. \[
  1600. \begin{array}{l}
  1601. \gray{\LintASTRacket{}} \\ \hline
  1602. \LvarASTRacket \\
  1603. \begin{array}{rcl}
  1604. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1605. \end{array}
  1606. \end{array}
  1607. \]
  1608. \fi}
  1609. {\if\edition\pythonEd
  1610. \[
  1611. \begin{array}{l}
  1612. \gray{\LintASTPython}\\ \hline
  1613. \LvarASTPython \\
  1614. \begin{array}{rcl}
  1615. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1616. \end{array}
  1617. \end{array}
  1618. \]
  1619. \fi}
  1620. \end{minipage}
  1621. }
  1622. \caption{The abstract syntax of \LangVar{}.}
  1623. \label{fig:Lvar-syntax}
  1624. \end{figure}
  1625. {\if\edition\racketEd
  1626. Let us dive further into the syntax and semantics of the \LangVar{}
  1627. language. The \key{let} feature defines a variable for use within its
  1628. body and initializes the variable with the value of an expression.
  1629. The abstract syntax for \key{let} is defined in
  1630. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1631. \begin{lstlisting}
  1632. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1633. \end{lstlisting}
  1634. For example, the following program initializes \code{x} to $32$ and then
  1635. evaluates the body \code{(+ 10 x)}, producing $42$.
  1636. \begin{lstlisting}
  1637. (let ([x (+ 12 20)]) (+ 10 x))
  1638. \end{lstlisting}
  1639. \fi}
  1640. %
  1641. {\if\edition\pythonEd
  1642. %
  1643. The \LangVar{} language includes assignment statements, which define a
  1644. variable for use in later statements and initializes the variable with
  1645. the value of an expression. The abstract syntax for assignment is
  1646. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1647. assignment is
  1648. \begin{lstlisting}
  1649. |$\itm{var}$| = |$\itm{exp}$|
  1650. \end{lstlisting}
  1651. For example, the following program initializes the variable \code{x}
  1652. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1653. \begin{lstlisting}
  1654. x = 12 + 20
  1655. print(10 + x)
  1656. \end{lstlisting}
  1657. \fi}
  1658. {\if\edition\racketEd
  1659. %
  1660. When there are multiple \key{let}'s for the same variable, the closest
  1661. enclosing \key{let} is used. That is, variable definitions overshadow
  1662. prior definitions. Consider the following program with two \key{let}'s
  1663. that define two variables named \code{x}. Can you figure out the
  1664. result?
  1665. \begin{lstlisting}
  1666. (let ([x 32]) (+ (let ([x 10]) x) x))
  1667. \end{lstlisting}
  1668. For the purposes of depicting which variable occurences correspond to
  1669. which definitions, the following shows the \code{x}'s annotated with
  1670. subscripts to distinguish them. Double check that your answer for the
  1671. above is the same as your answer for this annotated version of the
  1672. program.
  1673. \begin{lstlisting}
  1674. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1675. \end{lstlisting}
  1676. The initializing expression is always evaluated before the body of the
  1677. \key{let}, so in the following, the \key{read} for \code{x} is
  1678. performed before the \key{read} for \code{y}. Given the input
  1679. $52$ then $10$, the following produces $42$ (not $-42$).
  1680. \begin{lstlisting}
  1681. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1682. \end{lstlisting}
  1683. \fi}
  1684. \subsection{Extensible Interpreters via Method Overriding}
  1685. \label{sec:extensible-interp}
  1686. To prepare for discussing the interpreter of \LangVar{}, we explain
  1687. why we implement it in an object-oriented style. Throughout this book
  1688. we define many interpreters, one for each of language that we
  1689. study. Because each language builds on the prior one, there is a lot
  1690. of commonality between these interpreters. We want to write down the
  1691. common parts just once instead of many times. A naive
  1692. interpreter for \LangVar{} would handle the
  1693. \racket{cases for variables and \code{let}}
  1694. \python{case for variables}
  1695. but dispatch to an interpreter for \LangInt{}
  1696. in the rest of the cases. The following code sketches this idea. (We
  1697. explain the \code{env} parameter soon, in
  1698. Section~\ref{sec:interp-Lvar}.)
  1699. \begin{center}
  1700. {\if\edition\racketEd
  1701. \begin{minipage}{0.45\textwidth}
  1702. \begin{lstlisting}
  1703. (define ((interp_Lint env) e)
  1704. (match e
  1705. [(Prim '- (list e1))
  1706. (fx- 0 ((interp_Lint env) e1))]
  1707. ...))
  1708. \end{lstlisting}
  1709. \end{minipage}
  1710. \begin{minipage}{0.45\textwidth}
  1711. \begin{lstlisting}
  1712. (define ((interp_Lvar 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 ((interp_Lint env) e)]))
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. \fi}
  1724. {\if\edition\pythonEd
  1725. \begin{minipage}{0.45\textwidth}
  1726. \begin{lstlisting}
  1727. def interp_Lint(e, env):
  1728. match e:
  1729. case UnaryOp(USub(), e1):
  1730. return - interp_Lint(e1, env)
  1731. ...
  1732. \end{lstlisting}
  1733. \end{minipage}
  1734. \begin{minipage}{0.45\textwidth}
  1735. \begin{lstlisting}
  1736. def interp_Lvar(e, env):
  1737. match e:
  1738. case Name(id):
  1739. return env[id]
  1740. case _:
  1741. return interp_Lint(e, env)
  1742. \end{lstlisting}
  1743. \end{minipage}
  1744. \fi}
  1745. \end{center}
  1746. The problem with this naive approach is that it does not handle
  1747. situations in which an \LangVar{} feature, such as a variable, is
  1748. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1749. the following program.
  1750. %
  1751. {\if\edition\racketEd
  1752. \begin{lstlisting}
  1753. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1754. \end{lstlisting}
  1755. \fi}
  1756. {\if\edition\pythonEd
  1757. \begin{lstlisting}
  1758. y = 10
  1759. print(-y)
  1760. \end{lstlisting}
  1761. \fi}
  1762. %
  1763. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1764. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1765. then it recursively calls \code{interp\_Lint} again on its argument.
  1766. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1767. an error!
  1768. To make our interpreters extensible we need something called
  1769. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1770. recursive knot is delayed to when the functions are
  1771. composed. Object-oriented languages provide open recursion via
  1772. method overriding\index{subject}{method overriding}. The
  1773. following code uses method overriding to interpret \LangInt{} and
  1774. \LangVar{} using
  1775. %
  1776. \racket{the
  1777. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1778. \index{subject}{class} feature of Racket.}
  1779. %
  1780. \python{a Python \code{class} definition.}
  1781. %
  1782. We define one class for each language and define a method for
  1783. interpreting expressions inside each class. The class for \LangVar{}
  1784. inherits from the class for \LangInt{} and the method
  1785. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1786. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1787. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1788. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1789. \code{interp\_exp} in \LangInt{}.
  1790. \begin{center}
  1791. \hspace{-20pt}
  1792. {\if\edition\racketEd
  1793. \begin{minipage}{0.45\textwidth}
  1794. \begin{lstlisting}
  1795. (define interp-Lint-class
  1796. (class object%
  1797. (define/public ((interp_exp env) e)
  1798. (match e
  1799. [(Prim '- (list e))
  1800. (fx- 0 ((interp_exp env) e))]
  1801. ...))
  1802. ...))
  1803. \end{lstlisting}
  1804. \end{minipage}
  1805. \begin{minipage}{0.45\textwidth}
  1806. \begin{lstlisting}
  1807. (define interp-Lvar-class
  1808. (class interp-Lint-class
  1809. (define/override ((interp_exp env) e)
  1810. (match e
  1811. [(Var x)
  1812. (dict-ref env x)]
  1813. [(Let x e body)
  1814. (define v ((interp_exp env) e))
  1815. (define env^ (dict-set env x v))
  1816. ((interp_exp env^) body)]
  1817. [else
  1818. (super (interp_exp env) e)]))
  1819. ...
  1820. ))
  1821. \end{lstlisting}
  1822. \end{minipage}
  1823. \fi}
  1824. {\if\edition\pythonEd
  1825. \begin{minipage}{0.45\textwidth}
  1826. \begin{lstlisting}
  1827. class InterpLint:
  1828. def interp_exp(e):
  1829. match e:
  1830. case UnaryOp(USub(), e1):
  1831. return -self.interp_exp(e1)
  1832. ...
  1833. ...
  1834. \end{lstlisting}
  1835. \end{minipage}
  1836. \begin{minipage}{0.45\textwidth}
  1837. \begin{lstlisting}
  1838. def InterpLvar(InterpLint):
  1839. def interp_exp(e):
  1840. match e:
  1841. case Name(id):
  1842. return env[id]
  1843. case _:
  1844. return super().interp_exp(e)
  1845. ...
  1846. \end{lstlisting}
  1847. \end{minipage}
  1848. \fi}
  1849. \end{center}
  1850. Getting back to the troublesome example, repeated here:
  1851. {\if\edition\racketEd
  1852. \begin{lstlisting}
  1853. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1854. \end{lstlisting}
  1855. \fi}
  1856. {\if\edition\pythonEd
  1857. \begin{lstlisting}
  1858. y = 10
  1859. print(-y)
  1860. \end{lstlisting}
  1861. \fi}
  1862. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1863. \racket{on this expression,}
  1864. \python{on the \code{-y} expression,}
  1865. %
  1866. call it \code{e0}, by creating an object of the \LangVar{} class
  1867. and calling the \code{interp\_exp} method.
  1868. {\if\edition\racketEd
  1869. \begin{lstlisting}
  1870. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1871. \end{lstlisting}
  1872. \fi}
  1873. {\if\edition\pythonEd
  1874. \begin{lstlisting}
  1875. InterpLvar().interp_exp(e0)
  1876. \end{lstlisting}
  1877. \fi}
  1878. \noindent To process the \code{-} operator, the default case of
  1879. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1880. method in \LangInt{}. But then for the recursive method call, it
  1881. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1882. \code{Var} node is handled correctly. Thus, method overriding gives us
  1883. the open recursion that we need to implement our interpreters in an
  1884. extensible way.
  1885. \subsection{Definitional Interpreter for \LangVar{}}
  1886. \label{sec:interp-Lvar}
  1887. {\if\edition\racketEd
  1888. \begin{figure}[tp]
  1889. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1890. \small
  1891. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1892. An \emph{association list} (alist) is a list of key-value pairs.
  1893. For example, we can map people to their ages with an alist.
  1894. \index{subject}{alist}\index{subject}{association list}
  1895. \begin{lstlisting}[basicstyle=\ttfamily]
  1896. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1897. \end{lstlisting}
  1898. The \emph{dictionary} interface is for mapping keys to values.
  1899. Every alist implements this interface. \index{subject}{dictionary} The package
  1900. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1901. provides many functions for working with dictionaries. Here
  1902. are a few of them:
  1903. \begin{description}
  1904. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1905. returns the value associated with the given $\itm{key}$.
  1906. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1907. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1908. but otherwise is the same as $\itm{dict}$.
  1909. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1910. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1911. of keys and values in $\itm{dict}$. For example, the following
  1912. creates a new alist in which the ages are incremented.
  1913. \end{description}
  1914. \vspace{-10pt}
  1915. \begin{lstlisting}[basicstyle=\ttfamily]
  1916. (for/list ([(k v) (in-dict ages)])
  1917. (cons k (add1 v)))
  1918. \end{lstlisting}
  1919. \end{tcolorbox}
  1920. %\end{wrapfigure}
  1921. \caption{Association lists implement the dictionary interface.}
  1922. \label{fig:alist}
  1923. \end{figure}
  1924. \fi}
  1925. Having justified the use of classes and methods to implement
  1926. interpreters, we revisit the definitional interpreter for \LangInt{}
  1927. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1928. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1929. interpreter for \LangVar{} adds two new \key{match} cases for
  1930. variables and \racket{\key{let}}\python{assignment}. For
  1931. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1932. value bound to a variable to all the uses of the variable. To
  1933. accomplish this, we maintain a mapping from variables to values
  1934. called an \emph{environment}\index{subject}{environment}.
  1935. %
  1936. We use
  1937. %
  1938. \racket{an association list (alist) }%
  1939. %
  1940. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1941. %
  1942. to represent the environment.
  1943. %
  1944. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1945. and the \code{racket/dict} package.}
  1946. %
  1947. The \code{interp\_exp} function takes the current environment,
  1948. \code{env}, as an extra parameter. When the interpreter encounters a
  1949. variable, it looks up the corresponding value in the dictionary.
  1950. %
  1951. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1952. initializing expression, extends the environment with the result
  1953. value bound to the variable, using \code{dict-set}, then evaluates
  1954. the body of the \key{Let}.}
  1955. %
  1956. \python{When the interpreter encounters an assignment, it evaluates
  1957. the initializing expression and then associates the resulting value
  1958. with the variable in the environment.}
  1959. \begin{figure}[tp]
  1960. {\if\edition\racketEd
  1961. \begin{lstlisting}
  1962. (define interp-Lint-class
  1963. (class object%
  1964. (super-new)
  1965. (define/public ((interp_exp env) e)
  1966. (match e
  1967. [(Int n) n]
  1968. [(Prim 'read '())
  1969. (define r (read))
  1970. (cond [(fixnum? r) r]
  1971. [else (error 'interp_exp "expected an integer" r)])]
  1972. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1973. [(Prim '+ (list e1 e2))
  1974. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1975. [(Prim '- (list e1 e2))
  1976. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1977. (define/public (interp_program p)
  1978. (match p
  1979. [(Program '() e) ((interp_exp '()) e)]))
  1980. ))
  1981. \end{lstlisting}
  1982. \fi}
  1983. {\if\edition\pythonEd
  1984. \begin{lstlisting}
  1985. class InterpLint:
  1986. def interp_exp(self, e, env):
  1987. match e:
  1988. case BinOp(left, Add(), right):
  1989. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1990. case BinOp(left, Sub(), right):
  1991. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1992. case UnaryOp(USub(), v):
  1993. return - self.interp_exp(v, env)
  1994. case Constant(value):
  1995. return value
  1996. case Call(Name('input_int'), []):
  1997. return int(input())
  1998. def interp_stmts(self, ss, env):
  1999. if len(ss) == 0:
  2000. return
  2001. match ss[0]:
  2002. case Expr(Call(Name('print'), [arg])):
  2003. print(self.interp_exp(arg, env), end='')
  2004. return self.interp_stmts(ss[1:], env)
  2005. case Expr(value):
  2006. self.interp_exp(value, env)
  2007. return self.interp_stmts(ss[1:], env)
  2008. def interp(self, p):
  2009. match p:
  2010. case Module(body):
  2011. self.interp_stmts(body, {})
  2012. def interp_Lint(p):
  2013. return InterpLint().interp(p)
  2014. \end{lstlisting}
  2015. \fi}
  2016. \caption{Interpreter for \LangInt{} as a class.}
  2017. \label{fig:interp-Lint-class}
  2018. \end{figure}
  2019. \begin{figure}[tp]
  2020. {\if\edition\racketEd
  2021. \begin{lstlisting}
  2022. (define interp-Lvar-class
  2023. (class interp-Lint-class
  2024. (super-new)
  2025. (define/override ((interp_exp env) e)
  2026. (match e
  2027. [(Var x) (dict-ref env x)]
  2028. [(Let x e body)
  2029. (define new-env (dict-set env x ((interp_exp env) e)))
  2030. ((interp_exp new-env) body)]
  2031. [else ((super interp-exp env) e)]))
  2032. ))
  2033. (define (interp_Lvar p)
  2034. (send (new interp-Lvar-class) interp_program p))
  2035. \end{lstlisting}
  2036. \fi}
  2037. {\if\edition\pythonEd
  2038. \begin{lstlisting}
  2039. class InterpLvar(InterpLint):
  2040. def interp_exp(self, e, env):
  2041. match e:
  2042. case Name(id):
  2043. return env[id]
  2044. case _:
  2045. return super().interp_exp(e, env)
  2046. def interp_stmts(self, ss, env):
  2047. if len(ss) == 0:
  2048. return
  2049. match ss[0]:
  2050. case Assign([lhs], value):
  2051. env[lhs.id] = self.interp_exp(value, env)
  2052. return self.interp_stmts(ss[1:], env)
  2053. case _:
  2054. return super().interp_stmts(ss, env)
  2055. def interp_Lvar(p):
  2056. return InterpLvar().interp(p)
  2057. \end{lstlisting}
  2058. \fi}
  2059. \caption{Interpreter for the \LangVar{} language.}
  2060. \label{fig:interp-Lvar}
  2061. \end{figure}
  2062. The goal for this chapter is to implement a compiler that translates
  2063. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2064. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2065. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2066. That is, they output the same integer $n$. We depict this correctness
  2067. criteria in the following diagram.
  2068. \[
  2069. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2070. \node (p1) at (0, 0) {$P_1$};
  2071. \node (p2) at (4, 0) {$P_2$};
  2072. \node (o) at (4, -2) {$n$};
  2073. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2074. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2075. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2076. \end{tikzpicture}
  2077. \]
  2078. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2079. compiling \LangVar{}.
  2080. \section{The \LangXInt{} Assembly Language}
  2081. \label{sec:x86}
  2082. \index{subject}{x86}
  2083. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2084. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2085. assembler.
  2086. %
  2087. A program begins with a \code{main} label followed by a sequence of
  2088. instructions. The \key{globl} directive says that the \key{main}
  2089. procedure is externally visible, which is necessary so that the
  2090. operating system can call it.
  2091. %
  2092. An x86 program is stored in the computer's memory. For our purposes,
  2093. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2094. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2095. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2096. the address of the next instruction to be executed. For most
  2097. instructions, the program counter is incremented after the instruction
  2098. is executed, so it points to the next instruction in memory. Most x86
  2099. instructions take two operands, where each operand is either an
  2100. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2101. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2102. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2103. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2104. && \key{r8} \MID \key{r9} \MID \key{r10}
  2105. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2106. \MID \key{r14} \MID \key{r15}}
  2107. \newcommand{\GrammarXInt}{
  2108. \begin{array}{rcl}
  2109. \Reg &::=& \allregisters{} \\
  2110. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2111. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2112. \key{subq} \; \Arg\key{,} \Arg \MID
  2113. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2114. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2115. \key{callq} \; \mathit{label} \MID
  2116. \key{retq} \MID
  2117. \key{jmp}\,\itm{label} \MID \\
  2118. && \itm{label}\key{:}\; \Instr
  2119. \end{array}
  2120. }
  2121. \begin{figure}[tp]
  2122. \fbox{
  2123. \begin{minipage}{0.96\textwidth}
  2124. {\if\edition\racketEd
  2125. \[
  2126. \begin{array}{l}
  2127. \GrammarXInt \\
  2128. \begin{array}{lcl}
  2129. \LangXIntM{} &::= & \key{.globl main}\\
  2130. & & \key{main:} \; \Instr\ldots
  2131. \end{array}
  2132. \end{array}
  2133. \]
  2134. \fi}
  2135. {\if\edition\pythonEd
  2136. \[
  2137. \begin{array}{lcl}
  2138. \Reg &::=& \allregisters{} \\
  2139. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2140. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2141. \key{subq} \; \Arg\key{,} \Arg \MID
  2142. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2143. && \key{callq} \; \mathit{label} \MID
  2144. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2145. \LangXIntM{} &::= & \key{.globl main}\\
  2146. & & \key{main:} \; \Instr^{*}
  2147. \end{array}
  2148. \]
  2149. \fi}
  2150. \end{minipage}
  2151. }
  2152. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2153. \label{fig:x86-int-concrete}
  2154. \end{figure}
  2155. A register is a special kind of variable that holds a 64-bit
  2156. value. There are 16 general-purpose registers in the computer and
  2157. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2158. is written with a \key{\%} followed by the register name, such as
  2159. \key{\%rax}.
  2160. An immediate value is written using the notation \key{\$}$n$ where $n$
  2161. is an integer.
  2162. %
  2163. %
  2164. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2165. which obtains the address stored in register $r$ and then adds $n$
  2166. bytes to the address. The resulting address is used to load or store
  2167. to memory depending on whether it occurs as a source or destination
  2168. argument of an instruction.
  2169. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2170. source $s$ and destination $d$, applies the arithmetic operation, then
  2171. writes the result back to the destination $d$. \index{subject}{instruction}
  2172. %
  2173. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2174. stores the result in $d$.
  2175. %
  2176. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2177. specified by the label and $\key{retq}$ returns from a procedure to
  2178. its caller.
  2179. %
  2180. We discuss procedure calls in more detail later in this chapter and in
  2181. Chapter~\ref{ch:Lfun}.
  2182. %
  2183. The last letter \key{q} indicates that these instructions operate on
  2184. quadwords, i.e., 64-bit values.
  2185. %
  2186. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2187. counter to the address of the instruction after the specified
  2188. label.}
  2189. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2190. all of the x86 instructions used in this book.
  2191. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2192. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2193. \lstinline{movq $10, %rax}
  2194. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2195. adds $32$ to the $10$ in \key{rax} and
  2196. puts the result, $42$, back into \key{rax}.
  2197. %
  2198. The last instruction \key{retq} finishes the \key{main} function by
  2199. returning the integer in \key{rax} to the operating system. The
  2200. operating system interprets this integer as the program's exit
  2201. code. By convention, an exit code of 0 indicates that a program
  2202. completed successfully, and all other exit codes indicate various
  2203. errors.
  2204. %
  2205. \racket{Nevertheless, in this book we return the result of the program
  2206. as the exit code.}
  2207. \begin{figure}[tbp]
  2208. \begin{lstlisting}
  2209. .globl main
  2210. main:
  2211. movq $10, %rax
  2212. addq $32, %rax
  2213. retq
  2214. \end{lstlisting}
  2215. \caption{An x86 program that computes
  2216. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2217. \label{fig:p0-x86}
  2218. \end{figure}
  2219. We exhibit the use of memory for storing intermediate results in the
  2220. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2221. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2222. uses a region of memory called the \emph{procedure call stack} (or
  2223. \emph{stack} for
  2224. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2225. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2226. for each procedure call. The memory layout for an individual frame is
  2227. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2228. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2229. address of the item at the top of the stack. In general, we use the
  2230. term \emph{pointer}\index{subject}{pointer} for something that
  2231. contains an address. The stack grows downward in memory, so we
  2232. increase the size of the stack by subtracting from the stack pointer.
  2233. In the context of a procedure call, the \emph{return
  2234. address}\index{subject}{return address} is the instruction after the
  2235. call instruction on the caller side. The function call instruction,
  2236. \code{callq}, pushes the return address onto the stack prior to
  2237. jumping to the procedure. The register \key{rbp} is the \emph{base
  2238. pointer}\index{subject}{base pointer} and is used to access
  2239. variables that are stored in the frame of the current procedure call.
  2240. The base pointer of the caller is stored after the return address. In
  2241. Figure~\ref{fig:frame} we number the variables from $1$ to
  2242. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2243. at $-16\key{(\%rbp)}$, etc.
  2244. \begin{figure}[tbp]
  2245. {\if\edition\racketEd
  2246. \begin{lstlisting}
  2247. start:
  2248. movq $10, -8(%rbp)
  2249. negq -8(%rbp)
  2250. movq -8(%rbp), %rax
  2251. addq $52, %rax
  2252. jmp conclusion
  2253. .globl main
  2254. main:
  2255. pushq %rbp
  2256. movq %rsp, %rbp
  2257. subq $16, %rsp
  2258. jmp start
  2259. conclusion:
  2260. addq $16, %rsp
  2261. popq %rbp
  2262. retq
  2263. \end{lstlisting}
  2264. \fi}
  2265. {\if\edition\pythonEd
  2266. \begin{lstlisting}
  2267. .globl main
  2268. main:
  2269. pushq %rbp
  2270. movq %rsp, %rbp
  2271. subq $16, %rsp
  2272. movq $10, -8(%rbp)
  2273. negq -8(%rbp)
  2274. movq -8(%rbp), %rax
  2275. addq $52, %rax
  2276. addq $16, %rsp
  2277. popq %rbp
  2278. retq
  2279. \end{lstlisting}
  2280. \fi}
  2281. \caption{An x86 program that computes
  2282. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2283. \label{fig:p1-x86}
  2284. \end{figure}
  2285. \begin{figure}[tbp]
  2286. \centering
  2287. \begin{tabular}{|r|l|} \hline
  2288. Position & Contents \\ \hline
  2289. 8(\key{\%rbp}) & return address \\
  2290. 0(\key{\%rbp}) & old \key{rbp} \\
  2291. -8(\key{\%rbp}) & variable $1$ \\
  2292. -16(\key{\%rbp}) & variable $2$ \\
  2293. \ldots & \ldots \\
  2294. 0(\key{\%rsp}) & variable $n$\\ \hline
  2295. \end{tabular}
  2296. \caption{Memory layout of a frame.}
  2297. \label{fig:frame}
  2298. \end{figure}
  2299. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2300. control is transferred from the operating system to the \code{main}
  2301. function. The operating system issues a \code{callq main} instruction
  2302. which pushes its return address on the stack and then jumps to
  2303. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2304. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2305. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2306. alignment (because the \code{callq} pushed the return address). The
  2307. first three instructions are the typical
  2308. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2309. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2310. pointer \code{rsp} and then saves the base pointer of the caller at
  2311. address \code{rsp} on the stack. The next instruction \code{movq
  2312. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2313. which is pointing at the location of the old base pointer. The
  2314. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2315. make enough room for storing variables. This program needs one
  2316. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2317. 16-byte aligned and we're ready to make calls to other functions.
  2318. \racket{The last instruction of the prelude is \code{jmp start}, which
  2319. transfers control to the instructions that were generated from the
  2320. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2321. \racket{The first instruction under the \code{start} label is}
  2322. %
  2323. \python{The first instruction after the prelude is}
  2324. %
  2325. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2326. %
  2327. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2328. $1$ to $-10$.
  2329. %
  2330. The next instruction moves the $-10$ from variable $1$ into the
  2331. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2332. the value in \code{rax}, updating its contents to $42$.
  2333. \racket{The three instructions under the label \code{conclusion} are the
  2334. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2335. %
  2336. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2337. \code{main} function consists of the last three instructions.}
  2338. %
  2339. The first two restore the \code{rsp} and \code{rbp} registers to the
  2340. state they were in at the beginning of the procedure. In particular,
  2341. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2342. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2343. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2344. \key{retq}, jumps back to the procedure that called this one and adds
  2345. $8$ to the stack pointer.
  2346. Our compiler needs a convenient representation for manipulating x86
  2347. programs, so we define an abstract syntax for x86 in
  2348. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2349. \LangXInt{}.
  2350. %
  2351. {\if\edition\pythonEd%
  2352. The main difference compared to the concrete syntax of \LangXInt{}
  2353. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2354. names, and register names are explicitly represented by strings.
  2355. \fi} %
  2356. {\if\edition\racketEd
  2357. The main difference compared to the concrete syntax of \LangXInt{}
  2358. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2359. front of every instruction. Instead instructions are grouped into
  2360. \emph{basic blocks}\index{subject}{basic block} with a
  2361. label associated with every basic block, which is why the \key{X86Program}
  2362. struct includes an alist mapping labels to basic blocks. The reason for this
  2363. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2364. introduce conditional branching. The \code{Block} structure includes
  2365. an $\itm{info}$ field that is not needed for this chapter but becomes
  2366. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2367. $\itm{info}$ field should contain an empty list.
  2368. \fi}
  2369. %
  2370. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2371. node includes an integer for representing the arity of the function,
  2372. i.e., the number of arguments, which is helpful to know during
  2373. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2374. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2375. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2376. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2377. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2378. \MID \skey{r14} \MID \skey{r15}}
  2379. \newcommand{\ASTXIntRacket}{
  2380. \begin{array}{lcl}
  2381. \Reg &::=& \allregisters{} \\
  2382. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2383. \MID \DEREF{\Reg}{\Int} \\
  2384. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2385. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2386. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2387. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2388. \MID \PUSHQ{\Arg}
  2389. \MID \POPQ{\Arg} \\
  2390. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2391. \MID \RETQ{}
  2392. \MID \JMP{\itm{label}} \\
  2393. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2394. \end{array}
  2395. }
  2396. \begin{figure}[tp]
  2397. \fbox{
  2398. \begin{minipage}{0.94\textwidth}
  2399. \small
  2400. {\if\edition\racketEd
  2401. \[
  2402. \begin{array}{l}
  2403. \ASTXIntRacket \\
  2404. \begin{array}{lcl}
  2405. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2406. \end{array}
  2407. \end{array}
  2408. \]
  2409. \fi}
  2410. {\if\edition\pythonEd
  2411. \[
  2412. \begin{array}{lcl}
  2413. \Reg &::=& \allastregisters{} \\
  2414. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2415. \MID \DEREF{\Reg}{\Int} \\
  2416. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2417. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2418. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2419. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2420. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2421. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2422. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2423. \end{array}
  2424. \]
  2425. \fi}
  2426. \end{minipage}
  2427. }
  2428. \caption{The abstract syntax of \LangXInt{} assembly.}
  2429. \label{fig:x86-int-ast}
  2430. \end{figure}
  2431. \section{Planning the trip to x86}
  2432. \label{sec:plan-s0-x86}
  2433. To compile one language to another it helps to focus on the
  2434. differences between the two languages because the compiler will need
  2435. to bridge those differences. What are the differences between \LangVar{}
  2436. and x86 assembly? Here are some of the most important ones:
  2437. \begin{enumerate}
  2438. \item x86 arithmetic instructions typically have two arguments and
  2439. update the second argument in place. In contrast, \LangVar{}
  2440. arithmetic operations take two arguments and produce a new value.
  2441. An x86 instruction may have at most one memory-accessing argument.
  2442. Furthermore, some x86 instructions place special restrictions on
  2443. their arguments.
  2444. \item An argument of an \LangVar{} operator can be a deeply-nested
  2445. expression, whereas x86 instructions restrict their arguments to be
  2446. integer constants, registers, and memory locations.
  2447. {\if\edition\racketEd
  2448. \item The order of execution in x86 is explicit in the syntax: a
  2449. sequence of instructions and jumps to labeled positions, whereas in
  2450. \LangVar{} the order of evaluation is a left-to-right depth-first
  2451. traversal of the abstract syntax tree.
  2452. \fi}
  2453. \item A program in \LangVar{} can have any number of variables
  2454. whereas x86 has 16 registers and the procedure call stack.
  2455. {\if\edition\racketEd
  2456. \item Variables in \LangVar{} can shadow other variables with the
  2457. same name. In x86, registers have unique names and memory locations
  2458. have unique addresses.
  2459. \fi}
  2460. \end{enumerate}
  2461. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2462. down the problem into several steps, dealing with the above
  2463. differences one at a time. Each of these steps is called a \emph{pass}
  2464. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2465. %
  2466. This terminology comes from the way each step passes over, or
  2467. traverses, the AST of the program.
  2468. %
  2469. Furthermore, we follow the nanopass approach, which means we strive
  2470. for each pass to accomplish one clear objective (not two or three at
  2471. the same time).
  2472. %
  2473. We begin by sketching how we might implement each pass, and give them
  2474. names. We then figure out an ordering of the passes and the
  2475. input/output language for each pass. The very first pass has
  2476. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2477. its output language. In between we can choose whichever language is
  2478. most convenient for expressing the output of each pass, whether that
  2479. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2480. our own design. Finally, to implement each pass we write one
  2481. recursive function per non-terminal in the grammar of the input
  2482. language of the pass. \index{subject}{intermediate language}
  2483. Our compiler for \LangVar{} consists of the following passes.
  2484. %
  2485. \begin{description}
  2486. {\if\edition\racketEd
  2487. \item[\key{uniquify}] deals with the shadowing of variables by
  2488. renaming every variable to a unique name.
  2489. \fi}
  2490. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2491. of a primitive operation or function call is a variable or integer,
  2492. that is, an \emph{atomic} expression. We refer to non-atomic
  2493. expressions as \emph{complex}. This pass introduces temporary
  2494. variables to hold the results of complex
  2495. subexpressions.\index{subject}{atomic
  2496. expression}\index{subject}{complex expression}%
  2497. {\if\edition\racketEd
  2498. \item[\key{explicate\_control}] makes the execution order of the
  2499. program explicit. It converts the abstract syntax tree
  2500. representation into a graph in which each node is a labeled sequence
  2501. of statements and the edges are \code{goto} statements.
  2502. \fi}
  2503. \item[\key{select\_instructions}] handles the difference between
  2504. \LangVar{} operations and x86 instructions. This pass converts each
  2505. \LangVar{} operation to a short sequence of instructions that
  2506. accomplishes the same task.
  2507. \item[\key{assign\_homes}] replaces variables with registers or stack
  2508. locations.
  2509. \end{description}
  2510. %
  2511. {\if\edition\racketEd
  2512. %
  2513. Our treatment of \code{remove\_complex\_operands} and
  2514. \code{explicate\_control} as separate passes is an example of the
  2515. nanopass approach\footnote{For analogous decompositions of the
  2516. translation into continuation passing style, see the work of
  2517. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2518. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2519. %
  2520. \fi}
  2521. The next question is: in what order should we apply these passes? This
  2522. question can be challenging because it is difficult to know ahead of
  2523. time which orderings will be better (easier to implement, produce more
  2524. efficient code, etc.) so oftentimes trial-and-error is
  2525. involved. Nevertheless, we can plan ahead and make educated choices
  2526. regarding the ordering.
  2527. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2528. \key{uniquify}? The \key{uniquify} pass should come first because
  2529. \key{explicate\_control} changes all the \key{let}-bound variables to
  2530. become local variables whose scope is the entire program, which would
  2531. confuse variables with the same name.}
  2532. %
  2533. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2534. because the later removes the \key{let} form, but it is convenient to
  2535. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2536. %
  2537. \racket{The ordering of \key{uniquify} with respect to
  2538. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2539. \key{uniquify} to come first.}
  2540. The \key{select\_instructions} and \key{assign\_homes} passes are
  2541. intertwined.
  2542. %
  2543. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2544. passing arguments to functions and it is preferable to assign
  2545. parameters to their corresponding registers. This suggests that it
  2546. would be better to start with the \key{select\_instructions} pass,
  2547. which generates the instructions for argument passing, before
  2548. performing register allocation.
  2549. %
  2550. On the other hand, by selecting instructions first we may run into a
  2551. dead end in \key{assign\_homes}. Recall that only one argument of an
  2552. x86 instruction may be a memory access but \key{assign\_homes} might
  2553. be forced to assign both arguments to memory locations.
  2554. %
  2555. A sophisticated approach is to iteratively repeat the two passes until
  2556. a solution is found. However, to reduce implementation complexity we
  2557. recommend placing \key{select\_instructions} first, followed by the
  2558. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2559. that uses a reserved register to fix outstanding problems.
  2560. \begin{figure}[tbp]
  2561. {\if\edition\racketEd
  2562. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2563. \node (Lvar) at (0,2) {\large \LangVar{}};
  2564. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2565. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2566. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2567. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2568. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2569. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2570. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2571. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2572. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2573. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2574. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2575. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2576. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2577. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2578. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2579. \end{tikzpicture}
  2580. \fi}
  2581. {\if\edition\pythonEd
  2582. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2583. \node (Lvar) at (0,2) {\large \LangVar{}};
  2584. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2585. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2586. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2587. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2588. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2589. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2590. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2591. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2592. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2593. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2594. \end{tikzpicture}
  2595. \fi}
  2596. \caption{Diagram of the passes for compiling \LangVar{}. }
  2597. \label{fig:Lvar-passes}
  2598. \end{figure}
  2599. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2600. passes and identifies the input and output language of each pass.
  2601. %
  2602. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2603. language, which extends \LangXInt{} with an unbounded number of
  2604. program-scope variables and removes the restrictions regarding
  2605. instruction arguments.
  2606. %
  2607. The last pass, \key{prelude\_and\_conclusion}, places the program
  2608. instructions inside a \code{main} function with instructions for the
  2609. prelude and conclusion.
  2610. %
  2611. \racket{In the next section we discuss the \LangCVar{} intermediate
  2612. language that serves as the output of \code{explicate\_control}.}
  2613. %
  2614. The remainder of this chapter provides guidance on the implementation
  2615. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2616. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2617. %% are programs that are still in the \LangVar{} language, though the
  2618. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2619. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2620. %% %
  2621. %% The output of \code{explicate\_control} is in an intermediate language
  2622. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2623. %% syntax, which we introduce in the next section. The
  2624. %% \key{select-instruction} pass translates from \LangCVar{} to
  2625. %% \LangXVar{}. The \key{assign-homes} and
  2626. %% \key{patch-instructions}
  2627. %% passes input and output variants of x86 assembly.
  2628. \newcommand{\CvarGrammarRacket}{
  2629. \begin{array}{lcl}
  2630. \Atm &::=& \Int \MID \Var \\
  2631. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2632. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2633. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2634. \end{array}
  2635. }
  2636. \newcommand{\CvarASTRacket}{
  2637. \begin{array}{lcl}
  2638. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2639. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2640. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2641. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2642. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2643. \end{array}
  2644. }
  2645. {\if\edition\racketEd
  2646. \subsection{The \LangCVar{} Intermediate Language}
  2647. The output of \code{explicate\_control} is similar to the $C$
  2648. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2649. categories for expressions and statements, so we name it \LangCVar{}.
  2650. This style of intermediate language is also known as
  2651. \emph{three-address code}, to emphasize that the typical form of a
  2652. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2653. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2654. The concrete syntax for \LangCVar{} is defined in
  2655. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2656. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2657. %
  2658. The \LangCVar{} language supports the same operators as \LangVar{} but
  2659. the arguments of operators are restricted to atomic
  2660. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2661. assignment statements which can be executed in sequence using the
  2662. \key{Seq} form. A sequence of statements always ends with
  2663. \key{Return}, a guarantee that is baked into the grammar rules for
  2664. \itm{tail}. The naming of this non-terminal comes from the term
  2665. \emph{tail position}\index{subject}{tail position}, which refers to an
  2666. expression that is the last one to execute within a function or
  2667. program.
  2668. A \LangCVar{} program consists of an alist mapping labels to
  2669. tails. This is more general than necessary for the present chapter, as
  2670. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2671. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2672. there will be just one label, \key{start}, and the whole program is
  2673. its tail.
  2674. %
  2675. The $\itm{info}$ field of the \key{CProgram} form, after the
  2676. \code{explicate\_control} pass, contains a mapping from the symbol
  2677. \key{locals} to a list of variables, that is, a list of all the
  2678. variables used in the program. At the start of the program, these
  2679. variables are uninitialized; they become initialized on their first
  2680. assignment.
  2681. \begin{figure}[tbp]
  2682. \fbox{
  2683. \begin{minipage}{0.96\textwidth}
  2684. \[
  2685. \begin{array}{l}
  2686. \CvarGrammarRacket \\
  2687. \begin{array}{lcl}
  2688. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2689. \end{array}
  2690. \end{array}
  2691. \]
  2692. \end{minipage}
  2693. }
  2694. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2695. \label{fig:c0-concrete-syntax}
  2696. \end{figure}
  2697. \begin{figure}[tbp]
  2698. \fbox{
  2699. \begin{minipage}{0.96\textwidth}
  2700. \[
  2701. \begin{array}{l}
  2702. \CvarASTRacket \\
  2703. \begin{array}{lcl}
  2704. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2705. \end{array}
  2706. \end{array}
  2707. \]
  2708. \end{minipage}
  2709. }
  2710. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2711. \label{fig:c0-syntax}
  2712. \end{figure}
  2713. The definitional interpreter for \LangCVar{} is in the support code,
  2714. in the file \code{interp-Cvar.rkt}.
  2715. \fi}
  2716. {\if\edition\racketEd
  2717. \section{Uniquify Variables}
  2718. \label{sec:uniquify-Lvar}
  2719. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2720. programs in which every \key{let} binds a unique variable name. For
  2721. example, the \code{uniquify} pass should translate the program on the
  2722. left into the program on the right.
  2723. \begin{transformation}
  2724. \begin{lstlisting}
  2725. (let ([x 32])
  2726. (+ (let ([x 10]) x) x))
  2727. \end{lstlisting}
  2728. \compilesto
  2729. \begin{lstlisting}
  2730. (let ([x.1 32])
  2731. (+ (let ([x.2 10]) x.2) x.1))
  2732. \end{lstlisting}
  2733. \end{transformation}
  2734. The following is another example translation, this time of a program
  2735. with a \key{let} nested inside the initializing expression of another
  2736. \key{let}.
  2737. \begin{transformation}
  2738. \begin{lstlisting}
  2739. (let ([x (let ([x 4])
  2740. (+ x 1))])
  2741. (+ x 2))
  2742. \end{lstlisting}
  2743. \compilesto
  2744. \begin{lstlisting}
  2745. (let ([x.2 (let ([x.1 4])
  2746. (+ x.1 1))])
  2747. (+ x.2 2))
  2748. \end{lstlisting}
  2749. \end{transformation}
  2750. We recommend implementing \code{uniquify} by creating a structurally
  2751. recursive function named \code{uniquify\_exp} that mostly just copies
  2752. an expression. However, when encountering a \key{let}, it should
  2753. generate a unique name for the variable and associate the old name
  2754. with the new name in an alist.\footnote{The Racket function
  2755. \code{gensym} is handy for generating unique variable names.} The
  2756. \code{uniquify\_exp} function needs to access this alist when it gets
  2757. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2758. for the alist.
  2759. The skeleton of the \code{uniquify\_exp} function is shown in
  2760. Figure~\ref{fig:uniquify-Lvar}.
  2761. %% The function is curried so that it is
  2762. %% convenient to partially apply it to an alist and then apply it to
  2763. %% different expressions, as in the last case for primitive operations in
  2764. %% Figure~\ref{fig:uniquify-Lvar}.
  2765. The
  2766. %
  2767. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2768. %
  2769. form of Racket is useful for transforming the element of a list to
  2770. produce a new list.\index{subject}{for/list}
  2771. \begin{figure}[tbp]
  2772. \begin{lstlisting}
  2773. (define (uniquify_exp env)
  2774. (lambda (e)
  2775. (match e
  2776. [(Var x) ___]
  2777. [(Int n) (Int n)]
  2778. [(Let x e body) ___]
  2779. [(Prim op es)
  2780. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2781. (define (uniquify p)
  2782. (match p
  2783. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2784. \end{lstlisting}
  2785. \caption{Skeleton for the \key{uniquify} pass.}
  2786. \label{fig:uniquify-Lvar}
  2787. \end{figure}
  2788. \begin{exercise}
  2789. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2790. Complete the \code{uniquify} pass by filling in the blanks in
  2791. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2792. variables and for the \key{let} form in the file \code{compiler.rkt}
  2793. in the support code.
  2794. \end{exercise}
  2795. \begin{exercise}
  2796. \normalfont\normalsize
  2797. \label{ex:Lvar}
  2798. Create five \LangVar{} programs that exercise the most interesting
  2799. parts of the \key{uniquify} pass, that is, the programs should include
  2800. \key{let} forms, variables, and variables that shadow each other.
  2801. The five programs should be placed in the subdirectory named
  2802. \key{tests} and the file names should start with \code{var\_test\_}
  2803. followed by a unique integer and end with the file extension
  2804. \key{.rkt}.
  2805. %
  2806. The \key{run-tests.rkt} script in the support code checks whether the
  2807. output programs produce the same result as the input programs. The
  2808. script uses the \key{interp-tests} function
  2809. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2810. your \key{uniquify} pass on the example programs. The \code{passes}
  2811. parameter of \key{interp-tests} is a list that should have one entry
  2812. for each pass in your compiler. For now, define \code{passes} to
  2813. contain just one entry for \code{uniquify} as shown below.
  2814. \begin{lstlisting}
  2815. (define passes
  2816. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2817. \end{lstlisting}
  2818. Run the \key{run-tests.rkt} script in the support code to check
  2819. whether the output programs produce the same result as the input
  2820. programs.
  2821. \end{exercise}
  2822. \fi}
  2823. \section{Remove Complex Operands}
  2824. \label{sec:remove-complex-opera-Lvar}
  2825. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2826. into a restricted form in which the arguments of operations are atomic
  2827. expressions. Put another way, this pass removes complex
  2828. operands\index{subject}{complex operand}, such as the expression
  2829. \racket{\code{(- 10)}}\python{\code{-10}}
  2830. in the program below. This is accomplished by introducing a new
  2831. temporary variable, assigning the complex operand to the new
  2832. variable, and then using the new variable in place of the complex
  2833. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2834. right.
  2835. {\if\edition\racketEd
  2836. \begin{transformation}
  2837. % var_test_19.rkt
  2838. \begin{lstlisting}
  2839. (let ([x (+ 42 (- 10))])
  2840. (+ x 10))
  2841. \end{lstlisting}
  2842. \compilesto
  2843. \begin{lstlisting}
  2844. (let ([x (let ([tmp.1 (- 10)])
  2845. (+ 42 tmp.1))])
  2846. (+ x 10))
  2847. \end{lstlisting}
  2848. \end{transformation}
  2849. \fi}
  2850. {\if\edition\pythonEd
  2851. \begin{transformation}
  2852. \begin{lstlisting}
  2853. x = 42 + -10
  2854. print(x + 10)
  2855. \end{lstlisting}
  2856. \compilesto
  2857. \begin{lstlisting}
  2858. tmp_0 = -10
  2859. x = 42 + tmp_0
  2860. tmp_1 = x + 10
  2861. print(tmp_1)
  2862. \end{lstlisting}
  2863. \end{transformation}
  2864. \fi}
  2865. \newcommand{\LvarMonadASTRacket}{
  2866. \begin{array}{rcl}
  2867. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2868. \Exp &::=& \Atm \MID \READ{} \\
  2869. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2870. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2871. \end{array}
  2872. }
  2873. \newcommand{\LvarMonadASTPython}{
  2874. \begin{array}{rcl}
  2875. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2876. \Exp{} &::=& \Atm \MID \READ{} \\
  2877. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2878. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2879. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2880. \end{array}
  2881. }
  2882. \begin{figure}[tp]
  2883. \centering
  2884. \fbox{
  2885. \begin{minipage}{0.96\textwidth}
  2886. {\if\edition\racketEd
  2887. \[
  2888. \begin{array}{l}
  2889. \LvarMonadASTRacket \\
  2890. \begin{array}{rcl}
  2891. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2892. \end{array}
  2893. \end{array}
  2894. \]
  2895. \fi}
  2896. {\if\edition\pythonEd
  2897. \[
  2898. \begin{array}{l}
  2899. \LvarMonadASTPython \\
  2900. \begin{array}{rcl}
  2901. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2902. \end{array}
  2903. \end{array}
  2904. \]
  2905. \fi}
  2906. \end{minipage}
  2907. }
  2908. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2909. atomic expressions.}
  2910. \label{fig:Lvar-anf-syntax}
  2911. \end{figure}
  2912. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2913. of this pass, the language \LangVarANF{}. The only difference is that
  2914. operator arguments are restricted to be atomic expressions that are
  2915. defined by the \Atm{} non-terminal. In particular, integer constants
  2916. and variables are atomic.
  2917. The atomic expressions are pure (they do not cause or depend on
  2918. side-effects) whereas complex expressions may have side effects, such
  2919. as \READ{}. A language with this separation between pure versus
  2920. side-effecting expressions is said to be in monadic normal
  2921. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2922. in the name \LangVarANF{}. An important invariant of the
  2923. \code{remove\_complex\_operands} pass is that the relative ordering
  2924. among complex expressions is not changed, but the relative ordering
  2925. between atomic expressions and complex expressions can change and
  2926. often does. The reason that these changes are behaviour preserving is
  2927. that the atomic expressions are pure.
  2928. Another well-known form for intermediate languages is the
  2929. \emph{administrative normal form}
  2930. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2931. \index{subject}{administrative normal form} \index{subject}{ANF}
  2932. %
  2933. The \LangVarANF{} language is not quite in ANF because we allow the
  2934. right-hand side of a \code{let} to be a complex expression.
  2935. {\if\edition\racketEd
  2936. We recommend implementing this pass with two mutually recursive
  2937. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2938. \code{rco\_atom} to subexpressions that need to become atomic and to
  2939. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2940. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2941. returns an expression. The \code{rco\_atom} function returns two
  2942. things: an atomic expression and an alist mapping temporary variables to
  2943. complex subexpressions. You can return multiple things from a function
  2944. using Racket's \key{values} form and you can receive multiple things
  2945. from a function call using the \key{define-values} form.
  2946. \fi}
  2947. %
  2948. {\if\edition\pythonEd
  2949. %
  2950. We recommend implementing this pass with an auxiliary method named
  2951. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2952. Boolean that specifies whether the expression needs to become atomic
  2953. or not. The \code{rco\_exp} method should return a pair consisting of
  2954. the new expression and a list of pairs, associating new temporary
  2955. variables with their initializing expressions.
  2956. %
  2957. \fi}
  2958. {\if\edition\racketEd
  2959. %
  2960. Returning to the example program with the expression \code{(+ 42 (-
  2961. 10))}, the subexpression \code{(- 10)} should be processed using the
  2962. \code{rco\_atom} function because it is an argument of the \code{+}
  2963. operator and therefore needs to become atomic. The output of
  2964. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  2965. \begin{transformation}
  2966. \begin{lstlisting}
  2967. (- 10)
  2968. \end{lstlisting}
  2969. \compilesto
  2970. \begin{lstlisting}
  2971. tmp.1
  2972. ((tmp.1 . (- 10)))
  2973. \end{lstlisting}
  2974. \end{transformation}
  2975. \fi}
  2976. %
  2977. {\if\edition\pythonEd
  2978. %
  2979. Returning to the example program with the expression \code{42 + -10},
  2980. the subexpression \code{-10} should be processed using the
  2981. \code{rco\_exp} function with \code{True} as the second argument
  2982. because \code{-10} is an argument of the \code{+} operator and
  2983. therefore needs to become atomic. The output of \code{rco\_exp}
  2984. applied to \code{-10} is as follows.
  2985. \begin{transformation}
  2986. \begin{lstlisting}
  2987. -10
  2988. \end{lstlisting}
  2989. \compilesto
  2990. \begin{lstlisting}
  2991. tmp_1
  2992. [(tmp_1, -10)]
  2993. \end{lstlisting}
  2994. \end{transformation}
  2995. %
  2996. \fi}
  2997. Take special care of programs such as the following that
  2998. %
  2999. \racket{bind a variable to an atomic expression.}
  3000. %
  3001. \python{assign an atomic expression to a variable.}
  3002. %
  3003. You should leave such \racket{variable bindings}\python{assignments}
  3004. unchanged, as shown in the program on the right\\
  3005. %
  3006. {\if\edition\racketEd
  3007. \begin{transformation}
  3008. % var_test_20.rkt
  3009. \begin{lstlisting}
  3010. (let ([a 42])
  3011. (let ([b a])
  3012. b))
  3013. \end{lstlisting}
  3014. \compilesto
  3015. \begin{lstlisting}
  3016. (let ([a 42])
  3017. (let ([b a])
  3018. b))
  3019. \end{lstlisting}
  3020. \end{transformation}
  3021. \fi}
  3022. {\if\edition\pythonEd
  3023. \begin{transformation}
  3024. \begin{lstlisting}
  3025. a = 42
  3026. b = a
  3027. print(b)
  3028. \end{lstlisting}
  3029. \compilesto
  3030. \begin{lstlisting}
  3031. a = 42
  3032. b = a
  3033. print(b)
  3034. \end{lstlisting}
  3035. \end{transformation}
  3036. \fi}
  3037. %
  3038. \noindent A careless implementation might produce the following output with
  3039. unnecessary temporary variables.
  3040. \begin{center}
  3041. \begin{minipage}{0.4\textwidth}
  3042. {\if\edition\racketEd
  3043. \begin{lstlisting}
  3044. (let ([tmp.1 42])
  3045. (let ([a tmp.1])
  3046. (let ([tmp.2 a])
  3047. (let ([b tmp.2])
  3048. b))))
  3049. \end{lstlisting}
  3050. \fi}
  3051. {\if\edition\pythonEd
  3052. \begin{lstlisting}
  3053. tmp_1 = 42
  3054. a = tmp_1
  3055. tmp_2 = a
  3056. b = tmp_2
  3057. print(b)
  3058. \end{lstlisting}
  3059. \fi}
  3060. \end{minipage}
  3061. \end{center}
  3062. \begin{exercise}
  3063. \normalfont\normalsize
  3064. {\if\edition\racketEd
  3065. Implement the \code{remove\_complex\_operands} function in
  3066. \code{compiler.rkt}.
  3067. %
  3068. Create three new \LangVar{} programs that exercise the interesting
  3069. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3070. regarding file names described in Exercise~\ref{ex:Lvar}.
  3071. %
  3072. In the \code{run-tests.rkt} script, add the following entry to the
  3073. list of \code{passes} and then run the script to test your compiler.
  3074. \begin{lstlisting}
  3075. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3076. \end{lstlisting}
  3077. While debugging your compiler, it is often useful to see the
  3078. intermediate programs that are output from each pass. To print the
  3079. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3080. \code{interp-tests} in \code{run-tests.rkt}.
  3081. \fi}
  3082. %
  3083. {\if\edition\pythonEd
  3084. Implement the \code{remove\_complex\_operands} pass in
  3085. \code{compiler.py}, creating auxiliary functions for each
  3086. non-terminal in the grammar, i.e., \code{rco\_exp}
  3087. and \code{rco\_stmt}. We recommend you use the function
  3088. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3089. \fi}
  3090. \end{exercise}
  3091. {\if\edition\pythonEd
  3092. \begin{exercise}
  3093. \normalfont\normalsize
  3094. \label{ex:Lvar}
  3095. Create five \LangVar{} programs that exercise the most interesting
  3096. parts of the \code{remove\_complex\_operands} pass. The five programs
  3097. should be placed in the subdirectory named \key{tests} and the file
  3098. names should start with \code{var\_test\_} followed by a unique
  3099. integer and end with the file extension \key{.py}.
  3100. %% The \key{run-tests.rkt} script in the support code checks whether the
  3101. %% output programs produce the same result as the input programs. The
  3102. %% script uses the \key{interp-tests} function
  3103. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3104. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3105. %% parameter of \key{interp-tests} is a list that should have one entry
  3106. %% for each pass in your compiler. For now, define \code{passes} to
  3107. %% contain just one entry for \code{uniquify} as shown below.
  3108. %% \begin{lstlisting}
  3109. %% (define passes
  3110. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3111. %% \end{lstlisting}
  3112. Run the \key{run-tests.py} script in the support code to check
  3113. whether the output programs produce the same result as the input
  3114. programs.
  3115. \end{exercise}
  3116. \fi}
  3117. {\if\edition\racketEd
  3118. \section{Explicate Control}
  3119. \label{sec:explicate-control-Lvar}
  3120. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3121. programs that make the order of execution explicit in their
  3122. syntax. For now this amounts to flattening \key{let} constructs into a
  3123. sequence of assignment statements. For example, consider the following
  3124. \LangVar{} program.\\
  3125. % var_test_11.rkt
  3126. \begin{minipage}{0.96\textwidth}
  3127. \begin{lstlisting}
  3128. (let ([y (let ([x 20])
  3129. (+ x (let ([x 22]) x)))])
  3130. y)
  3131. \end{lstlisting}
  3132. \end{minipage}\\
  3133. %
  3134. The output of the previous pass is shown below, on the left, and the
  3135. output of \code{explicate\_control} is on the right. Recall that the
  3136. right-hand-side of a \key{let} executes before its body, so the order
  3137. of evaluation for this program is to assign \code{20} to \code{x.1},
  3138. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3139. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3140. this ordering explicit.
  3141. \begin{transformation}
  3142. \begin{lstlisting}
  3143. (let ([y (let ([x.1 20])
  3144. (let ([x.2 22])
  3145. (+ x.1 x.2)))])
  3146. y)
  3147. \end{lstlisting}
  3148. \compilesto
  3149. \begin{lstlisting}[language=C]
  3150. start:
  3151. x.1 = 20;
  3152. x.2 = 22;
  3153. y = (+ x.1 x.2);
  3154. return y;
  3155. \end{lstlisting}
  3156. \end{transformation}
  3157. \begin{figure}[tbp]
  3158. \begin{lstlisting}
  3159. (define (explicate_tail e)
  3160. (match e
  3161. [(Var x) ___]
  3162. [(Int n) (Return (Int n))]
  3163. [(Let x rhs body) ___]
  3164. [(Prim op es) ___]
  3165. [else (error "explicate_tail unhandled case" e)]))
  3166. (define (explicate_assign e x cont)
  3167. (match e
  3168. [(Var x) ___]
  3169. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3170. [(Let y rhs body) ___]
  3171. [(Prim op es) ___]
  3172. [else (error "explicate_assign unhandled case" e)]))
  3173. (define (explicate_control p)
  3174. (match p
  3175. [(Program info body) ___]))
  3176. \end{lstlisting}
  3177. \caption{Skeleton for the \code{explicate\_control} pass.}
  3178. \label{fig:explicate-control-Lvar}
  3179. \end{figure}
  3180. The organization of this pass depends on the notion of tail position
  3181. that we have alluded to earlier. Here is the definition.
  3182. \begin{definition}
  3183. The following rules define when an expression is in \textbf{\emph{tail
  3184. position}}\index{subject}{tail position} for the language \LangVar{}.
  3185. \begin{enumerate}
  3186. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3187. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3188. \end{enumerate}
  3189. \end{definition}
  3190. We recommend implementing \code{explicate\_control} using two
  3191. recursive functions, \code{explicate\_tail} and
  3192. \code{explicate\_assign}, as suggested in the skeleton code in
  3193. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3194. function should be applied to expressions in tail position whereas the
  3195. \code{explicate\_assign} should be applied to expressions that occur on
  3196. the right-hand-side of a \key{let}.
  3197. %
  3198. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3199. input and produces a \Tail{} in \LangCVar{} (see
  3200. Figure~\ref{fig:c0-syntax}).
  3201. %
  3202. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3203. the variable that it is to be assigned to, and a \Tail{} in
  3204. \LangCVar{} for the code that comes after the assignment. The
  3205. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3206. The \code{explicate\_assign} function is in accumulator-passing style:
  3207. the \code{cont} parameter is used for accumulating the output. This
  3208. accumulator-passing style plays an important role in how we generate
  3209. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3210. The abbreviation \code{cont} is for continuation because it contains
  3211. the generated code that should come after the current assignment.
  3212. This code organization is also related to continuation-passing style,
  3213. except that \code{cont} is not what happens next during compilation,
  3214. but what happens next in the generated code.
  3215. \begin{exercise}\normalfont\normalsize
  3216. %
  3217. Implement the \code{explicate\_control} function in
  3218. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3219. exercise the code in \code{explicate\_control}.
  3220. %
  3221. In the \code{run-tests.rkt} script, add the following entry to the
  3222. list of \code{passes} and then run the script to test your compiler.
  3223. \begin{lstlisting}
  3224. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3225. \end{lstlisting}
  3226. \end{exercise}
  3227. \fi}
  3228. \section{Select Instructions}
  3229. \label{sec:select-Lvar}
  3230. \index{subject}{instruction selection}
  3231. In the \code{select\_instructions} pass we begin the work of
  3232. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3233. language of this pass is a variant of x86 that still uses variables,
  3234. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3235. non-terminal of the \LangXInt{} abstract syntax
  3236. (Figure~\ref{fig:x86-int-ast}).
  3237. \racket{We recommend implementing the
  3238. \code{select\_instructions} with three auxiliary functions, one for
  3239. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3240. $\Tail$.}
  3241. \python{We recommend implementing an auxiliary function
  3242. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3243. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3244. same and integer constants change to immediates, that is, $\INT{n}$
  3245. changes to $\IMM{n}$.}
  3246. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3247. arithmetic operations. For example, consider the addition operation
  3248. below, on the left side. There is an \key{addq} instruction in x86,
  3249. but it performs an in-place update. So we could move $\Arg_1$
  3250. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3251. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3252. $\Atm_1$ and $\Atm_2$ respectively.
  3253. \begin{transformation}
  3254. {\if\edition\racketEd
  3255. \begin{lstlisting}
  3256. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3257. \end{lstlisting}
  3258. \fi}
  3259. {\if\edition\pythonEd
  3260. \begin{lstlisting}
  3261. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3262. \end{lstlisting}
  3263. \fi}
  3264. \compilesto
  3265. \begin{lstlisting}
  3266. movq |$\Arg_1$|, |$\itm{var}$|
  3267. addq |$\Arg_2$|, |$\itm{var}$|
  3268. \end{lstlisting}
  3269. \end{transformation}
  3270. There are also cases that require special care to avoid generating
  3271. needlessly complicated code. For example, if one of the arguments of
  3272. the addition is the same variable as the left-hand side of the
  3273. assignment, as shown below, then there is no need for the extra move
  3274. instruction. The assignment statement can be translated into a single
  3275. \key{addq} instruction as follows.
  3276. \begin{transformation}
  3277. {\if\edition\racketEd
  3278. \begin{lstlisting}
  3279. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3280. \end{lstlisting}
  3281. \fi}
  3282. {\if\edition\pythonEd
  3283. \begin{lstlisting}
  3284. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3285. \end{lstlisting}
  3286. \fi}
  3287. \compilesto
  3288. \begin{lstlisting}
  3289. addq |$\Arg_1$|, |$\itm{var}$|
  3290. \end{lstlisting}
  3291. \end{transformation}
  3292. The \READOP{} operation does not have a direct counterpart in x86
  3293. assembly, so we provide this functionality with the function
  3294. \code{read\_int} in the file \code{runtime.c}, written in
  3295. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3296. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3297. system}, or simply the \emph{runtime} for short. When compiling your
  3298. generated x86 assembly code, you need to compile \code{runtime.c} to
  3299. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3300. \code{-c}) and link it into the executable. For our purposes of code
  3301. generation, all you need to do is translate an assignment of
  3302. \READOP{} into a call to the \code{read\_int} function followed by a
  3303. move from \code{rax} to the left-hand-side variable. (Recall that the
  3304. return value of a function goes into \code{rax}.)
  3305. \begin{transformation}
  3306. {\if\edition\racketEd
  3307. \begin{lstlisting}
  3308. |$\itm{var}$| = (read);
  3309. \end{lstlisting}
  3310. \fi}
  3311. {\if\edition\pythonEd
  3312. \begin{lstlisting}
  3313. |$\itm{var}$| = input_int();
  3314. \end{lstlisting}
  3315. \fi}
  3316. \compilesto
  3317. \begin{lstlisting}
  3318. callq read_int
  3319. movq %rax, |$\itm{var}$|
  3320. \end{lstlisting}
  3321. \end{transformation}
  3322. {\if\edition\pythonEd
  3323. %
  3324. Similarly, we translate the \code{print} operation, shown below, into
  3325. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3326. In x86, the first six arguments to functions are passed in registers,
  3327. with the first argument passed in register \code{rdi}. So we move the
  3328. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3329. \code{callq} instruction.
  3330. \begin{transformation}
  3331. \begin{lstlisting}
  3332. print(|$\Atm$|)
  3333. \end{lstlisting}
  3334. \compilesto
  3335. \begin{lstlisting}
  3336. movq |$\Arg$|, %rdi
  3337. callq print_int
  3338. \end{lstlisting}
  3339. \end{transformation}
  3340. %
  3341. \fi}
  3342. {\if\edition\racketEd
  3343. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3344. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3345. assignment to the \key{rax} register followed by a jump to the
  3346. conclusion of the program (so the conclusion needs to be labeled).
  3347. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3348. recursively and then append the resulting instructions.
  3349. \fi}
  3350. {\if\edition\pythonEd
  3351. We recommend that you use the function \code{utils.label\_name()} to
  3352. transform a string into an label argument suitably suitable for, e.g.,
  3353. the target of the \code{callq} instruction. This practice makes your
  3354. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3355. all labels.
  3356. \fi}
  3357. \begin{exercise}
  3358. \normalfont\normalsize
  3359. {\if\edition\racketEd
  3360. Implement the \code{select\_instructions} pass in
  3361. \code{compiler.rkt}. Create three new example programs that are
  3362. designed to exercise all of the interesting cases in this pass.
  3363. %
  3364. In the \code{run-tests.rkt} script, add the following entry to the
  3365. list of \code{passes} and then run the script to test your compiler.
  3366. \begin{lstlisting}
  3367. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3368. \end{lstlisting}
  3369. \fi}
  3370. {\if\edition\pythonEd
  3371. Implement the \key{select\_instructions} pass in
  3372. \code{compiler.py}. Create three new example programs that are
  3373. designed to exercise all of the interesting cases in this pass.
  3374. Run the \code{run-tests.py} script to to check
  3375. whether the output programs produce the same result as the input
  3376. programs.
  3377. \fi}
  3378. \end{exercise}
  3379. \section{Assign Homes}
  3380. \label{sec:assign-Lvar}
  3381. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3382. \LangXVar{} programs that no longer use program variables.
  3383. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3384. the program variables in registers or on the stack. For runtime
  3385. efficiency, it is better to place variables in registers, but as there
  3386. are only 16 registers, some programs must necessarily resort to
  3387. placing some variables on the stack. In this chapter we focus on the
  3388. mechanics of placing variables on the stack. We study an algorithm for
  3389. placing variables in registers in
  3390. Chapter~\ref{ch:register-allocation-Lvar}.
  3391. Consider again the following \LangVar{} program from
  3392. Section~\ref{sec:remove-complex-opera-Lvar}.
  3393. % var_test_20.rkt
  3394. {\if\edition\racketEd
  3395. \begin{lstlisting}
  3396. (let ([a 42])
  3397. (let ([b a])
  3398. b))
  3399. \end{lstlisting}
  3400. \fi}
  3401. {\if\edition\pythonEd
  3402. \begin{lstlisting}
  3403. a = 42
  3404. b = a
  3405. print(b)
  3406. \end{lstlisting}
  3407. \fi}
  3408. %
  3409. The output of \code{select\_instructions} is shown below, on the left,
  3410. and the output of \code{assign\_homes} is on the right. In this
  3411. example, we assign variable \code{a} to stack location
  3412. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3413. \begin{transformation}
  3414. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3415. movq $42, a
  3416. movq a, b
  3417. movq b, %rax
  3418. \end{lstlisting}
  3419. \compilesto
  3420. %stack-space: 16
  3421. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3422. movq $42, -8(%rbp)
  3423. movq -8(%rbp), -16(%rbp)
  3424. movq -16(%rbp), %rax
  3425. \end{lstlisting}
  3426. \end{transformation}
  3427. \racket{
  3428. The \code{assign\_homes} pass should replace all variables
  3429. with stack locations.
  3430. The list of variables can be obtain from
  3431. the \code{locals-types} entry in the $\itm{info}$ of the
  3432. \code{X86Program} node. The \code{locals-types} entry is an alist
  3433. mapping all the variables in the program to their types
  3434. (for now just \code{Integer}).
  3435. As an aside, the \code{locals-types} entry is
  3436. computed by \code{type-check-Cvar} in the support code, which
  3437. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3438. which you should propagate to the \code{X86Program} node.}
  3439. %
  3440. \python{The \code{assign\_homes} pass should replace all uses of
  3441. variables with stack locations.}
  3442. %
  3443. In the process of assigning variables to stack locations, it is
  3444. convenient for you to compute and store the size of the frame (in
  3445. bytes) in
  3446. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3447. %
  3448. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3449. %
  3450. which is needed later to generate the conclusion of the \code{main}
  3451. procedure. The x86-64 standard requires the frame size to be a
  3452. multiple of 16 bytes.\index{subject}{frame}
  3453. % TODO: store the number of variables instead? -Jeremy
  3454. \begin{exercise}\normalfont\normalsize
  3455. Implement the \code{assign\_homes} pass in
  3456. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3457. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3458. grammar. We recommend that the auxiliary functions take an extra
  3459. parameter that maps variable names to homes (stack locations for now).
  3460. %
  3461. {\if\edition\racketEd
  3462. In the \code{run-tests.rkt} script, add the following entry to the
  3463. list of \code{passes} and then run the script to test your compiler.
  3464. \begin{lstlisting}
  3465. (list "assign homes" assign-homes interp_x86-0)
  3466. \end{lstlisting}
  3467. \fi}
  3468. {\if\edition\pythonEd
  3469. Run the \code{run-tests.py} script to to check
  3470. whether the output programs produce the same result as the input
  3471. programs.
  3472. \fi}
  3473. \end{exercise}
  3474. \section{Patch Instructions}
  3475. \label{sec:patch-s0}
  3476. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3477. \LangXInt{} by making sure that each instruction adheres to the
  3478. restriction that at most one argument of an instruction may be a
  3479. memory reference.
  3480. We return to the following example.\\
  3481. \begin{minipage}{0.5\textwidth}
  3482. % var_test_20.rkt
  3483. {\if\edition\racketEd
  3484. \begin{lstlisting}
  3485. (let ([a 42])
  3486. (let ([b a])
  3487. b))
  3488. \end{lstlisting}
  3489. \fi}
  3490. {\if\edition\pythonEd
  3491. \begin{lstlisting}
  3492. a = 42
  3493. b = a
  3494. print(b)
  3495. \end{lstlisting}
  3496. \fi}
  3497. \end{minipage}\\
  3498. The \code{assign\_homes} pass produces the following translation. \\
  3499. \begin{minipage}{0.5\textwidth}
  3500. {\if\edition\racketEd
  3501. \begin{lstlisting}
  3502. movq $42, -8(%rbp)
  3503. movq -8(%rbp), -16(%rbp)
  3504. movq -16(%rbp), %rax
  3505. \end{lstlisting}
  3506. \fi}
  3507. {\if\edition\pythonEd
  3508. \begin{lstlisting}
  3509. movq 42, -8(%rbp)
  3510. movq -8(%rbp), -16(%rbp)
  3511. movq -16(%rbp), %rdi
  3512. callq print_int
  3513. \end{lstlisting}
  3514. \fi}
  3515. \end{minipage}\\
  3516. The second \key{movq} instruction is problematic because both
  3517. arguments are stack locations. We suggest fixing this problem by
  3518. moving from the source location to the register \key{rax} and then
  3519. from \key{rax} to the destination location, as follows.
  3520. \begin{lstlisting}
  3521. movq -8(%rbp), %rax
  3522. movq %rax, -16(%rbp)
  3523. \end{lstlisting}
  3524. \begin{exercise}
  3525. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3526. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3527. Create three new example programs that are
  3528. designed to exercise all of the interesting cases in this pass.
  3529. %
  3530. {\if\edition\racketEd
  3531. In the \code{run-tests.rkt} script, add the following entry to the
  3532. list of \code{passes} and then run the script to test your compiler.
  3533. \begin{lstlisting}
  3534. (list "patch instructions" patch_instructions interp_x86-0)
  3535. \end{lstlisting}
  3536. \fi}
  3537. {\if\edition\pythonEd
  3538. Run the \code{run-tests.py} script to to check
  3539. whether the output programs produce the same result as the input
  3540. programs.
  3541. \fi}
  3542. \end{exercise}
  3543. \section{Generate Prelude and Conclusion}
  3544. \label{sec:print-x86}
  3545. \index{subject}{prelude}\index{subject}{conclusion}
  3546. The last step of the compiler from \LangVar{} to x86 is to generate
  3547. the \code{main} function with a prelude and conclusion wrapped around
  3548. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3549. discussed in Section~\ref{sec:x86}.
  3550. When running on Mac OS X, your compiler should prefix an underscore to
  3551. all labels, e.g., changing \key{main} to \key{\_main}.
  3552. %
  3553. \racket{The Racket call \code{(system-type 'os)} is useful for
  3554. determining which operating system the compiler is running on. It
  3555. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3556. %
  3557. \python{The Python \code{platform} library includes a \code{system()}
  3558. function that returns \code{'Linux'}, \code{'Windows'}, or
  3559. \code{'Darwin'} (for Mac).}
  3560. \begin{exercise}\normalfont\normalsize
  3561. %
  3562. Implement the \key{prelude\_and\_conclusion} pass in
  3563. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3564. %
  3565. {\if\edition\racketEd
  3566. In the \code{run-tests.rkt} script, add the following entry to the
  3567. list of \code{passes} and then run the script to test your compiler.
  3568. \begin{lstlisting}
  3569. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3570. \end{lstlisting}
  3571. %
  3572. Uncomment the call to the \key{compiler-tests} function
  3573. (Appendix~\ref{appendix:utilities}), which tests your complete
  3574. compiler by executing the generated x86 code. It translates the x86
  3575. AST that you produce into a string by invoking the \code{print-x86}
  3576. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3577. the provided \key{runtime.c} file to \key{runtime.o} using
  3578. \key{gcc}. Run the script to test your compiler.
  3579. %
  3580. \fi}
  3581. {\if\edition\pythonEd
  3582. %
  3583. Run the \code{run-tests.py} script to to check whether the output
  3584. programs produce the same result as the input programs. That script
  3585. translates the x86 AST that you produce into a string by invoking the
  3586. \code{repr} method that is implemented by the x86 AST classes in
  3587. \code{x86\_ast.py}.
  3588. %
  3589. \fi}
  3590. \end{exercise}
  3591. \section{Challenge: Partial Evaluator for \LangVar{}}
  3592. \label{sec:pe-Lvar}
  3593. \index{subject}{partial evaluation}
  3594. This section describes two optional challenge exercises that involve
  3595. adapting and improving the partial evaluator for \LangInt{} that was
  3596. introduced in Section~\ref{sec:partial-evaluation}.
  3597. \begin{exercise}\label{ex:pe-Lvar}
  3598. \normalfont\normalsize
  3599. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3600. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3601. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3602. %
  3603. \racket{\key{let} binding}\python{assignment}
  3604. %
  3605. to the \LangInt{} language, so you will need to add cases for them in
  3606. the \code{pe\_exp}
  3607. %
  3608. \racket{function.}
  3609. %
  3610. \python{and \code{pe\_stmt} functions.}
  3611. %
  3612. Once complete, add the partial evaluation pass to the front of your
  3613. compiler and make sure that your compiler still passes all of the
  3614. tests.
  3615. \end{exercise}
  3616. \begin{exercise}
  3617. \normalfont\normalsize
  3618. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3619. \code{pe\_add} auxiliary functions with functions that know more about
  3620. arithmetic. For example, your partial evaluator should translate
  3621. {\if\edition\racketEd
  3622. \[
  3623. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3624. \code{(+ 2 (read))}
  3625. \]
  3626. \fi}
  3627. {\if\edition\pythonEd
  3628. \[
  3629. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3630. \code{2 + input\_int()}
  3631. \]
  3632. \fi}
  3633. To accomplish this, the \code{pe\_exp} function should produce output
  3634. in the form of the $\itm{residual}$ non-terminal of the following
  3635. grammar. The idea is that when processing an addition expression, we
  3636. can always produce either 1) an integer constant, 2) an addition
  3637. expression with an integer constant on the left-hand side but not the
  3638. right-hand side, or 3) or an addition expression in which neither
  3639. subexpression is a constant.
  3640. {\if\edition\racketEd
  3641. \[
  3642. \begin{array}{lcl}
  3643. \itm{inert} &::=& \Var
  3644. \MID \LP\key{read}\RP
  3645. \MID \LP\key{-} ~\Var\RP
  3646. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3647. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3648. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3649. \itm{residual} &::=& \Int
  3650. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3651. \MID \itm{inert}
  3652. \end{array}
  3653. \]
  3654. \fi}
  3655. {\if\edition\pythonEd
  3656. \[
  3657. \begin{array}{lcl}
  3658. \itm{inert} &::=& \Var
  3659. \MID \key{input\_int}\LP\RP
  3660. \MID \key{-} \Var
  3661. \MID \key{-} \key{input\_int}\LP\RP
  3662. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3663. \itm{residual} &::=& \Int
  3664. \MID \Int ~ \key{+} ~ \itm{inert}
  3665. \MID \itm{inert}
  3666. \end{array}
  3667. \]
  3668. \fi}
  3669. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3670. inputs are $\itm{residual}$ expressions and they should return
  3671. $\itm{residual}$ expressions. Once the improvements are complete,
  3672. make sure that your compiler still passes all of the tests. After
  3673. all, fast code is useless if it produces incorrect results!
  3674. \end{exercise}
  3675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3676. \chapter{Register Allocation}
  3677. \label{ch:register-allocation-Lvar}
  3678. \index{subject}{register allocation}
  3679. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3680. variables on the procedure call stack. It can take 10s to 100s of
  3681. cycles for the CPU to access locations on the stack whereas accessing
  3682. a register takes only a single cycle. In this chapter we improve the
  3683. efficiency of our generated code by storing some variables in
  3684. registers. The goal of register allocation is to fit as many variables
  3685. into registers as possible. Some programs have more variables than
  3686. registers so we cannot always map each variable to a different
  3687. register. Fortunately, it is common for different variables to be
  3688. in-use during different periods of time during program execution, and
  3689. in those cases we can map multiple variables to the same register.
  3690. The program in Figure~\ref{fig:reg-eg} serves as a running
  3691. example. The source program is on the left and the output of
  3692. instruction selection is on the right. The program is almost in the
  3693. x86 assembly language but it still uses variables. Consider variables
  3694. \code{x} and \code{z}. After the variable \code{x} is moved to
  3695. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3696. hand, is used only after this point, so \code{x} and \code{z} could
  3697. share the same register.
  3698. \begin{figure}
  3699. \begin{minipage}{0.45\textwidth}
  3700. Example \LangVar{} program:
  3701. % var_test_28.rkt
  3702. {\if\edition\racketEd
  3703. \begin{lstlisting}
  3704. (let ([v 1])
  3705. (let ([w 42])
  3706. (let ([x (+ v 7)])
  3707. (let ([y x])
  3708. (let ([z (+ x w)])
  3709. (+ z (- y)))))))
  3710. \end{lstlisting}
  3711. \fi}
  3712. {\if\edition\pythonEd
  3713. \begin{lstlisting}
  3714. v = 1
  3715. w = 42
  3716. x = v + 7
  3717. y = x
  3718. z = x + w
  3719. print(z + (- y))
  3720. \end{lstlisting}
  3721. \fi}
  3722. \end{minipage}
  3723. \begin{minipage}{0.45\textwidth}
  3724. After instruction selection:
  3725. {\if\edition\racketEd
  3726. \begin{lstlisting}
  3727. locals-types:
  3728. x : Integer, y : Integer,
  3729. z : Integer, t : Integer,
  3730. v : Integer, w : Integer
  3731. start:
  3732. movq $1, v
  3733. movq $42, w
  3734. movq v, x
  3735. addq $7, x
  3736. movq x, y
  3737. movq x, z
  3738. addq w, z
  3739. movq y, t
  3740. negq t
  3741. movq z, %rax
  3742. addq t, %rax
  3743. jmp conclusion
  3744. \end{lstlisting}
  3745. \fi}
  3746. {\if\edition\pythonEd
  3747. \begin{lstlisting}
  3748. movq $1, v
  3749. movq $42, w
  3750. movq v, x
  3751. addq $7, x
  3752. movq x, y
  3753. movq x, z
  3754. addq w, z
  3755. movq y, tmp_0
  3756. negq tmp_0
  3757. movq z, tmp_1
  3758. addq tmp_0, tmp_1
  3759. movq tmp_1, %rdi
  3760. callq print_int
  3761. \end{lstlisting}
  3762. \fi}
  3763. \end{minipage}
  3764. \caption{A running example for register allocation.}
  3765. \label{fig:reg-eg}
  3766. \end{figure}
  3767. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3768. compute where a variable is in-use. Once we have that information, we
  3769. compute which variables are in-use at the same time, i.e., which ones
  3770. \emph{interfere}\index{subject}{interfere} with each other, and
  3771. represent this relation as an undirected graph whose vertices are
  3772. variables and edges indicate when two variables interfere
  3773. (Section~\ref{sec:build-interference}). We then model register
  3774. allocation as a graph coloring problem
  3775. (Section~\ref{sec:graph-coloring}).
  3776. If we run out of registers despite these efforts, we place the
  3777. remaining variables on the stack, similar to what we did in
  3778. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3779. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3780. location. The decision to spill a variable is handled as part of the
  3781. graph coloring process.
  3782. We make the simplifying assumption that each variable is assigned to
  3783. one location (a register or stack address). A more sophisticated
  3784. approach is to assign a variable to one or more locations in different
  3785. regions of the program. For example, if a variable is used many times
  3786. in short sequence and then only used again after many other
  3787. instructions, it could be more efficient to assign the variable to a
  3788. register during the initial sequence and then move it to the stack for
  3789. the rest of its lifetime. We refer the interested reader to
  3790. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3791. approach.
  3792. % discuss prioritizing variables based on how much they are used.
  3793. \section{Registers and Calling Conventions}
  3794. \label{sec:calling-conventions}
  3795. \index{subject}{calling conventions}
  3796. As we perform register allocation, we must be aware of the
  3797. \emph{calling conventions} \index{subject}{calling conventions} that
  3798. govern how functions calls are performed in x86.
  3799. %
  3800. Even though \LangVar{} does not include programmer-defined functions,
  3801. our generated code includes a \code{main} function that is called by
  3802. the operating system and our generated code contains calls to the
  3803. \code{read\_int} function.
  3804. Function calls require coordination between two pieces of code that
  3805. may be written by different programmers or generated by different
  3806. compilers. Here we follow the System V calling conventions that are
  3807. used by the GNU C compiler on Linux and
  3808. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3809. %
  3810. The calling conventions include rules about how functions share the
  3811. use of registers. In particular, the caller is responsible for freeing
  3812. up some registers prior to the function call for use by the callee.
  3813. These are called the \emph{caller-saved registers}
  3814. \index{subject}{caller-saved registers}
  3815. and they are
  3816. \begin{lstlisting}
  3817. rax rcx rdx rsi rdi r8 r9 r10 r11
  3818. \end{lstlisting}
  3819. On the other hand, the callee is responsible for preserving the values
  3820. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3821. which are
  3822. \begin{lstlisting}
  3823. rsp rbp rbx r12 r13 r14 r15
  3824. \end{lstlisting}
  3825. We can think about this caller/callee convention from two points of
  3826. view, the caller view and the callee view:
  3827. \begin{itemize}
  3828. \item The caller should assume that all the caller-saved registers get
  3829. overwritten with arbitrary values by the callee. On the other hand,
  3830. the caller can safely assume that all the callee-saved registers
  3831. retain their original values.
  3832. \item The callee can freely use any of the caller-saved registers.
  3833. However, if the callee wants to use a callee-saved register, the
  3834. callee must arrange to put the original value back in the register
  3835. prior to returning to the caller. This can be accomplished by saving
  3836. the value to the stack in the prelude of the function and restoring
  3837. the value in the conclusion of the function.
  3838. \end{itemize}
  3839. In x86, registers are also used for passing arguments to a function
  3840. and for the return value. In particular, the first six arguments of a
  3841. function are passed in the following six registers, in this order.
  3842. \index{subject}{argument-passing registers}
  3843. \index{subject}{parameter-passing registers}
  3844. \begin{lstlisting}
  3845. rdi rsi rdx rcx r8 r9
  3846. \end{lstlisting}
  3847. If there are more than six arguments, then the convention is to use
  3848. space on the frame of the caller for the rest of the
  3849. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3850. need more than six arguments.
  3851. %
  3852. \racket{For now, the only function we care about is \code{read\_int}
  3853. and it takes zero arguments.}
  3854. %
  3855. \python{For now, the only functions we care about are \code{read\_int}
  3856. and \code{print\_int}, which take zero and one argument, respectively.}
  3857. %
  3858. The register \code{rax} is used for the return value of a function.
  3859. The next question is how these calling conventions impact register
  3860. allocation. Consider the \LangVar{} program in
  3861. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3862. example from the caller point of view and then from the callee point
  3863. of view. We refer to a variable that is in-use during a function call
  3864. as being a \emph{call-live variable}\index{subject}{call-live
  3865. variable}.
  3866. The program makes two calls to \READOP{}. The variable \code{x} is
  3867. call-live because it is in-use during the second call to \READOP{}; we
  3868. must ensure that the value in \code{x} does not get overwritten during
  3869. the call to \READOP{}. One obvious approach is to save all the values
  3870. that reside in caller-saved registers to the stack prior to each
  3871. function call, and restore them after each call. That way, if the
  3872. register allocator chooses to assign \code{x} to a caller-saved
  3873. register, its value will be preserved across the call to \READOP{}.
  3874. However, saving and restoring to the stack is relatively slow. If
  3875. \code{x} is not used many times, it may be better to assign \code{x}
  3876. to a stack location in the first place. Or better yet, if we can
  3877. arrange for \code{x} to be placed in a callee-saved register, then it
  3878. won't need to be saved and restored during function calls.
  3879. The approach that we recommend for call-live variables is to either
  3880. assign them to callee-saved registers or to spill them to the
  3881. stack. On the other hand, for variables that are not call-live, we try
  3882. the following alternatives in order 1) look for an available
  3883. caller-saved register (to leave room for other variables in the
  3884. callee-saved register), 2) look for a callee-saved register, and 3)
  3885. spill the variable to the stack.
  3886. It is straightforward to implement this approach in a graph coloring
  3887. register allocator. First, we know which variables are call-live
  3888. because we already need to compute which variables are in-use at every
  3889. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3890. we build the interference graph
  3891. (Section~\ref{sec:build-interference}), we can place an edge between
  3892. each of the call-live variables and the caller-saved registers in the
  3893. interference graph. This will prevent the graph coloring algorithm
  3894. from assigning them to caller-saved registers.
  3895. Returning to the example in
  3896. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3897. generated x86 code on the right-hand side. Notice that variable
  3898. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3899. is already in a safe place during the second call to
  3900. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3901. \code{rcx}, a caller-saved register, because \code{y} is not a
  3902. call-live variable.
  3903. Next we analyze the example from the callee point of view, focusing on
  3904. the prelude and conclusion of the \code{main} function. As usual the
  3905. prelude begins with saving the \code{rbp} register to the stack and
  3906. setting the \code{rbp} to the current stack pointer. We now know why
  3907. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3908. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3909. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3910. (\code{x}). The other callee-saved registers are not saved in the
  3911. prelude because they are not used. The prelude subtracts 8 bytes from
  3912. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3913. conclusion, we see that \code{rbx} is restored from the stack with a
  3914. \code{popq} instruction.
  3915. \index{subject}{prelude}\index{subject}{conclusion}
  3916. \begin{figure}[tp]
  3917. \begin{minipage}{0.45\textwidth}
  3918. Example \LangVar{} program:
  3919. %var_test_14.rkt
  3920. {\if\edition\racketEd
  3921. \begin{lstlisting}
  3922. (let ([x (read)])
  3923. (let ([y (read)])
  3924. (+ (+ x y) 42)))
  3925. \end{lstlisting}
  3926. \fi}
  3927. {\if\edition\pythonEd
  3928. \begin{lstlisting}
  3929. x = input_int()
  3930. y = input_int()
  3931. print((x + y) + 42)
  3932. \end{lstlisting}
  3933. \fi}
  3934. \end{minipage}
  3935. \begin{minipage}{0.45\textwidth}
  3936. Generated x86 assembly:
  3937. {\if\edition\racketEd
  3938. \begin{lstlisting}
  3939. start:
  3940. callq read_int
  3941. movq %rax, %rbx
  3942. callq read_int
  3943. movq %rax, %rcx
  3944. addq %rcx, %rbx
  3945. movq %rbx, %rax
  3946. addq $42, %rax
  3947. jmp _conclusion
  3948. .globl main
  3949. main:
  3950. pushq %rbp
  3951. movq %rsp, %rbp
  3952. pushq %rbx
  3953. subq $8, %rsp
  3954. jmp start
  3955. conclusion:
  3956. addq $8, %rsp
  3957. popq %rbx
  3958. popq %rbp
  3959. retq
  3960. \end{lstlisting}
  3961. \fi}
  3962. {\if\edition\pythonEd
  3963. \begin{lstlisting}
  3964. .globl main
  3965. main:
  3966. pushq %rbp
  3967. movq %rsp, %rbp
  3968. pushq %rbx
  3969. subq $8, %rsp
  3970. callq read_int
  3971. movq %rax, %rbx
  3972. callq read_int
  3973. movq %rax, %rcx
  3974. movq %rbx, %rdx
  3975. addq %rcx, %rdx
  3976. movq %rdx, %rcx
  3977. addq $42, %rcx
  3978. movq %rcx, %rdi
  3979. callq print_int
  3980. addq $8, %rsp
  3981. popq %rbx
  3982. popq %rbp
  3983. retq
  3984. \end{lstlisting}
  3985. \fi}
  3986. \end{minipage}
  3987. \caption{An example with function calls.}
  3988. \label{fig:example-calling-conventions}
  3989. \end{figure}
  3990. %\clearpage
  3991. \section{Liveness Analysis}
  3992. \label{sec:liveness-analysis-Lvar}
  3993. \index{subject}{liveness analysis}
  3994. The \code{uncover\_live} \racket{pass}\python{function} performs
  3995. \emph{liveness analysis}, that is, it discovers which variables are
  3996. in-use in different regions of a program.
  3997. %
  3998. A variable or register is \emph{live} at a program point if its
  3999. current value is used at some later point in the program. We refer to
  4000. variables, stack locations, and registers collectively as
  4001. \emph{locations}.
  4002. %
  4003. Consider the following code fragment in which there are two writes to
  4004. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4005. time?
  4006. \begin{center}
  4007. \begin{minipage}{0.96\textwidth}
  4008. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4009. movq $5, a
  4010. movq $30, b
  4011. movq a, c
  4012. movq $10, b
  4013. addq b, c
  4014. \end{lstlisting}
  4015. \end{minipage}
  4016. \end{center}
  4017. The answer is no because \code{a} is live from line 1 to 3 and
  4018. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4019. line 2 is never used because it is overwritten (line 4) before the
  4020. next read (line 5).
  4021. The live locations for each instruction can be computed by traversing
  4022. the instruction sequence back to front (i.e., backwards in execution
  4023. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4024. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4025. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4026. locations before instruction $I_k$. \racket{We recommend representing
  4027. these sets with the Racket \code{set} data structure described in
  4028. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4029. with the Python
  4030. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4031. data structure.}
  4032. {\if\edition\racketEd
  4033. \begin{figure}[tp]
  4034. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4035. \small
  4036. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4037. A \emph{set} is an unordered collection of elements without duplicates.
  4038. Here are some of the operations defined on sets.
  4039. \index{subject}{set}
  4040. \begin{description}
  4041. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4042. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4043. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4044. difference of the two sets.
  4045. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4046. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4047. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4048. \end{description}
  4049. \end{tcolorbox}
  4050. %\end{wrapfigure}
  4051. \caption{The \code{set} data structure.}
  4052. \label{fig:set}
  4053. \end{figure}
  4054. \fi}
  4055. The live locations after an instruction are always the same as the
  4056. live locations before the next instruction.
  4057. \index{subject}{live-after} \index{subject}{live-before}
  4058. \begin{equation} \label{eq:live-after-before-next}
  4059. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4060. \end{equation}
  4061. To start things off, there are no live locations after the last
  4062. instruction, so
  4063. \begin{equation}\label{eq:live-last-empty}
  4064. L_{\mathsf{after}}(n) = \emptyset
  4065. \end{equation}
  4066. We then apply the following rule repeatedly, traversing the
  4067. instruction sequence back to front.
  4068. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4069. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4070. \end{equation}
  4071. where $W(k)$ are the locations written to by instruction $I_k$ and
  4072. $R(k)$ are the locations read by instruction $I_k$.
  4073. {\if\edition\racketEd
  4074. %
  4075. There is a special case for \code{jmp} instructions. The locations
  4076. that are live before a \code{jmp} should be the locations in
  4077. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4078. maintaining an alist named \code{label->live} that maps each label to
  4079. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4080. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4081. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4082. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4083. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4084. %
  4085. \fi}
  4086. Let us walk through the above example, applying these formulas
  4087. starting with the instruction on line 5. We collect the answers in
  4088. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4089. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4090. instruction (formula~\ref{eq:live-last-empty}). The
  4091. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4092. because it reads from variables \code{b} and \code{c}
  4093. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4094. \[
  4095. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4096. \]
  4097. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4098. the live-before set from line 5 to be the live-after set for this
  4099. instruction (formula~\ref{eq:live-after-before-next}).
  4100. \[
  4101. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4102. \]
  4103. This move instruction writes to \code{b} and does not read from any
  4104. variables, so we have the following live-before set
  4105. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4106. \[
  4107. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4108. \]
  4109. The live-before for instruction \code{movq a, c}
  4110. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4111. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4112. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4113. variable that is not live and does not read from a variable.
  4114. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4115. because it writes to variable \code{a}.
  4116. \begin{figure}[tbp]
  4117. \begin{minipage}{0.45\textwidth}
  4118. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4119. movq $5, a
  4120. movq $30, b
  4121. movq a, c
  4122. movq $10, b
  4123. addq b, c
  4124. \end{lstlisting}
  4125. \end{minipage}
  4126. \vrule\hspace{10pt}
  4127. \begin{minipage}{0.45\textwidth}
  4128. \begin{align*}
  4129. L_{\mathsf{before}}(1)= \emptyset,
  4130. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4131. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4132. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4133. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4134. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4135. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4136. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4137. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4138. L_{\mathsf{after}}(5)= \emptyset
  4139. \end{align*}
  4140. \end{minipage}
  4141. \caption{Example output of liveness analysis on a short example.}
  4142. \label{fig:liveness-example-0}
  4143. \end{figure}
  4144. \begin{exercise}\normalfont\normalsize
  4145. Perform liveness analysis by hand on the running example in
  4146. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4147. sets for each instruction. Compare your answers to the solution
  4148. shown in Figure~\ref{fig:live-eg}.
  4149. \end{exercise}
  4150. \begin{figure}[tp]
  4151. \hspace{20pt}
  4152. \begin{minipage}{0.45\textwidth}
  4153. {\if\edition\racketEd
  4154. \begin{lstlisting}
  4155. |$\{\ttm{rsp}\}$|
  4156. movq $1, v
  4157. |$\{\ttm{v},\ttm{rsp}\}$|
  4158. movq $42, w
  4159. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4160. movq v, x
  4161. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4162. addq $7, x
  4163. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4164. movq x, y
  4165. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4166. movq x, z
  4167. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4168. addq w, z
  4169. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4170. movq y, t
  4171. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4172. negq t
  4173. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4174. movq z, %rax
  4175. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4176. addq t, %rax
  4177. |$\{\ttm{rax},\ttm{rsp}\}$|
  4178. jmp conclusion
  4179. \end{lstlisting}
  4180. \fi}
  4181. {\if\edition\pythonEd
  4182. \begin{lstlisting}
  4183. movq $1, v
  4184. |$\{\ttm{v}\}$|
  4185. movq $42, w
  4186. |$\{\ttm{w}, \ttm{v}\}$|
  4187. movq v, x
  4188. |$\{\ttm{w}, \ttm{x}\}$|
  4189. addq $7, x
  4190. |$\{\ttm{w}, \ttm{x}\}$|
  4191. movq x, y
  4192. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4193. movq x, z
  4194. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4195. addq w, z
  4196. |$\{\ttm{y}, \ttm{z}\}$|
  4197. movq y, tmp_0
  4198. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4199. negq tmp_0
  4200. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4201. movq z, tmp_1
  4202. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4203. addq tmp_0, tmp_1
  4204. |$\{\ttm{tmp\_1}\}$|
  4205. movq tmp_1, %rdi
  4206. |$\{\ttm{rdi}\}$|
  4207. callq print_int
  4208. |$\{\}$|
  4209. \end{lstlisting}
  4210. \fi}
  4211. \end{minipage}
  4212. \caption{The running example annotated with live-after sets.}
  4213. \label{fig:live-eg}
  4214. \end{figure}
  4215. \begin{exercise}\normalfont\normalsize
  4216. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4217. %
  4218. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4219. field of the \code{Block} structure.}
  4220. %
  4221. \python{Return a dictionary that maps each instruction to its
  4222. live-after set.}
  4223. %
  4224. \racket{We recommend creating an auxiliary function that takes a list
  4225. of instructions and an initial live-after set (typically empty) and
  4226. returns the list of live-after sets.}
  4227. %
  4228. We recommend creating auxiliary functions to 1) compute the set
  4229. of locations that appear in an \Arg{}, 2) compute the locations read
  4230. by an instruction (the $R$ function), and 3) the locations written by
  4231. an instruction (the $W$ function). The \code{callq} instruction should
  4232. include all of the caller-saved registers in its write-set $W$ because
  4233. the calling convention says that those registers may be written to
  4234. during the function call. Likewise, the \code{callq} instruction
  4235. should include the appropriate argument-passing registers in its
  4236. read-set $R$, depending on the arity of the function being
  4237. called. (This is why the abstract syntax for \code{callq} includes the
  4238. arity.)
  4239. \end{exercise}
  4240. %\clearpage
  4241. \section{Build the Interference Graph}
  4242. \label{sec:build-interference}
  4243. {\if\edition\racketEd
  4244. \begin{figure}[tp]
  4245. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4246. \small
  4247. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4248. A \emph{graph} is a collection of vertices and edges where each
  4249. edge connects two vertices. A graph is \emph{directed} if each
  4250. edge points from a source to a target. Otherwise the graph is
  4251. \emph{undirected}.
  4252. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4253. \begin{description}
  4254. %% We currently don't use directed graphs. We instead use
  4255. %% directed multi-graphs. -Jeremy
  4256. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4257. directed graph from a list of edges. Each edge is a list
  4258. containing the source and target vertex.
  4259. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4260. undirected graph from a list of edges. Each edge is represented by
  4261. a list containing two vertices.
  4262. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4263. inserts a vertex into the graph.
  4264. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4265. inserts an edge between the two vertices.
  4266. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4267. returns a sequence of vertices adjacent to the vertex.
  4268. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4269. returns a sequence of all vertices in the graph.
  4270. \end{description}
  4271. \end{tcolorbox}
  4272. %\end{wrapfigure}
  4273. \caption{The Racket \code{graph} package.}
  4274. \label{fig:graph}
  4275. \end{figure}
  4276. \fi}
  4277. Based on the liveness analysis, we know where each location is live.
  4278. However, during register allocation, we need to answer questions of
  4279. the specific form: are locations $u$ and $v$ live at the same time?
  4280. (And therefore cannot be assigned to the same register.) To make this
  4281. question more efficient to answer, we create an explicit data
  4282. structure, an \emph{interference graph}\index{subject}{interference
  4283. graph}. An interference graph is an undirected graph that has an
  4284. edge between two locations if they are live at the same time, that is,
  4285. if they interfere with each other.
  4286. %
  4287. \racket{We recommend using the Racket \code{graph} package
  4288. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4289. %
  4290. \python{We provide implementations of directed and undirected graph
  4291. data structures in the file \code{graph.py} of the support code.}
  4292. A straightforward way to compute the interference graph is to look at
  4293. the set of live locations between each instruction and add an edge to
  4294. the graph for every pair of variables in the same set. This approach
  4295. is less than ideal for two reasons. First, it can be expensive because
  4296. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4297. locations. Second, in the special case where two locations hold the
  4298. same value (because one was assigned to the other), they can be live
  4299. at the same time without interfering with each other.
  4300. A better way to compute the interference graph is to focus on
  4301. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4302. must not overwrite something in a live location. So for each
  4303. instruction, we create an edge between the locations being written to
  4304. and the live locations. (Except that a location never interferes with
  4305. itself.) For the \key{callq} instruction, we consider all of the
  4306. caller-saved registers as being written to, so an edge is added
  4307. between every live variable and every caller-saved register. Also, for
  4308. \key{movq} there is the special case of two variables holding the same
  4309. value. If a live variable $v$ is the same as the source of the
  4310. \key{movq}, then there is no need to add an edge between $v$ and the
  4311. destination, because they both hold the same value.
  4312. %
  4313. So we have the following two rules.
  4314. \begin{enumerate}
  4315. \item If instruction $I_k$ is a move instruction of the form
  4316. \key{movq} $s$\key{,} $d$, then for every $v \in
  4317. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4318. $(d,v)$.
  4319. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4320. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4321. $(d,v)$.
  4322. \end{enumerate}
  4323. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4324. the above rules to each instruction. We highlight a few of the
  4325. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4326. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4327. so \code{v} interferes with \code{rsp}.}
  4328. %
  4329. \python{The first instruction is \lstinline{movq $1, v} and the
  4330. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4331. no interference because $\ttm{v}$ is the destination of the move.}
  4332. %
  4333. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4334. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4335. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4336. %
  4337. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4338. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4339. $\ttm{x}$ interferes with \ttm{w}.}
  4340. %
  4341. \racket{The next instruction is \lstinline{movq x, y} and the
  4342. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4343. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4344. \ttm{x} because \ttm{x} is the source of the move and therefore
  4345. \ttm{x} and \ttm{y} hold the same value.}
  4346. %
  4347. \python{The next instruction is \lstinline{movq x, y} and the
  4348. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4349. applies, so \ttm{y} interferes with \ttm{w} but not
  4350. \ttm{x} because \ttm{x} is the source of the move and therefore
  4351. \ttm{x} and \ttm{y} hold the same value.}
  4352. %
  4353. Figure~\ref{fig:interference-results} lists the interference results
  4354. for all of the instructions and the resulting interference graph is
  4355. shown in Figure~\ref{fig:interfere}.
  4356. \begin{figure}[tbp]
  4357. \begin{quote}
  4358. {\if\edition\racketEd
  4359. \begin{tabular}{ll}
  4360. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4361. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4362. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4363. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4364. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4365. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4366. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4367. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4368. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4369. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4370. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4371. \lstinline!jmp conclusion!& no interference.
  4372. \end{tabular}
  4373. \fi}
  4374. {\if\edition\pythonEd
  4375. \begin{tabular}{ll}
  4376. \lstinline!movq $1, v!& no interference\\
  4377. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4378. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4379. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4380. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4381. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4382. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4383. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4384. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4385. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4386. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4387. \lstinline!movq tmp_1, %rdi! & no interference \\
  4388. \lstinline!callq print_int!& no interference.
  4389. \end{tabular}
  4390. \fi}
  4391. \end{quote}
  4392. \caption{Interference results for the running example.}
  4393. \label{fig:interference-results}
  4394. \end{figure}
  4395. \begin{figure}[tbp]
  4396. \large
  4397. {\if\edition\racketEd
  4398. \[
  4399. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4400. \node (rax) at (0,0) {$\ttm{rax}$};
  4401. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4402. \node (t1) at (0,2) {$\ttm{t}$};
  4403. \node (z) at (3,2) {$\ttm{z}$};
  4404. \node (x) at (6,2) {$\ttm{x}$};
  4405. \node (y) at (3,0) {$\ttm{y}$};
  4406. \node (w) at (6,0) {$\ttm{w}$};
  4407. \node (v) at (9,0) {$\ttm{v}$};
  4408. \draw (t1) to (rax);
  4409. \draw (t1) to (z);
  4410. \draw (z) to (y);
  4411. \draw (z) to (w);
  4412. \draw (x) to (w);
  4413. \draw (y) to (w);
  4414. \draw (v) to (w);
  4415. \draw (v) to (rsp);
  4416. \draw (w) to (rsp);
  4417. \draw (x) to (rsp);
  4418. \draw (y) to (rsp);
  4419. \path[-.,bend left=15] (z) edge node {} (rsp);
  4420. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4421. \draw (rax) to (rsp);
  4422. \end{tikzpicture}
  4423. \]
  4424. \fi}
  4425. {\if\edition\pythonEd
  4426. \[
  4427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4428. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4429. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4430. \node (z) at (3,2) {$\ttm{z}$};
  4431. \node (x) at (6,2) {$\ttm{x}$};
  4432. \node (y) at (3,0) {$\ttm{y}$};
  4433. \node (w) at (6,0) {$\ttm{w}$};
  4434. \node (v) at (9,0) {$\ttm{v}$};
  4435. \draw (t0) to (t1);
  4436. \draw (t0) to (z);
  4437. \draw (z) to (y);
  4438. \draw (z) to (w);
  4439. \draw (x) to (w);
  4440. \draw (y) to (w);
  4441. \draw (v) to (w);
  4442. \end{tikzpicture}
  4443. \]
  4444. \fi}
  4445. \caption{The interference graph of the example program.}
  4446. \label{fig:interfere}
  4447. \end{figure}
  4448. %% Our next concern is to choose a data structure for representing the
  4449. %% interference graph. There are many choices for how to represent a
  4450. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4451. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4452. %% data structure is to study the algorithm that uses the data structure,
  4453. %% determine what operations need to be performed, and then choose the
  4454. %% data structure that provide the most efficient implementations of
  4455. %% those operations. Often times the choice of data structure can have an
  4456. %% effect on the time complexity of the algorithm, as it does here. If
  4457. %% you skim the next section, you will see that the register allocation
  4458. %% algorithm needs to ask the graph for all of its vertices and, given a
  4459. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4460. %% correct choice of graph representation is that of an adjacency
  4461. %% list. There are helper functions in \code{utilities.rkt} for
  4462. %% representing graphs using the adjacency list representation:
  4463. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4464. %% (Appendix~\ref{appendix:utilities}).
  4465. %% %
  4466. %% \margincomment{\footnotesize To do: change to use the
  4467. %% Racket graph library. \\ --Jeremy}
  4468. %% %
  4469. %% In particular, those functions use a hash table to map each vertex to
  4470. %% the set of adjacent vertices, and the sets are represented using
  4471. %% Racket's \key{set}, which is also a hash table.
  4472. \begin{exercise}\normalfont\normalsize
  4473. \racket{Implement the compiler pass named \code{build\_interference} according
  4474. to the algorithm suggested above. We recommend using the Racket
  4475. \code{graph} package to create and inspect the interference graph.
  4476. The output graph of this pass should be stored in the $\itm{info}$ field of
  4477. the program, under the key \code{conflicts}.}
  4478. %
  4479. \python{Implement a function named \code{build\_interference}
  4480. according to the algorithm suggested above that
  4481. returns the interference graph.}
  4482. \end{exercise}
  4483. \section{Graph Coloring via Sudoku}
  4484. \label{sec:graph-coloring}
  4485. \index{subject}{graph coloring}
  4486. \index{subject}{Sudoku}
  4487. \index{subject}{color}
  4488. We come to the main event of this chapter, mapping variables to
  4489. registers and stack locations. Variables that interfere with each
  4490. other must be mapped to different locations. In terms of the
  4491. interference graph, this means that adjacent vertices must be mapped
  4492. to different locations. If we think of locations as colors, the
  4493. register allocation problem becomes the graph coloring
  4494. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4495. The reader may be more familiar with the graph coloring problem than he
  4496. or she realizes; the popular game of Sudoku is an instance of the
  4497. graph coloring problem. The following describes how to build a graph
  4498. out of an initial Sudoku board.
  4499. \begin{itemize}
  4500. \item There is one vertex in the graph for each Sudoku square.
  4501. \item There is an edge between two vertices if the corresponding squares
  4502. are in the same row, in the same column, or if the squares are in
  4503. the same $3\times 3$ region.
  4504. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4505. \item Based on the initial assignment of numbers to squares in the
  4506. Sudoku board, assign the corresponding colors to the corresponding
  4507. vertices in the graph.
  4508. \end{itemize}
  4509. If you can color the remaining vertices in the graph with the nine
  4510. colors, then you have also solved the corresponding game of Sudoku.
  4511. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4512. the corresponding graph with colored vertices. We map the Sudoku
  4513. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4514. sampling of the vertices (the colored ones) because showing edges for
  4515. all of the vertices would make the graph unreadable.
  4516. \begin{figure}[tbp]
  4517. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4518. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4519. \caption{A Sudoku game board and the corresponding colored graph.}
  4520. \label{fig:sudoku-graph}
  4521. \end{figure}
  4522. Some techniques for playing Sudoku correspond to heuristics used in
  4523. graph coloring algorithms. For example, one of the basic techniques
  4524. for Sudoku is called Pencil Marks. The idea is to use a process of
  4525. elimination to determine what numbers are no longer available for a
  4526. square and write down those numbers in the square (writing very
  4527. small). For example, if the number $1$ is assigned to a square, then
  4528. write the pencil mark $1$ in all the squares in the same row, column,
  4529. and region to indicate that $1$ is no longer an option for those other
  4530. squares.
  4531. %
  4532. The Pencil Marks technique corresponds to the notion of
  4533. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4534. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4535. are no longer available. In graph terminology, we have the following
  4536. definition:
  4537. \begin{equation*}
  4538. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4539. \text{ and } \mathrm{color}(v) = c \}
  4540. \end{equation*}
  4541. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4542. edge with $u$.
  4543. The Pencil Marks technique leads to a simple strategy for filling in
  4544. numbers: if there is a square with only one possible number left, then
  4545. choose that number! But what if there are no squares with only one
  4546. possibility left? One brute-force approach is to try them all: choose
  4547. the first one and if that ultimately leads to a solution, great. If
  4548. not, backtrack and choose the next possibility. One good thing about
  4549. Pencil Marks is that it reduces the degree of branching in the search
  4550. tree. Nevertheless, backtracking can be terribly time consuming. One
  4551. way to reduce the amount of backtracking is to use the
  4552. most-constrained-first heuristic (aka. minimum remaining
  4553. values)~\citep{Russell2003}. That is, when choosing a square, always
  4554. choose one with the fewest possibilities left (the vertex with the
  4555. highest saturation). The idea is that choosing highly constrained
  4556. squares earlier rather than later is better because later on there may
  4557. not be any possibilities left in the highly saturated squares.
  4558. However, register allocation is easier than Sudoku because the
  4559. register allocator can fall back to assigning variables to stack
  4560. locations when the registers run out. Thus, it makes sense to replace
  4561. backtracking with greedy search: make the best choice at the time and
  4562. keep going. We still wish to minimize the number of colors needed, so
  4563. we use the most-constrained-first heuristic in the greedy search.
  4564. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4565. algorithm for register allocation based on saturation and the
  4566. most-constrained-first heuristic. It is roughly equivalent to the
  4567. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4568. %,Gebremedhin:1999fk,Omari:2006uq
  4569. Just as in Sudoku, the algorithm represents colors with integers. The
  4570. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4571. for register allocation. The integers $k$ and larger correspond to
  4572. stack locations. The registers that are not used for register
  4573. allocation, such as \code{rax}, are assigned to negative integers. In
  4574. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4575. %% One might wonder why we include registers at all in the liveness
  4576. %% analysis and interference graph. For example, we never allocate a
  4577. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4578. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4579. %% to use register for passing arguments to functions, it will be
  4580. %% necessary for those registers to appear in the interference graph
  4581. %% because those registers will also be assigned to variables, and we
  4582. %% don't want those two uses to encroach on each other. Regarding
  4583. %% registers such as \code{rax} and \code{rsp} that are not used for
  4584. %% variables, we could omit them from the interference graph but that
  4585. %% would require adding special cases to our algorithm, which would
  4586. %% complicate the logic for little gain.
  4587. \begin{figure}[btp]
  4588. \centering
  4589. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4590. Algorithm: DSATUR
  4591. Input: a graph |$G$|
  4592. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4593. |$W \gets \mathrm{vertices}(G)$|
  4594. while |$W \neq \emptyset$| do
  4595. pick a vertex |$u$| from |$W$| with the highest saturation,
  4596. breaking ties randomly
  4597. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4598. |$\mathrm{color}[u] \gets c$|
  4599. |$W \gets W - \{u\}$|
  4600. \end{lstlisting}
  4601. \caption{The saturation-based greedy graph coloring algorithm.}
  4602. \label{fig:satur-algo}
  4603. \end{figure}
  4604. {\if\edition\racketEd
  4605. With the DSATUR algorithm in hand, let us return to the running
  4606. example and consider how to color the interference graph in
  4607. Figure~\ref{fig:interfere}.
  4608. %
  4609. We start by assigning the register nodes to their own color. For
  4610. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4611. assigned $-2$. The variables are not yet colored, so they are
  4612. annotated with a dash. We then update the saturation for vertices that
  4613. are adjacent to a register, obtaining the following annotated
  4614. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4615. it interferes with both \code{rax} and \code{rsp}.
  4616. \[
  4617. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4618. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4619. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4620. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4621. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4622. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4623. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4624. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4625. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4626. \draw (t1) to (rax);
  4627. \draw (t1) to (z);
  4628. \draw (z) to (y);
  4629. \draw (z) to (w);
  4630. \draw (x) to (w);
  4631. \draw (y) to (w);
  4632. \draw (v) to (w);
  4633. \draw (v) to (rsp);
  4634. \draw (w) to (rsp);
  4635. \draw (x) to (rsp);
  4636. \draw (y) to (rsp);
  4637. \path[-.,bend left=15] (z) edge node {} (rsp);
  4638. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4639. \draw (rax) to (rsp);
  4640. \end{tikzpicture}
  4641. \]
  4642. The algorithm says to select a maximally saturated vertex. So we pick
  4643. $\ttm{t}$ and color it with the first available integer, which is
  4644. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4645. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4646. \[
  4647. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4648. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4649. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4650. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4651. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4652. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4653. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4654. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4655. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4656. \draw (t1) to (rax);
  4657. \draw (t1) to (z);
  4658. \draw (z) to (y);
  4659. \draw (z) to (w);
  4660. \draw (x) to (w);
  4661. \draw (y) to (w);
  4662. \draw (v) to (w);
  4663. \draw (v) to (rsp);
  4664. \draw (w) to (rsp);
  4665. \draw (x) to (rsp);
  4666. \draw (y) to (rsp);
  4667. \path[-.,bend left=15] (z) edge node {} (rsp);
  4668. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4669. \draw (rax) to (rsp);
  4670. \end{tikzpicture}
  4671. \]
  4672. We repeat the process, selecting a maximally saturated vertex,
  4673. choosing is \code{z}, and color it with the first available number, which
  4674. is $1$. We add $1$ to the saturation for the neighboring vertices
  4675. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4676. \[
  4677. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4678. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4679. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4680. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4681. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4682. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4683. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4684. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4685. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4686. \draw (t1) to (rax);
  4687. \draw (t1) to (z);
  4688. \draw (z) to (y);
  4689. \draw (z) to (w);
  4690. \draw (x) to (w);
  4691. \draw (y) to (w);
  4692. \draw (v) to (w);
  4693. \draw (v) to (rsp);
  4694. \draw (w) to (rsp);
  4695. \draw (x) to (rsp);
  4696. \draw (y) to (rsp);
  4697. \path[-.,bend left=15] (z) edge node {} (rsp);
  4698. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4699. \draw (rax) to (rsp);
  4700. \end{tikzpicture}
  4701. \]
  4702. The most saturated vertices are now \code{w} and \code{y}. We color
  4703. \code{w} with the first available color, which is $0$.
  4704. \[
  4705. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4706. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4707. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4708. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4709. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4710. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4711. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4712. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4713. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4714. \draw (t1) to (rax);
  4715. \draw (t1) to (z);
  4716. \draw (z) to (y);
  4717. \draw (z) to (w);
  4718. \draw (x) to (w);
  4719. \draw (y) to (w);
  4720. \draw (v) to (w);
  4721. \draw (v) to (rsp);
  4722. \draw (w) to (rsp);
  4723. \draw (x) to (rsp);
  4724. \draw (y) to (rsp);
  4725. \path[-.,bend left=15] (z) edge node {} (rsp);
  4726. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4727. \draw (rax) to (rsp);
  4728. \end{tikzpicture}
  4729. \]
  4730. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4731. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4732. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4733. and \code{z}, whose colors are $0$ and $1$ respectively.
  4734. \[
  4735. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4736. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4737. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4738. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4739. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4740. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4741. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4742. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4743. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4744. \draw (t1) to (rax);
  4745. \draw (t1) to (z);
  4746. \draw (z) to (y);
  4747. \draw (z) to (w);
  4748. \draw (x) to (w);
  4749. \draw (y) to (w);
  4750. \draw (v) to (w);
  4751. \draw (v) to (rsp);
  4752. \draw (w) to (rsp);
  4753. \draw (x) to (rsp);
  4754. \draw (y) to (rsp);
  4755. \path[-.,bend left=15] (z) edge node {} (rsp);
  4756. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4757. \draw (rax) to (rsp);
  4758. \end{tikzpicture}
  4759. \]
  4760. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4761. \[
  4762. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4763. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4764. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4765. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4766. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4767. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4768. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4769. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4770. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4771. \draw (t1) to (rax);
  4772. \draw (t1) to (z);
  4773. \draw (z) to (y);
  4774. \draw (z) to (w);
  4775. \draw (x) to (w);
  4776. \draw (y) to (w);
  4777. \draw (v) to (w);
  4778. \draw (v) to (rsp);
  4779. \draw (w) to (rsp);
  4780. \draw (x) to (rsp);
  4781. \draw (y) to (rsp);
  4782. \path[-.,bend left=15] (z) edge node {} (rsp);
  4783. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4784. \draw (rax) to (rsp);
  4785. \end{tikzpicture}
  4786. \]
  4787. In the last step of the algorithm, we color \code{x} with $1$.
  4788. \[
  4789. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4790. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4791. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4792. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4793. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4794. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4795. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4796. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4797. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4798. \draw (t1) to (rax);
  4799. \draw (t1) to (z);
  4800. \draw (z) to (y);
  4801. \draw (z) to (w);
  4802. \draw (x) to (w);
  4803. \draw (y) to (w);
  4804. \draw (v) to (w);
  4805. \draw (v) to (rsp);
  4806. \draw (w) to (rsp);
  4807. \draw (x) to (rsp);
  4808. \draw (y) to (rsp);
  4809. \path[-.,bend left=15] (z) edge node {} (rsp);
  4810. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4811. \draw (rax) to (rsp);
  4812. \end{tikzpicture}
  4813. \]
  4814. So we obtain the following coloring:
  4815. \[
  4816. \{
  4817. \ttm{rax} \mapsto -1,
  4818. \ttm{rsp} \mapsto -2,
  4819. \ttm{t} \mapsto 0,
  4820. \ttm{z} \mapsto 1,
  4821. \ttm{x} \mapsto 1,
  4822. \ttm{y} \mapsto 2,
  4823. \ttm{w} \mapsto 0,
  4824. \ttm{v} \mapsto 1
  4825. \}
  4826. \]
  4827. \fi}
  4828. %
  4829. {\if\edition\pythonEd
  4830. %
  4831. With the DSATUR algorithm in hand, let us return to the running
  4832. example and consider how to color the interference graph in
  4833. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4834. to indicate that it has not yet been assigned a color. The saturation
  4835. sets are also shown for each node; all of them start as the empty set.
  4836. (We do not include the register nodes in the graph below because there
  4837. were no interference edges involving registers in this program, but in
  4838. general there can be.)
  4839. %
  4840. \[
  4841. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4842. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4843. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4844. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4845. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4846. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4847. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4848. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4849. \draw (t0) to (t1);
  4850. \draw (t0) to (z);
  4851. \draw (z) to (y);
  4852. \draw (z) to (w);
  4853. \draw (x) to (w);
  4854. \draw (y) to (w);
  4855. \draw (v) to (w);
  4856. \end{tikzpicture}
  4857. \]
  4858. The algorithm says to select a maximally saturated vertex, but they
  4859. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4860. then color it with the first available integer, which is $0$. We mark
  4861. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4862. they interfere with $\ttm{tmp\_0}$.
  4863. \[
  4864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4865. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4866. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4867. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4868. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4869. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4870. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4871. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4872. \draw (t0) to (t1);
  4873. \draw (t0) to (z);
  4874. \draw (z) to (y);
  4875. \draw (z) to (w);
  4876. \draw (x) to (w);
  4877. \draw (y) to (w);
  4878. \draw (v) to (w);
  4879. \end{tikzpicture}
  4880. \]
  4881. We repeat the process. The most saturated vertices are \code{z} and
  4882. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4883. available number, which is $1$. We add $1$ to the saturation for the
  4884. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4885. \[
  4886. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4887. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4888. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4889. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4890. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4891. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4892. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4893. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4894. \draw (t0) to (t1);
  4895. \draw (t0) to (z);
  4896. \draw (z) to (y);
  4897. \draw (z) to (w);
  4898. \draw (x) to (w);
  4899. \draw (y) to (w);
  4900. \draw (v) to (w);
  4901. \end{tikzpicture}
  4902. \]
  4903. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4904. \code{y}. We color \code{w} with the first available color, which
  4905. is $0$.
  4906. \[
  4907. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4908. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4909. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4910. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4911. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4912. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4913. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4914. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4915. \draw (t0) to (t1);
  4916. \draw (t0) to (z);
  4917. \draw (z) to (y);
  4918. \draw (z) to (w);
  4919. \draw (x) to (w);
  4920. \draw (y) to (w);
  4921. \draw (v) to (w);
  4922. \end{tikzpicture}
  4923. \]
  4924. Now \code{y} is the most saturated, so we color it with $2$.
  4925. \[
  4926. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4927. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4928. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4929. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4930. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4931. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4932. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4933. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4934. \draw (t0) to (t1);
  4935. \draw (t0) to (z);
  4936. \draw (z) to (y);
  4937. \draw (z) to (w);
  4938. \draw (x) to (w);
  4939. \draw (y) to (w);
  4940. \draw (v) to (w);
  4941. \end{tikzpicture}
  4942. \]
  4943. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4944. We choose to color \code{v} with $1$.
  4945. \[
  4946. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4947. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4948. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4949. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4950. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4951. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4952. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4953. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4954. \draw (t0) to (t1);
  4955. \draw (t0) to (z);
  4956. \draw (z) to (y);
  4957. \draw (z) to (w);
  4958. \draw (x) to (w);
  4959. \draw (y) to (w);
  4960. \draw (v) to (w);
  4961. \end{tikzpicture}
  4962. \]
  4963. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4964. \[
  4965. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4966. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4967. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4968. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4969. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4970. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4971. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4972. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4973. \draw (t0) to (t1);
  4974. \draw (t0) to (z);
  4975. \draw (z) to (y);
  4976. \draw (z) to (w);
  4977. \draw (x) to (w);
  4978. \draw (y) to (w);
  4979. \draw (v) to (w);
  4980. \end{tikzpicture}
  4981. \]
  4982. So we obtain the following coloring:
  4983. \[
  4984. \{ \ttm{tmp\_0} \mapsto 0,
  4985. \ttm{tmp\_1} \mapsto 1,
  4986. \ttm{z} \mapsto 1,
  4987. \ttm{x} \mapsto 1,
  4988. \ttm{y} \mapsto 2,
  4989. \ttm{w} \mapsto 0,
  4990. \ttm{v} \mapsto 1 \}
  4991. \]
  4992. \fi}
  4993. We recommend creating an auxiliary function named \code{color\_graph}
  4994. that takes an interference graph and a list of all the variables in
  4995. the program. This function should return a mapping of variables to
  4996. their colors (represented as natural numbers). By creating this helper
  4997. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4998. when we add support for functions.
  4999. To prioritize the processing of highly saturated nodes inside the
  5000. \code{color\_graph} function, we recommend using the priority queue
  5001. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5002. addition, you will need to maintain a mapping from variables to their
  5003. ``handles'' in the priority queue so that you can notify the priority
  5004. queue when their saturation changes.}
  5005. {\if\edition\racketEd
  5006. \begin{figure}[tp]
  5007. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5008. \small
  5009. \begin{tcolorbox}[title=Priority Queue]
  5010. A \emph{priority queue} is a collection of items in which the
  5011. removal of items is governed by priority. In a ``min'' queue,
  5012. lower priority items are removed first. An implementation is in
  5013. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5014. queue} \index{subject}{minimum priority queue}
  5015. \begin{description}
  5016. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5017. priority queue that uses the $\itm{cmp}$ predicate to determine
  5018. whether its first argument has lower or equal priority to its
  5019. second argument.
  5020. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5021. items in the queue.
  5022. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5023. the item into the queue and returns a handle for the item in the
  5024. queue.
  5025. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5026. the lowest priority.
  5027. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5028. notifies the queue that the priority has decreased for the item
  5029. associated with the given handle.
  5030. \end{description}
  5031. \end{tcolorbox}
  5032. %\end{wrapfigure}
  5033. \caption{The priority queue data structure.}
  5034. \label{fig:priority-queue}
  5035. \end{figure}
  5036. \fi}
  5037. With the coloring complete, we finalize the assignment of variables to
  5038. registers and stack locations. We map the first $k$ colors to the $k$
  5039. registers and the rest of the colors to stack locations. Suppose for
  5040. the moment that we have just one register to use for register
  5041. allocation, \key{rcx}. Then we have the following map from colors to
  5042. locations.
  5043. \[
  5044. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5045. \]
  5046. Composing this mapping with the coloring, we arrive at the following
  5047. assignment of variables to locations.
  5048. {\if\edition\racketEd
  5049. \begin{gather*}
  5050. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5051. \ttm{w} \mapsto \key{\%rcx}, \,
  5052. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5053. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5054. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5055. \ttm{t} \mapsto \key{\%rcx} \}
  5056. \end{gather*}
  5057. \fi}
  5058. {\if\edition\pythonEd
  5059. \begin{gather*}
  5060. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5061. \ttm{w} \mapsto \key{\%rcx}, \,
  5062. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5063. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5064. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5065. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5066. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5067. \end{gather*}
  5068. \fi}
  5069. Adapt the code from the \code{assign\_homes} pass
  5070. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5071. assigned location. Applying the above assignment to our running
  5072. example, on the left, yields the program on the right.
  5073. % why frame size of 32? -JGS
  5074. \begin{center}
  5075. {\if\edition\racketEd
  5076. \begin{minipage}{0.3\textwidth}
  5077. \begin{lstlisting}
  5078. movq $1, v
  5079. movq $42, w
  5080. movq v, x
  5081. addq $7, x
  5082. movq x, y
  5083. movq x, z
  5084. addq w, z
  5085. movq y, t
  5086. negq t
  5087. movq z, %rax
  5088. addq t, %rax
  5089. jmp conclusion
  5090. \end{lstlisting}
  5091. \end{minipage}
  5092. $\Rightarrow\qquad$
  5093. \begin{minipage}{0.45\textwidth}
  5094. \begin{lstlisting}
  5095. movq $1, -8(%rbp)
  5096. movq $42, %rcx
  5097. movq -8(%rbp), -8(%rbp)
  5098. addq $7, -8(%rbp)
  5099. movq -8(%rbp), -16(%rbp)
  5100. movq -8(%rbp), -8(%rbp)
  5101. addq %rcx, -8(%rbp)
  5102. movq -16(%rbp), %rcx
  5103. negq %rcx
  5104. movq -8(%rbp), %rax
  5105. addq %rcx, %rax
  5106. jmp conclusion
  5107. \end{lstlisting}
  5108. \end{minipage}
  5109. \fi}
  5110. {\if\edition\pythonEd
  5111. \begin{minipage}{0.3\textwidth}
  5112. \begin{lstlisting}
  5113. movq $1, v
  5114. movq $42, w
  5115. movq v, x
  5116. addq $7, x
  5117. movq x, y
  5118. movq x, z
  5119. addq w, z
  5120. movq y, tmp_0
  5121. negq tmp_0
  5122. movq z, tmp_1
  5123. addq tmp_0, tmp_1
  5124. movq tmp_1, %rdi
  5125. callq print_int
  5126. \end{lstlisting}
  5127. \end{minipage}
  5128. $\Rightarrow\qquad$
  5129. \begin{minipage}{0.45\textwidth}
  5130. \begin{lstlisting}
  5131. movq $1, -8(%rbp)
  5132. movq $42, %rcx
  5133. movq -8(%rbp), -8(%rbp)
  5134. addq $7, -8(%rbp)
  5135. movq -8(%rbp), -16(%rbp)
  5136. movq -8(%rbp), -8(%rbp)
  5137. addq %rcx, -8(%rbp)
  5138. movq -16(%rbp), %rcx
  5139. negq %rcx
  5140. movq -8(%rbp), -8(%rbp)
  5141. addq %rcx, -8(%rbp)
  5142. movq -8(%rbp), %rdi
  5143. callq print_int
  5144. \end{lstlisting}
  5145. \end{minipage}
  5146. \fi}
  5147. \end{center}
  5148. \begin{exercise}\normalfont\normalsize
  5149. Implement the \code{allocate\_registers} pass.
  5150. Create five programs that exercise all aspects of the register
  5151. allocation algorithm, including spilling variables to the stack.
  5152. %
  5153. {\if\edition\racketEd
  5154. Replace \code{assign\_homes} in the list of \code{passes} in the
  5155. \code{run-tests.rkt} script with the three new passes:
  5156. \code{uncover\_live}, \code{build\_interference}, and
  5157. \code{allocate\_registers}.
  5158. Temporarily remove the call to \code{compiler-tests}.
  5159. Run the script to test the register allocator.
  5160. \fi}
  5161. %
  5162. {\if\edition\pythonEd
  5163. Run the \code{run-tests.py} script to to check whether the
  5164. output programs produce the same result as the input programs.
  5165. \fi}
  5166. \end{exercise}
  5167. \section{Patch Instructions}
  5168. \label{sec:patch-instructions}
  5169. The remaining step in the compilation to x86 is to ensure that the
  5170. instructions have at most one argument that is a memory access.
  5171. %
  5172. In the running example, the instruction \code{movq -8(\%rbp),
  5173. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5174. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5175. then move \code{rax} into \code{-16(\%rbp)}.
  5176. %
  5177. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5178. problematic, but they can simply be deleted. In general, we recommend
  5179. deleting all the trivial moves whose source and destination are the
  5180. same location.
  5181. %
  5182. The following is the output of \code{patch\_instructions} on the
  5183. running example.
  5184. \begin{center}
  5185. {\if\edition\racketEd
  5186. \begin{minipage}{0.4\textwidth}
  5187. \begin{lstlisting}
  5188. movq $1, -8(%rbp)
  5189. movq $42, %rcx
  5190. movq -8(%rbp), -8(%rbp)
  5191. addq $7, -8(%rbp)
  5192. movq -8(%rbp), -16(%rbp)
  5193. movq -8(%rbp), -8(%rbp)
  5194. addq %rcx, -8(%rbp)
  5195. movq -16(%rbp), %rcx
  5196. negq %rcx
  5197. movq -8(%rbp), %rax
  5198. addq %rcx, %rax
  5199. jmp conclusion
  5200. \end{lstlisting}
  5201. \end{minipage}
  5202. $\Rightarrow\qquad$
  5203. \begin{minipage}{0.45\textwidth}
  5204. \begin{lstlisting}
  5205. movq $1, -8(%rbp)
  5206. movq $42, %rcx
  5207. addq $7, -8(%rbp)
  5208. movq -8(%rbp), %rax
  5209. movq %rax, -16(%rbp)
  5210. addq %rcx, -8(%rbp)
  5211. movq -16(%rbp), %rcx
  5212. negq %rcx
  5213. movq -8(%rbp), %rax
  5214. addq %rcx, %rax
  5215. jmp conclusion
  5216. \end{lstlisting}
  5217. \end{minipage}
  5218. \fi}
  5219. {\if\edition\pythonEd
  5220. \begin{minipage}{0.4\textwidth}
  5221. \begin{lstlisting}
  5222. movq $1, -8(%rbp)
  5223. movq $42, %rcx
  5224. movq -8(%rbp), -8(%rbp)
  5225. addq $7, -8(%rbp)
  5226. movq -8(%rbp), -16(%rbp)
  5227. movq -8(%rbp), -8(%rbp)
  5228. addq %rcx, -8(%rbp)
  5229. movq -16(%rbp), %rcx
  5230. negq %rcx
  5231. movq -8(%rbp), -8(%rbp)
  5232. addq %rcx, -8(%rbp)
  5233. movq -8(%rbp), %rdi
  5234. callq print_int
  5235. \end{lstlisting}
  5236. \end{minipage}
  5237. $\Rightarrow\qquad$
  5238. \begin{minipage}{0.45\textwidth}
  5239. \begin{lstlisting}
  5240. movq $1, -8(%rbp)
  5241. movq $42, %rcx
  5242. addq $7, -8(%rbp)
  5243. movq -8(%rbp), %rax
  5244. movq %rax, -16(%rbp)
  5245. addq %rcx, -8(%rbp)
  5246. movq -16(%rbp), %rcx
  5247. negq %rcx
  5248. addq %rcx, -8(%rbp)
  5249. movq -8(%rbp), %rdi
  5250. callq print_int
  5251. \end{lstlisting}
  5252. \end{minipage}
  5253. \fi}
  5254. \end{center}
  5255. \begin{exercise}\normalfont\normalsize
  5256. %
  5257. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5258. %
  5259. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5260. %in the \code{run-tests.rkt} script.
  5261. %
  5262. Run the script to test the \code{patch\_instructions} pass.
  5263. \end{exercise}
  5264. \section{Prelude and Conclusion}
  5265. \label{sec:print-x86-reg-alloc}
  5266. \index{subject}{calling conventions}
  5267. \index{subject}{prelude}\index{subject}{conclusion}
  5268. Recall that this pass generates the prelude and conclusion
  5269. instructions to satisfy the x86 calling conventions
  5270. (Section~\ref{sec:calling-conventions}). With the addition of the
  5271. register allocator, the callee-saved registers used by the register
  5272. allocator must be saved in the prelude and restored in the conclusion.
  5273. In the \code{allocate\_registers} pass,
  5274. %
  5275. \racket{add an entry to the \itm{info}
  5276. of \code{X86Program} named \code{used\_callee}}
  5277. %
  5278. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5279. %
  5280. that stores the set of callee-saved registers that were assigned to
  5281. variables. The \code{prelude\_and\_conclusion} pass can then access
  5282. this information to decide which callee-saved registers need to be
  5283. saved and restored.
  5284. %
  5285. When calculating the amount to adjust the \code{rsp} in the prelude,
  5286. make sure to take into account the space used for saving the
  5287. callee-saved registers. Also, don't forget that the frame needs to be
  5288. a multiple of 16 bytes! We recommend using the following equation for
  5289. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5290. of spilled variables and $C$ be the number of callee-saved registers
  5291. that were allocated to variables. The $\itm{align}$ function rounds a
  5292. number up to the nearest 16 bytes.
  5293. \[
  5294. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5295. \]
  5296. The reason we subtract $8\itm{C}$ in the above equation is because the
  5297. prelude uses \code{pushq} to save each of the callee-saved registers,
  5298. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5299. \racket{An overview of all of the passes involved in register
  5300. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5301. {\if\edition\racketEd
  5302. \begin{figure}[tbp]
  5303. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5304. \node (Lvar) at (0,2) {\large \LangVar{}};
  5305. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5306. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5307. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5308. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5309. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5310. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5311. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5312. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5313. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5314. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5315. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5316. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5317. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5318. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5319. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5320. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5321. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5322. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5323. \end{tikzpicture}
  5324. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5325. \label{fig:reg-alloc-passes}
  5326. \end{figure}
  5327. \fi}
  5328. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5329. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5330. use of registers and the stack, we limit the register allocator for
  5331. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5332. the prelude\index{subject}{prelude} of the \code{main} function, we
  5333. push \code{rbx} onto the stack because it is a callee-saved register
  5334. and it was assigned to a variable by the register allocator. We
  5335. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5336. reserve space for the one spilled variable. After that subtraction,
  5337. the \code{rsp} is aligned to 16 bytes.
  5338. Moving on to the program proper, we see how the registers were
  5339. allocated.
  5340. %
  5341. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5342. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5343. %
  5344. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5345. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5346. were assigned to \code{rbx}.}
  5347. %
  5348. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5349. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5350. callee-save register \code{rbx} onto the stack. The spilled variables
  5351. must be placed lower on the stack than the saved callee-save
  5352. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5353. \code{-16(\%rbp)}.
  5354. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5355. done in the prelude. We move the stack pointer up by \code{8} bytes
  5356. (the room for spilled variables), then we pop the old values of
  5357. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5358. \code{retq} to return control to the operating system.
  5359. \begin{figure}[tbp]
  5360. % var_test_28.rkt
  5361. % (use-minimal-set-of-registers! #t)
  5362. % and only rbx rcx
  5363. % tmp 0 rbx
  5364. % z 1 rcx
  5365. % y 0 rbx
  5366. % w 2 16(%rbp)
  5367. % v 0 rbx
  5368. % x 0 rbx
  5369. {\if\edition\racketEd
  5370. \begin{lstlisting}
  5371. start:
  5372. movq $1, %rbx
  5373. movq $42, -16(%rbp)
  5374. addq $7, %rbx
  5375. movq %rbx, %rcx
  5376. addq -16(%rbp), %rcx
  5377. negq %rbx
  5378. movq %rcx, %rax
  5379. addq %rbx, %rax
  5380. jmp conclusion
  5381. .globl main
  5382. main:
  5383. pushq %rbp
  5384. movq %rsp, %rbp
  5385. pushq %rbx
  5386. subq $8, %rsp
  5387. jmp start
  5388. conclusion:
  5389. addq $8, %rsp
  5390. popq %rbx
  5391. popq %rbp
  5392. retq
  5393. \end{lstlisting}
  5394. \fi}
  5395. {\if\edition\pythonEd
  5396. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5397. \begin{lstlisting}
  5398. .globl main
  5399. main:
  5400. pushq %rbp
  5401. movq %rsp, %rbp
  5402. pushq %rbx
  5403. subq $8, %rsp
  5404. movq $1, %rcx
  5405. movq $42, %rbx
  5406. addq $7, %rcx
  5407. movq %rcx, -16(%rbp)
  5408. addq %rbx, -16(%rbp)
  5409. negq %rcx
  5410. movq -16(%rbp), %rbx
  5411. addq %rcx, %rbx
  5412. movq %rbx, %rdi
  5413. callq print_int
  5414. addq $8, %rsp
  5415. popq %rbx
  5416. popq %rbp
  5417. retq
  5418. \end{lstlisting}
  5419. \fi}
  5420. \caption{The x86 output from the running example
  5421. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5422. and \code{rcx}.}
  5423. \label{fig:running-example-x86}
  5424. \end{figure}
  5425. \begin{exercise}\normalfont\normalsize
  5426. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5427. %
  5428. \racket{
  5429. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5430. list of passes and the call to \code{compiler-tests}.}
  5431. %
  5432. Run the script to test the complete compiler for \LangVar{} that
  5433. performs register allocation.
  5434. \end{exercise}
  5435. \section{Challenge: Move Biasing}
  5436. \label{sec:move-biasing}
  5437. \index{subject}{move biasing}
  5438. This section describes an enhancement to the register allocator,
  5439. called move biasing, for students who are looking for an extra
  5440. challenge.
  5441. {\if\edition\racketEd
  5442. To motivate the need for move biasing we return to the running example
  5443. but this time we use all of the general purpose registers. So we have
  5444. the following mapping of color numbers to registers.
  5445. \[
  5446. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5447. \]
  5448. Using the same assignment of variables to color numbers that was
  5449. produced by the register allocator described in the last section, we
  5450. get the following program.
  5451. \begin{center}
  5452. \begin{minipage}{0.3\textwidth}
  5453. \begin{lstlisting}
  5454. movq $1, v
  5455. movq $42, w
  5456. movq v, x
  5457. addq $7, x
  5458. movq x, y
  5459. movq x, z
  5460. addq w, z
  5461. movq y, t
  5462. negq t
  5463. movq z, %rax
  5464. addq t, %rax
  5465. jmp conclusion
  5466. \end{lstlisting}
  5467. \end{minipage}
  5468. $\Rightarrow\qquad$
  5469. \begin{minipage}{0.45\textwidth}
  5470. \begin{lstlisting}
  5471. movq $1, %rdx
  5472. movq $42, %rcx
  5473. movq %rdx, %rdx
  5474. addq $7, %rdx
  5475. movq %rdx, %rsi
  5476. movq %rdx, %rdx
  5477. addq %rcx, %rdx
  5478. movq %rsi, %rcx
  5479. negq %rcx
  5480. movq %rdx, %rax
  5481. addq %rcx, %rax
  5482. jmp conclusion
  5483. \end{lstlisting}
  5484. \end{minipage}
  5485. \end{center}
  5486. In the above output code there are two \key{movq} instructions that
  5487. can be removed because their source and target are the same. However,
  5488. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5489. register, we could instead remove three \key{movq} instructions. We
  5490. can accomplish this by taking into account which variables appear in
  5491. \key{movq} instructions with which other variables.
  5492. \fi}
  5493. {\if\edition\pythonEd
  5494. %
  5495. To motivate the need for move biasing we return to the running example
  5496. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5497. remove three trivial move instructions from the running
  5498. example. However, we could remove another trivial move if we were able
  5499. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5500. We say that two variables $p$ and $q$ are \emph{move
  5501. related}\index{subject}{move related} if they participate together in
  5502. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5503. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5504. when there are multiple variables with the same saturation, prefer
  5505. variables that can be assigned to a color that is the same as the
  5506. color of a move related variable. Furthermore, when the register
  5507. allocator chooses a color for a variable, it should prefer a color
  5508. that has already been used for a move-related variable (assuming that
  5509. they do not interfere). Of course, this preference should not override
  5510. the preference for registers over stack locations. So this preference
  5511. should be used as a tie breaker when choosing between registers or
  5512. when choosing between stack locations.
  5513. We recommend representing the move relationships in a graph, similar
  5514. to how we represented interference. The following is the \emph{move
  5515. graph} for our running example.
  5516. {\if\edition\racketEd
  5517. \[
  5518. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5519. \node (rax) at (0,0) {$\ttm{rax}$};
  5520. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5521. \node (t) at (0,2) {$\ttm{t}$};
  5522. \node (z) at (3,2) {$\ttm{z}$};
  5523. \node (x) at (6,2) {$\ttm{x}$};
  5524. \node (y) at (3,0) {$\ttm{y}$};
  5525. \node (w) at (6,0) {$\ttm{w}$};
  5526. \node (v) at (9,0) {$\ttm{v}$};
  5527. \draw (v) to (x);
  5528. \draw (x) to (y);
  5529. \draw (x) to (z);
  5530. \draw (y) to (t);
  5531. \end{tikzpicture}
  5532. \]
  5533. \fi}
  5534. %
  5535. {\if\edition\pythonEd
  5536. \[
  5537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5538. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5539. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5540. \node (z) at (3,2) {$\ttm{z}$};
  5541. \node (x) at (6,2) {$\ttm{x}$};
  5542. \node (y) at (3,0) {$\ttm{y}$};
  5543. \node (w) at (6,0) {$\ttm{w}$};
  5544. \node (v) at (9,0) {$\ttm{v}$};
  5545. \draw (y) to (t0);
  5546. \draw (z) to (x);
  5547. \draw (z) to (t1);
  5548. \draw (x) to (y);
  5549. \draw (x) to (v);
  5550. \end{tikzpicture}
  5551. \]
  5552. \fi}
  5553. {\if\edition\racketEd
  5554. Now we replay the graph coloring, pausing to see the coloring of
  5555. \code{y}. Recall the following configuration. The most saturated vertices
  5556. were \code{w} and \code{y}.
  5557. \[
  5558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5559. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5560. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5561. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5562. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5563. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5564. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5565. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5566. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5567. \draw (t1) to (rax);
  5568. \draw (t1) to (z);
  5569. \draw (z) to (y);
  5570. \draw (z) to (w);
  5571. \draw (x) to (w);
  5572. \draw (y) to (w);
  5573. \draw (v) to (w);
  5574. \draw (v) to (rsp);
  5575. \draw (w) to (rsp);
  5576. \draw (x) to (rsp);
  5577. \draw (y) to (rsp);
  5578. \path[-.,bend left=15] (z) edge node {} (rsp);
  5579. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5580. \draw (rax) to (rsp);
  5581. \end{tikzpicture}
  5582. \]
  5583. %
  5584. Last time we chose to color \code{w} with $0$. But this time we see
  5585. that \code{w} is not move related to any vertex, but \code{y} is move
  5586. related to \code{t}. So we choose to color \code{y} with $0$, the
  5587. same color as \code{t}.
  5588. \[
  5589. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5590. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5591. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5592. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5593. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5594. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5595. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5596. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5597. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5598. \draw (t1) to (rax);
  5599. \draw (t1) to (z);
  5600. \draw (z) to (y);
  5601. \draw (z) to (w);
  5602. \draw (x) to (w);
  5603. \draw (y) to (w);
  5604. \draw (v) to (w);
  5605. \draw (v) to (rsp);
  5606. \draw (w) to (rsp);
  5607. \draw (x) to (rsp);
  5608. \draw (y) to (rsp);
  5609. \path[-.,bend left=15] (z) edge node {} (rsp);
  5610. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5611. \draw (rax) to (rsp);
  5612. \end{tikzpicture}
  5613. \]
  5614. Now \code{w} is the most saturated, so we color it $2$.
  5615. \[
  5616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5617. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5618. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5619. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5620. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5621. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5622. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5623. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5624. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5625. \draw (t1) to (rax);
  5626. \draw (t1) to (z);
  5627. \draw (z) to (y);
  5628. \draw (z) to (w);
  5629. \draw (x) to (w);
  5630. \draw (y) to (w);
  5631. \draw (v) to (w);
  5632. \draw (v) to (rsp);
  5633. \draw (w) to (rsp);
  5634. \draw (x) to (rsp);
  5635. \draw (y) to (rsp);
  5636. \path[-.,bend left=15] (z) edge node {} (rsp);
  5637. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5638. \draw (rax) to (rsp);
  5639. \end{tikzpicture}
  5640. \]
  5641. At this point, vertices \code{x} and \code{v} are most saturated, but
  5642. \code{x} is move related to \code{y} and \code{z}, so we color
  5643. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5644. \[
  5645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5646. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5647. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5648. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5649. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5650. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5651. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5652. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5653. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5654. \draw (t1) to (rax);
  5655. \draw (t) to (z);
  5656. \draw (z) to (y);
  5657. \draw (z) to (w);
  5658. \draw (x) to (w);
  5659. \draw (y) to (w);
  5660. \draw (v) to (w);
  5661. \draw (v) to (rsp);
  5662. \draw (w) to (rsp);
  5663. \draw (x) to (rsp);
  5664. \draw (y) to (rsp);
  5665. \path[-.,bend left=15] (z) edge node {} (rsp);
  5666. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5667. \draw (rax) to (rsp);
  5668. \end{tikzpicture}
  5669. \]
  5670. \fi}
  5671. %
  5672. {\if\edition\pythonEd
  5673. Now we replay the graph coloring, pausing before the coloring of
  5674. \code{w}. Recall the following configuration. The most saturated vertices
  5675. were \code{tmp\_1}, \code{w}, and \code{y}.
  5676. \[
  5677. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5678. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5679. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5680. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5681. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5682. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5683. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5684. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5685. \draw (t0) to (t1);
  5686. \draw (t0) to (z);
  5687. \draw (z) to (y);
  5688. \draw (z) to (w);
  5689. \draw (x) to (w);
  5690. \draw (y) to (w);
  5691. \draw (v) to (w);
  5692. \end{tikzpicture}
  5693. \]
  5694. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5695. or \code{y}, but note that \code{w} is not move related to any
  5696. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5697. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5698. \code{y} and color it $0$, we can delete another move instruction.
  5699. \[
  5700. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5701. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5702. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5703. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5704. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5705. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5706. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5707. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5708. \draw (t0) to (t1);
  5709. \draw (t0) to (z);
  5710. \draw (z) to (y);
  5711. \draw (z) to (w);
  5712. \draw (x) to (w);
  5713. \draw (y) to (w);
  5714. \draw (v) to (w);
  5715. \end{tikzpicture}
  5716. \]
  5717. Now \code{w} is the most saturated, so we color it $2$.
  5718. \[
  5719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5720. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5721. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5722. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5723. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5724. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5725. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5726. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5727. \draw (t0) to (t1);
  5728. \draw (t0) to (z);
  5729. \draw (z) to (y);
  5730. \draw (z) to (w);
  5731. \draw (x) to (w);
  5732. \draw (y) to (w);
  5733. \draw (v) to (w);
  5734. \end{tikzpicture}
  5735. \]
  5736. To finish the coloring, \code{x} and \code{v} get $0$ and
  5737. \code{tmp\_1} gets $1$.
  5738. \[
  5739. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5740. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5741. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5742. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5743. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5744. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5745. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5746. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5747. \draw (t0) to (t1);
  5748. \draw (t0) to (z);
  5749. \draw (z) to (y);
  5750. \draw (z) to (w);
  5751. \draw (x) to (w);
  5752. \draw (y) to (w);
  5753. \draw (v) to (w);
  5754. \end{tikzpicture}
  5755. \]
  5756. \fi}
  5757. So we have the following assignment of variables to registers.
  5758. {\if\edition\racketEd
  5759. \begin{gather*}
  5760. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5761. \ttm{w} \mapsto \key{\%rsi}, \,
  5762. \ttm{x} \mapsto \key{\%rcx}, \,
  5763. \ttm{y} \mapsto \key{\%rcx}, \,
  5764. \ttm{z} \mapsto \key{\%rdx}, \,
  5765. \ttm{t} \mapsto \key{\%rcx} \}
  5766. \end{gather*}
  5767. \fi}
  5768. {\if\edition\pythonEd
  5769. \begin{gather*}
  5770. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5771. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5772. \ttm{x} \mapsto \key{\%rcx}, \,
  5773. \ttm{y} \mapsto \key{\%rcx}, \\
  5774. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5775. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5776. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5777. \end{gather*}
  5778. \fi}
  5779. We apply this register assignment to the running example, on the left,
  5780. to obtain the code in the middle. The \code{patch\_instructions} then
  5781. deletes the trivial moves to obtain the code on the right.
  5782. {\if\edition\racketEd
  5783. \begin{minipage}{0.25\textwidth}
  5784. \begin{lstlisting}
  5785. movq $1, v
  5786. movq $42, w
  5787. movq v, x
  5788. addq $7, x
  5789. movq x, y
  5790. movq x, z
  5791. addq w, z
  5792. movq y, t
  5793. negq t
  5794. movq z, %rax
  5795. addq t, %rax
  5796. jmp conclusion
  5797. \end{lstlisting}
  5798. \end{minipage}
  5799. $\Rightarrow\qquad$
  5800. \begin{minipage}{0.25\textwidth}
  5801. \begin{lstlisting}
  5802. movq $1, %rcx
  5803. movq $42, %rsi
  5804. movq %rcx, %rcx
  5805. addq $7, %rcx
  5806. movq %rcx, %rcx
  5807. movq %rcx, %rdx
  5808. addq %rsi, %rdx
  5809. movq %rcx, %rcx
  5810. negq %rcx
  5811. movq %rdx, %rax
  5812. addq %rcx, %rax
  5813. jmp conclusion
  5814. \end{lstlisting}
  5815. \end{minipage}
  5816. $\Rightarrow\qquad$
  5817. \begin{minipage}{0.25\textwidth}
  5818. \begin{lstlisting}
  5819. movq $1, %rcx
  5820. movq $42, %rsi
  5821. addq $7, %rcx
  5822. movq %rcx, %rdx
  5823. addq %rsi, %rdx
  5824. negq %rcx
  5825. movq %rdx, %rax
  5826. addq %rcx, %rax
  5827. jmp conclusion
  5828. \end{lstlisting}
  5829. \end{minipage}
  5830. \fi}
  5831. {\if\edition\pythonEd
  5832. \begin{minipage}{0.20\textwidth}
  5833. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5834. movq $1, v
  5835. movq $42, w
  5836. movq v, x
  5837. addq $7, x
  5838. movq x, y
  5839. movq x, z
  5840. addq w, z
  5841. movq y, tmp_0
  5842. negq tmp_0
  5843. movq z, tmp_1
  5844. addq tmp_0, tmp_1
  5845. movq tmp_1, %rdi
  5846. callq _print_int
  5847. \end{lstlisting}
  5848. \end{minipage}
  5849. ${\Rightarrow\qquad}$
  5850. \begin{minipage}{0.30\textwidth}
  5851. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5852. movq $1, %rcx
  5853. movq $42, -16(%rbp)
  5854. movq %rcx, %rcx
  5855. addq $7, %rcx
  5856. movq %rcx, %rcx
  5857. movq %rcx, -8(%rbp)
  5858. addq -16(%rbp), -8(%rbp)
  5859. movq %rcx, %rcx
  5860. negq %rcx
  5861. movq -8(%rbp), -8(%rbp)
  5862. addq %rcx, -8(%rbp)
  5863. movq -8(%rbp), %rdi
  5864. callq _print_int
  5865. \end{lstlisting}
  5866. \end{minipage}
  5867. ${\Rightarrow\qquad}$
  5868. \begin{minipage}{0.20\textwidth}
  5869. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5870. movq $1, %rcx
  5871. movq $42, -16(%rbp)
  5872. addq $7, %rcx
  5873. movq %rcx, -8(%rbp)
  5874. movq -16(%rbp), %rax
  5875. addq %rax, -8(%rbp)
  5876. negq %rcx
  5877. addq %rcx, -8(%rbp)
  5878. movq -8(%rbp), %rdi
  5879. callq print_int
  5880. \end{lstlisting}
  5881. \end{minipage}
  5882. \fi}
  5883. \begin{exercise}\normalfont\normalsize
  5884. Change your implementation of \code{allocate\_registers} to take move
  5885. biasing into account. Create two new tests that include at least one
  5886. opportunity for move biasing and visually inspect the output x86
  5887. programs to make sure that your move biasing is working properly. Make
  5888. sure that your compiler still passes all of the tests.
  5889. \end{exercise}
  5890. %To do: another neat challenge would be to do
  5891. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5892. %% \subsection{Output of the Running Example}
  5893. %% \label{sec:reg-alloc-output}
  5894. % challenge: prioritize variables based on execution frequencies
  5895. % and the number of uses of a variable
  5896. % challenge: enhance the coloring algorithm using Chaitin's
  5897. % approach of prioritizing high-degree variables
  5898. % by removing low-degree variables (coloring them later)
  5899. % from the interference graph
  5900. \section{Further Reading}
  5901. \label{sec:register-allocation-further-reading}
  5902. Early register allocation algorithms were developed for Fortran
  5903. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5904. of graph coloring began in the late 1970s and early 1980s with the
  5905. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5906. algorithm is based on the following observation of
  5907. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5908. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5909. $v$ removed is also $k$ colorable. To see why, suppose that the
  5910. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5911. different colors, but since there are less than $k$ neighbors, there
  5912. will be one or more colors left over to use for coloring $v$ in $G$.
  5913. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5914. less than $k$ from the graph and recursively colors the rest of the
  5915. graph. Upon returning from the recursion, it colors $v$ with one of
  5916. the available colors and returns. \citet{Chaitin:1982vn} augments
  5917. this algorithm to handle spilling as follows. If there are no vertices
  5918. of degree lower than $k$ then pick a vertex at random, spill it,
  5919. remove it from the graph, and proceed recursively to color the rest of
  5920. the graph.
  5921. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5922. move-related and that don't interfere with each other, a process
  5923. called \emph{coalescing}. While coalescing decreases the number of
  5924. moves, it can make the graph more difficult to
  5925. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5926. which two variables are merged only if they have fewer than $k$
  5927. neighbors of high degree. \citet{George:1996aa} observe that
  5928. conservative coalescing is sometimes too conservative and make it more
  5929. aggressive by iterating the coalescing with the removal of low-degree
  5930. vertices.
  5931. %
  5932. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5933. also propose \emph{biased coloring} in which a variable is assigned to
  5934. the same color as another move-related variable if possible, as
  5935. discussed in Section~\ref{sec:move-biasing}.
  5936. %
  5937. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5938. performs coalescing, graph coloring, and spill code insertion until
  5939. all variables have been assigned a location.
  5940. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5941. spills variables that don't have to be: a high-degree variable can be
  5942. colorable if many of its neighbors are assigned the same color.
  5943. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5944. high-degree vertex is not immediately spilled. Instead the decision is
  5945. deferred until after the recursive call, at which point it is apparent
  5946. whether there is actually an available color or not. We observe that
  5947. this algorithm is equivalent to the smallest-last ordering
  5948. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5949. be registers and the rest to be stack locations.
  5950. %% biased coloring
  5951. Earlier editions of the compiler course at Indiana University
  5952. \citep{Dybvig:2010aa} were based on the algorithm of
  5953. \citet{Briggs:1994kx}.
  5954. The smallest-last ordering algorithm is one of many \emph{greedy}
  5955. coloring algorithms. A greedy coloring algorithm visits all the
  5956. vertices in a particular order and assigns each one the first
  5957. available color. An \emph{offline} greedy algorithm chooses the
  5958. ordering up-front, prior to assigning colors. The algorithm of
  5959. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5960. ordering does not depend on the colors assigned. Other orderings are
  5961. possible. For example, \citet{Chow:1984ys} order variables according
  5962. to an estimate of runtime cost.
  5963. An \emph{online} greedy coloring algorithm uses information about the
  5964. current assignment of colors to influence the order in which the
  5965. remaining vertices are colored. The saturation-based algorithm
  5966. described in this chapter is one such algorithm. We choose to use
  5967. saturation-based coloring because it is fun to introduce graph
  5968. coloring via Sudoku!
  5969. A register allocator may choose to map each variable to just one
  5970. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5971. variable to one or more locations. The later can be achieved by
  5972. \emph{live range splitting}, where a variable is replaced by several
  5973. variables that each handle part of its live
  5974. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5975. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5976. %% replacement algorithm, bottom-up local
  5977. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5978. %% Cooper: top-down (priority bassed), bottom-up
  5979. %% top-down
  5980. %% order variables by priority (estimated cost)
  5981. %% caveat: split variables into two groups:
  5982. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5983. %% color the constrained ones first
  5984. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5985. %% cite J. Cocke for an algorithm that colors variables
  5986. %% in a high-degree first ordering
  5987. %Register Allocation via Usage Counts, Freiburghouse CACM
  5988. \citet{Palsberg:2007si} observe that many of the interference graphs
  5989. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5990. that is, every cycle with four or more edges has an edge which is not
  5991. part of the cycle but which connects two vertices on the cycle. Such
  5992. graphs can be optimally colored by the greedy algorithm with a vertex
  5993. ordering determined by maximum cardinality search.
  5994. In situations where compile time is of utmost importance, such as in
  5995. just-in-time compilers, graph coloring algorithms can be too expensive
  5996. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5997. appropriate.
  5998. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5999. \chapter{Booleans and Conditionals}
  6000. \label{ch:Lif}
  6001. \index{subject}{Boolean}
  6002. \index{subject}{control flow}
  6003. \index{subject}{conditional expression}
  6004. The \LangVar{} language only has a single kind of value, the
  6005. integers. In this chapter we add a second kind of value, the Booleans,
  6006. to create the \LangIf{} language. The Boolean values \emph{true} and
  6007. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6008. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6009. several operations that involve Booleans (\key{and}, \key{not},
  6010. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6011. expression \python{and statement}. With the addition of \key{if},
  6012. programs can have non-trivial control flow which
  6013. %
  6014. \racket{impacts \code{explicate\_control} and liveness analysis}
  6015. %
  6016. \python{impacts liveness analysis and motivates a new pass named
  6017. \code{explicate\_control}}.
  6018. %
  6019. Also, because we now have two kinds of values, we need to handle
  6020. programs that apply an operation to the wrong kind of value, such as
  6021. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6022. There are two language design options for such situations. One option
  6023. is to signal an error and the other is to provide a wider
  6024. interpretation of the operation. \racket{The Racket
  6025. language}\python{Python} uses a mixture of these two options,
  6026. depending on the operation and the kind of value. For example, the
  6027. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6028. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6029. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6030. %
  6031. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6032. in Racket because \code{car} expects a pair.}
  6033. %
  6034. \python{On the other hand, \code{1[0]} results in a run-time error
  6035. in Python because an ``\code{int} object is not subscriptable''.}
  6036. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6037. design choices as \racket{Racket}\python{Python}, except much of the
  6038. error detection happens at compile time instead of run
  6039. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6040. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6041. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6042. Racket}\python{MyPy} reports a compile-time error
  6043. %
  6044. \racket{because Racket expects the type of the argument to be of the form
  6045. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6046. %
  6047. \python{stating that a ``value of type \code{int} is not indexable''.}
  6048. The \LangIf{} language performs type checking during compilation like
  6049. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6050. the alternative choice, that is, a dynamically typed language like
  6051. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6052. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6053. restrictive, for example, rejecting \racket{\code{(not
  6054. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6055. fairly simple because the focus of this book is on compilation, not
  6056. type systems, about which there are already several excellent
  6057. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6058. This chapter is organized as follows. We begin by defining the syntax
  6059. and interpreter for the \LangIf{} language
  6060. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6061. checking and define a type checker for \LangIf{}
  6062. (Section~\ref{sec:type-check-Lif}).
  6063. %
  6064. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6065. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6066. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6067. %
  6068. The remaining sections of this chapter discuss how Booleans and
  6069. conditional control flow require changes to the existing compiler
  6070. passes and the addition of new ones. We introduce the \code{shrink}
  6071. pass to translates some operators into others, thereby reducing the
  6072. number of operators that need to be handled in later passes.
  6073. %
  6074. The main event of this chapter is the \code{explicate\_control} pass
  6075. that is responsible for translating \code{if}'s into conditional
  6076. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6077. %
  6078. Regarding register allocation, there is the interesting question of
  6079. how to handle conditional \code{goto}'s during liveness analysis.
  6080. \section{The \LangIf{} Language}
  6081. \label{sec:lang-if}
  6082. The concrete and abstract syntax of the \LangIf{} language are defined in
  6083. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6084. respectively. The \LangIf{} language includes all of
  6085. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6086. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6087. \code{if} statement}. We expand the set of operators to include
  6088. \begin{enumerate}
  6089. \item the logical operators \key{and}, \key{or}, and \key{not},
  6090. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6091. for comparing integers or Booleans for equality, and
  6092. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6093. comparing integers.
  6094. \end{enumerate}
  6095. \racket{We reorganize the abstract syntax for the primitive
  6096. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6097. rule for all of them. This means that the grammar no longer checks
  6098. whether the arity of an operators matches the number of
  6099. arguments. That responsibility is moved to the type checker for
  6100. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6101. \newcommand{\LifGrammarRacket}{
  6102. \begin{array}{lcl}
  6103. \Type &::=& \key{Boolean} \\
  6104. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6105. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6106. \Exp &::=& \itm{bool}
  6107. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6108. \MID (\key{not}\;\Exp) \\
  6109. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6110. \end{array}
  6111. }
  6112. \newcommand{\LifASTRacket}{
  6113. \begin{array}{lcl}
  6114. \Type &::=& \key{Boolean} \\
  6115. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6116. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6117. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6118. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6119. \end{array}
  6120. }
  6121. \newcommand{\LintOpAST}{
  6122. \begin{array}{rcl}
  6123. \Type &::=& \key{Integer} \\
  6124. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6125. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6126. \end{array}
  6127. }
  6128. \newcommand{\LifGrammarPython}{
  6129. \begin{array}{rcl}
  6130. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6131. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6132. \MID \key{not}~\Exp \\
  6133. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6134. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6135. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6136. \end{array}
  6137. }
  6138. \newcommand{\LifASTPython}{
  6139. \begin{array}{lcl}
  6140. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6141. \itm{unaryop} &::=& \code{Not()} \\
  6142. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6143. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6144. \Exp &::=& \BOOL{\itm{bool}}
  6145. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6146. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6147. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6148. \end{array}
  6149. }
  6150. \begin{figure}[tp]
  6151. \centering
  6152. \fbox{
  6153. \begin{minipage}{0.96\textwidth}
  6154. {\if\edition\racketEd
  6155. \[
  6156. \begin{array}{l}
  6157. \gray{\LintGrammarRacket{}} \\ \hline
  6158. \gray{\LvarGrammarRacket{}} \\ \hline
  6159. \LifGrammarRacket{} \\
  6160. \begin{array}{lcl}
  6161. \LangIfM{} &::=& \Exp
  6162. \end{array}
  6163. \end{array}
  6164. \]
  6165. \fi}
  6166. {\if\edition\pythonEd
  6167. \[
  6168. \begin{array}{l}
  6169. \gray{\LintGrammarPython} \\ \hline
  6170. \gray{\LvarGrammarPython} \\ \hline
  6171. \LifGrammarPython \\
  6172. \begin{array}{rcl}
  6173. \LangIfM{} &::=& \Stmt^{*}
  6174. \end{array}
  6175. \end{array}
  6176. \]
  6177. \fi}
  6178. \end{minipage}
  6179. }
  6180. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6181. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6182. \label{fig:Lif-concrete-syntax}
  6183. \end{figure}
  6184. \begin{figure}[tp]
  6185. \centering
  6186. \fbox{
  6187. \begin{minipage}{0.96\textwidth}
  6188. {\if\edition\racketEd
  6189. \[
  6190. \begin{array}{l}
  6191. \gray{\LintOpAST} \\ \hline
  6192. \gray{\LvarASTRacket{}} \\ \hline
  6193. \LifASTRacket{} \\
  6194. \begin{array}{lcl}
  6195. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6196. \end{array}
  6197. \end{array}
  6198. \]
  6199. \fi}
  6200. {\if\edition\pythonEd
  6201. \[
  6202. \begin{array}{l}
  6203. \gray{\LintASTPython} \\ \hline
  6204. \gray{\LvarASTPython} \\ \hline
  6205. \LifASTPython \\
  6206. \begin{array}{lcl}
  6207. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6208. \end{array}
  6209. \end{array}
  6210. \]
  6211. \fi}
  6212. \end{minipage}
  6213. }
  6214. \caption{The abstract syntax of \LangIf{}.}
  6215. \label{fig:Lif-syntax}
  6216. \end{figure}
  6217. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6218. which inherits from the interpreter for \LangVar{}
  6219. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6220. evaluate to the corresponding Boolean values. The conditional
  6221. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6222. and then either evaluates $e_2$ or $e_3$ depending on whether
  6223. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6224. \code{and}, \code{or}, and \code{not} behave according to
  6225. propositional logic. In addition, the \code{and} and \code{or}
  6226. operations perform \emph{short-circuit evaluation}.
  6227. %
  6228. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6229. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6230. %
  6231. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6232. evaluated if $e_1$ evaluates to \TRUE{}.
  6233. \racket{With the increase in the number of primitive operations, the
  6234. interpreter would become repetitive without some care. We refactor
  6235. the case for \code{Prim}, moving the code that differs with each
  6236. operation into the \code{interp\_op} method shown in in
  6237. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6238. \code{or} operations separately because of their short-circuiting
  6239. behavior.}
  6240. \begin{figure}[tbp]
  6241. {\if\edition\racketEd
  6242. \begin{lstlisting}
  6243. (define interp-Lif-class
  6244. (class interp-Lvar-class
  6245. (super-new)
  6246. (define/public (interp_op op) ...)
  6247. (define/override ((interp_exp env) e)
  6248. (define recur (interp_exp env))
  6249. (match e
  6250. [(Bool b) b]
  6251. [(If cnd thn els)
  6252. (match (recur cnd)
  6253. [#t (recur thn)]
  6254. [#f (recur els)])]
  6255. [(Prim 'and (list e1 e2))
  6256. (match (recur e1)
  6257. [#t (match (recur e2) [#t #t] [#f #f])]
  6258. [#f #f])]
  6259. [(Prim 'or (list e1 e2))
  6260. (define v1 (recur e1))
  6261. (match v1
  6262. [#t #t]
  6263. [#f (match (recur e2) [#t #t] [#f #f])])]
  6264. [(Prim op args)
  6265. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6266. [else ((super interp_exp env) e)]))
  6267. ))
  6268. (define (interp_Lif p)
  6269. (send (new interp-Lif-class) interp_program p))
  6270. \end{lstlisting}
  6271. \fi}
  6272. {\if\edition\pythonEd
  6273. \begin{lstlisting}
  6274. class InterpLif(InterpLvar):
  6275. def interp_exp(self, e, env):
  6276. match e:
  6277. case IfExp(test, body, orelse):
  6278. if self.interp_exp(test, env):
  6279. return self.interp_exp(body, env)
  6280. else:
  6281. return self.interp_exp(orelse, env)
  6282. case UnaryOp(Not(), v):
  6283. return not self.interp_exp(v, env)
  6284. case BoolOp(And(), values):
  6285. if self.interp_exp(values[0], env):
  6286. return self.interp_exp(values[1], env)
  6287. else:
  6288. return False
  6289. case BoolOp(Or(), values):
  6290. if self.interp_exp(values[0], env):
  6291. return True
  6292. else:
  6293. return self.interp_exp(values[1], env)
  6294. case Compare(left, [cmp], [right]):
  6295. l = self.interp_exp(left, env)
  6296. r = self.interp_exp(right, env)
  6297. return self.interp_cmp(cmp)(l, r)
  6298. case _:
  6299. return super().interp_exp(e, env)
  6300. def interp_stmts(self, ss, env):
  6301. if len(ss) == 0:
  6302. return
  6303. match ss[0]:
  6304. case If(test, body, orelse):
  6305. if self.interp_exp(test, env):
  6306. return self.interp_stmts(body + ss[1:], env)
  6307. else:
  6308. return self.interp_stmts(orelse + ss[1:], env)
  6309. case _:
  6310. return super().interp_stmts(ss, env)
  6311. ...
  6312. \end{lstlisting}
  6313. \fi}
  6314. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6315. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6316. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6317. \label{fig:interp-Lif}
  6318. \end{figure}
  6319. {\if\edition\racketEd
  6320. \begin{figure}[tbp]
  6321. \begin{lstlisting}
  6322. (define/public (interp_op op)
  6323. (match op
  6324. ['+ fx+]
  6325. ['- fx-]
  6326. ['read read-fixnum]
  6327. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6328. ['eq? (lambda (v1 v2)
  6329. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6330. (and (boolean? v1) (boolean? v2))
  6331. (and (vector? v1) (vector? v2)))
  6332. (eq? v1 v2)]))]
  6333. ['< (lambda (v1 v2)
  6334. (cond [(and (fixnum? v1) (fixnum? v2))
  6335. (< v1 v2)]))]
  6336. ['<= (lambda (v1 v2)
  6337. (cond [(and (fixnum? v1) (fixnum? v2))
  6338. (<= v1 v2)]))]
  6339. ['> (lambda (v1 v2)
  6340. (cond [(and (fixnum? v1) (fixnum? v2))
  6341. (> v1 v2)]))]
  6342. ['>= (lambda (v1 v2)
  6343. (cond [(and (fixnum? v1) (fixnum? v2))
  6344. (>= v1 v2)]))]
  6345. [else (error 'interp_op "unknown operator")]))
  6346. \end{lstlisting}
  6347. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6348. \label{fig:interp-op-Lif}
  6349. \end{figure}
  6350. \fi}
  6351. {\if\edition\pythonEd
  6352. \begin{figure}
  6353. \begin{lstlisting}
  6354. class InterpLif(InterpLvar):
  6355. ...
  6356. def interp_cmp(self, cmp):
  6357. match cmp:
  6358. case Lt():
  6359. return lambda x, y: x < y
  6360. case LtE():
  6361. return lambda x, y: x <= y
  6362. case Gt():
  6363. return lambda x, y: x > y
  6364. case GtE():
  6365. return lambda x, y: x >= y
  6366. case Eq():
  6367. return lambda x, y: x == y
  6368. case NotEq():
  6369. return lambda x, y: x != y
  6370. \end{lstlisting}
  6371. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6372. \label{fig:interp-cmp-Lif}
  6373. \end{figure}
  6374. \fi}
  6375. \section{Type Checking \LangIf{} Programs}
  6376. \label{sec:type-check-Lif}
  6377. \index{subject}{type checking}
  6378. \index{subject}{semantic analysis}
  6379. It is helpful to think about type checking in two complementary
  6380. ways. A type checker predicts the type of value that will be produced
  6381. by each expression in the program. For \LangIf{}, we have just two types,
  6382. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6383. {\if\edition\racketEd
  6384. \begin{lstlisting}
  6385. (+ 10 (- (+ 12 20)))
  6386. \end{lstlisting}
  6387. \fi}
  6388. {\if\edition\pythonEd
  6389. \begin{lstlisting}
  6390. 10 + -(12 + 20)
  6391. \end{lstlisting}
  6392. \fi}
  6393. \noindent produces a value of type \INTTY{} while
  6394. {\if\edition\racketEd
  6395. \begin{lstlisting}
  6396. (and (not #f) #t)
  6397. \end{lstlisting}
  6398. \fi}
  6399. {\if\edition\pythonEd
  6400. \begin{lstlisting}
  6401. (not False) and True
  6402. \end{lstlisting}
  6403. \fi}
  6404. \noindent produces a value of type \BOOLTY{}.
  6405. A second way to think about type checking is that it enforces a set of
  6406. rules about which operators can be applied to which kinds of
  6407. values. For example, our type checker for \LangIf{} signals an error
  6408. for the below expression {\if\edition\racketEd
  6409. \begin{lstlisting}
  6410. (not (+ 10 (- (+ 12 20))))
  6411. \end{lstlisting}
  6412. \fi}
  6413. {\if\edition\pythonEd
  6414. \begin{lstlisting}
  6415. not (10 + -(12 + 20))
  6416. \end{lstlisting}
  6417. \fi}
  6418. \noindent The subexpression
  6419. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6420. \python{\code{(10 + -(12 + 20))}}
  6421. has type \INTTY{} but the type checker enforces the rule that the
  6422. argument of \code{not} must be an expression of type \BOOLTY{}.
  6423. We implement type checking using classes and methods because they
  6424. provide the open recursion needed to reuse code as we extend the type
  6425. checker in later chapters, analogous to the use of classes and methods
  6426. for the interpreters (Section~\ref{sec:extensible-interp}).
  6427. We separate the type checker for the \LangVar{} subset into its own
  6428. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6429. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6430. from the type checker for \LangVar{}. These type checkers are in the
  6431. files
  6432. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6433. and
  6434. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6435. of the support code.
  6436. %
  6437. Each type checker is a structurally recursive function over the AST.
  6438. Given an input expression \code{e}, the type checker either signals an
  6439. error or returns \racket{an expression and} its type.
  6440. %
  6441. \racket{It returns an expression because there are situations in which
  6442. we want to change or update the expression.}
  6443. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6444. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6445. \INTTY{}. To handle variables, the type checker uses the environment
  6446. \code{env} to map variables to types.
  6447. %
  6448. \racket{Consider the case for \key{let}. We type check the
  6449. initializing expression to obtain its type \key{T} and then
  6450. associate type \code{T} with the variable \code{x} in the
  6451. environment used to type check the body of the \key{let}. Thus,
  6452. when the type checker encounters a use of variable \code{x}, it can
  6453. find its type in the environment.}
  6454. %
  6455. \python{Consider the case for assignment. We type check the
  6456. initializing expression to obtain its type \key{t}. If the variable
  6457. \code{lhs.id} is already in the environment because there was a
  6458. prior assignment, we check that this initializer has the same type
  6459. as the prior one. If this is the first assignment to the variable,
  6460. we associate type \code{t} with the variable \code{lhs.id} in the
  6461. environment. Thus, when the type checker encounters a use of
  6462. variable \code{x}, it can find its type in the environment.}
  6463. %
  6464. \racket{Regarding primitive operators, we recursively analyze the
  6465. arguments and then invoke \code{type\_check\_op} to check whether
  6466. the argument types are allowed.}
  6467. %
  6468. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6469. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6470. \racket{Several auxiliary methods are used in the type checker. The
  6471. method \code{operator-types} defines a dictionary that maps the
  6472. operator names to their parameter and return types. The
  6473. \code{type-equal?} method determines whether two types are equal,
  6474. which for now simply dispatches to \code{equal?} (deep
  6475. equality). The \code{check-type-equal?} method triggers an error if
  6476. the two types are not equal. The \code{type-check-op} method looks
  6477. up the operator in the \code{operator-types} dictionary and then
  6478. checks whether the argument types are equal to the parameter types.
  6479. The result is the return type of the operator.}
  6480. %
  6481. \python{The auxiliary method \code{check\_type\_equal} triggers
  6482. an error if the two types are not equal.}
  6483. \begin{figure}[tbp]
  6484. {\if\edition\racketEd
  6485. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6486. (define type-check-Lvar-class
  6487. (class object%
  6488. (super-new)
  6489. (define/public (operator-types)
  6490. '((+ . ((Integer Integer) . Integer))
  6491. (- . ((Integer Integer) . Integer))
  6492. (read . (() . Integer))))
  6493. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6494. (define/public (check-type-equal? t1 t2 e)
  6495. (unless (type-equal? t1 t2)
  6496. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6497. (define/public (type-check-op op arg-types e)
  6498. (match (dict-ref (operator-types) op)
  6499. [`(,param-types . ,return-type)
  6500. (for ([at arg-types] [pt param-types])
  6501. (check-type-equal? at pt e))
  6502. return-type]
  6503. [else (error 'type-check-op "unrecognized ~a" op)]))
  6504. (define/public (type-check-exp env)
  6505. (lambda (e)
  6506. (match e
  6507. [(Int n) (values (Int n) 'Integer)]
  6508. [(Var x) (values (Var x) (dict-ref env x))]
  6509. [(Let x e body)
  6510. (define-values (e^ Te) ((type-check-exp env) e))
  6511. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6512. (values (Let x e^ b) Tb)]
  6513. [(Prim op es)
  6514. (define-values (new-es ts)
  6515. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6516. (values (Prim op new-es) (type-check-op op ts e))]
  6517. [else (error 'type-check-exp "couldn't match" e)])))
  6518. (define/public (type-check-program e)
  6519. (match e
  6520. [(Program info body)
  6521. (define-values (body^ Tb) ((type-check-exp '()) body))
  6522. (check-type-equal? Tb 'Integer body)
  6523. (Program info body^)]
  6524. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6525. ))
  6526. (define (type-check-Lvar p)
  6527. (send (new type-check-Lvar-class) type-check-program p))
  6528. \end{lstlisting}
  6529. \fi}
  6530. {\if\edition\pythonEd
  6531. \begin{lstlisting}[escapechar=`]
  6532. class TypeCheckLvar:
  6533. def check_type_equal(self, t1, t2, e):
  6534. if t1 != t2:
  6535. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6536. raise Exception(msg)
  6537. def type_check_exp(self, e, env):
  6538. match e:
  6539. case BinOp(left, (Add() | Sub()), right):
  6540. l = self.type_check_exp(left, env)
  6541. check_type_equal(l, int, left)
  6542. r = self.type_check_exp(right, env)
  6543. check_type_equal(r, int, right)
  6544. return int
  6545. case UnaryOp(USub(), v):
  6546. t = self.type_check_exp(v, env)
  6547. check_type_equal(t, int, v)
  6548. return int
  6549. case Name(id):
  6550. return env[id]
  6551. case Constant(value) if isinstance(value, int):
  6552. return int
  6553. case Call(Name('input_int'), []):
  6554. return int
  6555. def type_check_stmts(self, ss, env):
  6556. if len(ss) == 0:
  6557. return
  6558. match ss[0]:
  6559. case Assign([lhs], value):
  6560. t = self.type_check_exp(value, env)
  6561. if lhs.id in env:
  6562. check_type_equal(env[lhs.id], t, value)
  6563. else:
  6564. env[lhs.id] = t
  6565. return self.type_check_stmts(ss[1:], env)
  6566. case Expr(Call(Name('print'), [arg])):
  6567. t = self.type_check_exp(arg, env)
  6568. check_type_equal(t, int, arg)
  6569. return self.type_check_stmts(ss[1:], env)
  6570. case Expr(value):
  6571. self.type_check_exp(value, env)
  6572. return self.type_check_stmts(ss[1:], env)
  6573. def type_check_P(self, p):
  6574. match p:
  6575. case Module(body):
  6576. self.type_check_stmts(body, {})
  6577. \end{lstlisting}
  6578. \fi}
  6579. \caption{Type checker for the \LangVar{} language.}
  6580. \label{fig:type-check-Lvar}
  6581. \end{figure}
  6582. \begin{figure}[tbp]
  6583. {\if\edition\racketEd
  6584. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6585. (define type-check-Lif-class
  6586. (class type-check-Lvar-class
  6587. (super-new)
  6588. (inherit check-type-equal?)
  6589. (define/override (operator-types)
  6590. (append '((and . ((Boolean Boolean) . Boolean))
  6591. (or . ((Boolean Boolean) . Boolean))
  6592. (< . ((Integer Integer) . Boolean))
  6593. (<= . ((Integer Integer) . Boolean))
  6594. (> . ((Integer Integer) . Boolean))
  6595. (>= . ((Integer Integer) . Boolean))
  6596. (not . ((Boolean) . Boolean)))
  6597. (super operator-types)))
  6598. (define/override (type-check-exp env)
  6599. (lambda (e)
  6600. (match e
  6601. [(Bool b) (values (Bool b) 'Boolean)]
  6602. [(Prim 'eq? (list e1 e2))
  6603. (define-values (e1^ T1) ((type-check-exp env) e1))
  6604. (define-values (e2^ T2) ((type-check-exp env) e2))
  6605. (check-type-equal? T1 T2 e)
  6606. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6607. [(If cnd thn els)
  6608. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6609. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6610. (define-values (els^ Te) ((type-check-exp env) els))
  6611. (check-type-equal? Tc 'Boolean e)
  6612. (check-type-equal? Tt Te e)
  6613. (values (If cnd^ thn^ els^) Te)]
  6614. [else ((super type-check-exp env) e)])))
  6615. ))
  6616. (define (type-check-Lif p)
  6617. (send (new type-check-Lif-class) type-check-program p))
  6618. \end{lstlisting}
  6619. \fi}
  6620. {\if\edition\pythonEd
  6621. \begin{lstlisting}
  6622. class TypeCheckLif(TypeCheckLvar):
  6623. def type_check_exp(self, e, env):
  6624. match e:
  6625. case Constant(value) if isinstance(value, bool):
  6626. return bool
  6627. case BinOp(left, Sub(), right):
  6628. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6629. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6630. return int
  6631. case UnaryOp(Not(), v):
  6632. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6633. return bool
  6634. case BoolOp(op, values):
  6635. left = values[0] ; right = values[1]
  6636. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6637. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6638. return bool
  6639. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6640. or isinstance(cmp, NotEq):
  6641. l = self.type_check_exp(left, env)
  6642. r = self.type_check_exp(right, env)
  6643. check_type_equal(l, r, e)
  6644. return bool
  6645. case Compare(left, [cmp], [right]):
  6646. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6647. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6648. return bool
  6649. case IfExp(test, body, orelse):
  6650. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6651. b = self.type_check_exp(body, env)
  6652. o = self.type_check_exp(orelse, env)
  6653. check_type_equal(b, o, e)
  6654. return b
  6655. case _:
  6656. return super().type_check_exp(e, env)
  6657. def type_check_stmts(self, ss, env):
  6658. if len(ss) == 0:
  6659. return
  6660. match ss[0]:
  6661. case If(test, body, orelse):
  6662. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6663. b = self.type_check_stmts(body, env)
  6664. o = self.type_check_stmts(orelse, env)
  6665. check_type_equal(b, o, ss[0])
  6666. return self.type_check_stmts(ss[1:], env)
  6667. case _:
  6668. return super().type_check_stmts(ss, env)
  6669. \end{lstlisting}
  6670. \fi}
  6671. \caption{Type checker for the \LangIf{} language.}
  6672. \label{fig:type-check-Lif}
  6673. \end{figure}
  6674. The type checker for \LangIf{} is defined in
  6675. Figure~\ref{fig:type-check-Lif}.
  6676. %
  6677. The type of a Boolean constant is \BOOLTY{}.
  6678. %
  6679. \racket{The \code{operator-types} function adds dictionary entries for
  6680. the new operators.}
  6681. %
  6682. \python{Logical not requires its argument to be a \BOOLTY{} and
  6683. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6684. %
  6685. The equality operator requires the two arguments to have the same type
  6686. and therefore we handle it separately from the other operators.
  6687. %
  6688. \python{The other comparisons (less-than, etc.) require their
  6689. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6690. %
  6691. The condition of an \code{if} must
  6692. be of \BOOLTY{} type and the two branches must have the same type.
  6693. \begin{exercise}\normalfont\normalsize
  6694. Create 10 new test programs in \LangIf{}. Half of the programs should
  6695. have a type error. For those programs, create an empty file with the
  6696. same base name but with file extension \code{.tyerr}. For example, if
  6697. the test
  6698. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6699. is expected to error, then create
  6700. an empty file named \code{cond\_test\_14.tyerr}.
  6701. %
  6702. \racket{This indicates to \code{interp-tests} and
  6703. \code{compiler-tests} that a type error is expected. }
  6704. %
  6705. The other half of the test programs should not have type errors.
  6706. %
  6707. \racket{In the \code{run-tests.rkt} script, change the second argument
  6708. of \code{interp-tests} and \code{compiler-tests} to
  6709. \code{type-check-Lif}, which causes the type checker to run prior to
  6710. the compiler passes. Temporarily change the \code{passes} to an
  6711. empty list and run the script, thereby checking that the new test
  6712. programs either type check or not as intended.}
  6713. %
  6714. Run the test script to check that these test programs type check as
  6715. expected.
  6716. \end{exercise}
  6717. \clearpage
  6718. \section{The \LangCIf{} Intermediate Language}
  6719. \label{sec:Cif}
  6720. {\if\edition\racketEd
  6721. %
  6722. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6723. comparison operators to the \Exp{} non-terminal and the literals
  6724. \TRUE{} and \FALSE{} to the \Arg{} non-terminal. Regarding control
  6725. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6726. \Tail{} non-terminal. The condition of an \code{if} statement is a
  6727. comparison operation and the branches are \code{goto} statements,
  6728. making it straightforward to compile \code{if} statements to x86. The
  6729. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6730. expressions. A \code{goto} statement transfers control to the $\Tail$
  6731. expression corresponding to its label.
  6732. %
  6733. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6734. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6735. defines its abstract syntax.
  6736. %
  6737. \fi}
  6738. %
  6739. {\if\edition\pythonEd
  6740. %
  6741. The output of \key{explicate\_control} is a language similar to the
  6742. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6743. \code{goto} statements, so we name it \LangCIf{}.
  6744. %
  6745. The \LangCIf{} language supports the same operators as \LangIf{} but
  6746. the arguments of operators are restricted to atomic expressions. The
  6747. \LangCIf{} language does not include \code{if} expressions but it does
  6748. include a restricted form of \code{if} statment. The condition must be
  6749. a comparison and the two branches may only contain \code{goto}
  6750. statements. These restrictions make it easier to translate \code{if}
  6751. statements to x86. The \LangCIf{} language also adds a \code{return}
  6752. statement to finish the program with a specified value.
  6753. %
  6754. The \key{CProgram} construct contains a dictionary mapping labels to
  6755. lists of statements that end with a \code{return} statement, a
  6756. \code{goto}, or a conditional \code{goto}.
  6757. %% Statement lists of this
  6758. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6759. %% is a control transfer at the end and control only enters at the
  6760. %% beginning of the list, which is marked by the label.
  6761. %
  6762. A \code{goto} statement transfers control to the sequence of statements
  6763. associated with its label.
  6764. %
  6765. The concrete syntax for \LangCIf{} is defined in
  6766. Figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6767. in Figure~\ref{fig:c1-syntax}.
  6768. %
  6769. \fi}
  6770. %
  6771. \newcommand{\CifGrammarRacket}{
  6772. \begin{array}{lcl}
  6773. \Atm &::=& \itm{bool} \\
  6774. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6775. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6776. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6777. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6778. \end{array}
  6779. }
  6780. \newcommand{\CifASTRacket}{
  6781. \begin{array}{lcl}
  6782. \Atm &::=& \BOOL{\itm{bool}} \\
  6783. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6784. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6785. \Tail &::= & \GOTO{\itm{label}} \\
  6786. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6787. \end{array}
  6788. }
  6789. \newcommand{\CifGrammarPython}{
  6790. \begin{array}{lcl}
  6791. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6792. \Exp &::= & \Atm \MID \CREAD{}
  6793. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6794. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6795. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6796. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6797. &\MID& \CASSIGN{\Var}{\Exp}
  6798. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6799. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6800. \end{array}
  6801. }
  6802. \newcommand{\CifASTPython}{
  6803. \begin{array}{lcl}
  6804. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6805. \Exp &::= & \Atm \MID \READ{} \\
  6806. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6807. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6808. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6809. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6810. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6811. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6812. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6813. \end{array}
  6814. }
  6815. \begin{figure}[tbp]
  6816. \fbox{
  6817. \begin{minipage}{0.96\textwidth}
  6818. \small
  6819. {\if\edition\racketEd
  6820. \[
  6821. \begin{array}{l}
  6822. \gray{\CvarGrammarRacket} \\ \hline
  6823. \CifGrammarRacket \\
  6824. \begin{array}{lcl}
  6825. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6826. \end{array}
  6827. \end{array}
  6828. \]
  6829. \fi}
  6830. {\if\edition\pythonEd
  6831. \[
  6832. \begin{array}{l}
  6833. \CifGrammarPython \\
  6834. \begin{array}{lcl}
  6835. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6836. \end{array}
  6837. \end{array}
  6838. \]
  6839. \fi}
  6840. \end{minipage}
  6841. }
  6842. \caption{The concrete syntax of the \LangCIf{} intermediate language,
  6843. an extension of \LangCVar{} (Figure~\ref{fig:c0-concrete-syntax}).}
  6844. \label{fig:c1-concrete-syntax}
  6845. \end{figure}
  6846. \begin{figure}[tp]
  6847. \fbox{
  6848. \begin{minipage}{0.96\textwidth}
  6849. \small
  6850. {\if\edition\racketEd
  6851. \[
  6852. \begin{array}{l}
  6853. \gray{\CvarASTRacket} \\ \hline
  6854. \CifASTRacket \\
  6855. \begin{array}{lcl}
  6856. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6857. \end{array}
  6858. \end{array}
  6859. \]
  6860. \fi}
  6861. {\if\edition\pythonEd
  6862. \[
  6863. \begin{array}{l}
  6864. \CifASTPython \\
  6865. \begin{array}{lcl}
  6866. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6867. \end{array}
  6868. \end{array}
  6869. \]
  6870. \fi}
  6871. \end{minipage}
  6872. }
  6873. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6874. (Figure~\ref{fig:c0-syntax})}.}
  6875. \label{fig:c1-syntax}
  6876. \end{figure}
  6877. \section{The \LangXIf{} Language}
  6878. \label{sec:x86-if}
  6879. \index{subject}{x86} To implement the new logical operations, the
  6880. comparison operations, and the \key{if} expression\python{ and
  6881. statement}, we delve further into the x86
  6882. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6883. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6884. which includes instructions for logical operations, comparisons, and
  6885. \racket{conditional} jumps.
  6886. %
  6887. \python{The abstract syntax for an \LangXIf{} program contains a
  6888. dictionary mapping labels to sequences of instructions, each of
  6889. which we refer to as a \emph{basic block}\index{subject}{basic
  6890. block}.}
  6891. One challenge is that x86 does not provide an instruction that
  6892. directly implements logical negation (\code{not} in \LangIf{} and
  6893. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6894. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6895. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6896. bit of its arguments, and writes the results into its second argument.
  6897. Recall the truth table for exclusive-or:
  6898. \begin{center}
  6899. \begin{tabular}{l|cc}
  6900. & 0 & 1 \\ \hline
  6901. 0 & 0 & 1 \\
  6902. 1 & 1 & 0
  6903. \end{tabular}
  6904. \end{center}
  6905. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6906. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6907. for the bit $1$, the result is the opposite of the second bit. Thus,
  6908. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6909. the first argument as follows, where $\Arg$ is the translation of
  6910. $\Atm$ to x86.
  6911. \[
  6912. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6913. \qquad\Rightarrow\qquad
  6914. \begin{array}{l}
  6915. \key{movq}~ \Arg\key{,} \Var\\
  6916. \key{xorq}~ \key{\$1,} \Var
  6917. \end{array}
  6918. \]
  6919. \newcommand{\GrammarXIf}{
  6920. \begin{array}{lcl}
  6921. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6922. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6923. \Arg &::=& \key{\%}\itm{bytereg}\\
  6924. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6925. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  6926. \MID \key{cmpq}~\Arg\key{,}~\Arg
  6927. \MID \key{set}cc~\Arg
  6928. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  6929. &\MID& \key{j}cc~\itm{label} \\
  6930. \end{array}
  6931. }
  6932. \begin{figure}[tp]
  6933. \fbox{
  6934. \begin{minipage}{0.96\textwidth}
  6935. \[
  6936. \begin{array}{l}
  6937. \gray{\GrammarXInt} \\ \hline
  6938. \GrammarXIf \\
  6939. \begin{array}{lcl}
  6940. \LangXIfM{} &::= & \key{.globl main} \\
  6941. & & \key{main:} \; \Instr\ldots
  6942. \end{array}
  6943. \end{array}
  6944. \]
  6945. \end{minipage}
  6946. }
  6947. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6948. \label{fig:x86-1-concrete}
  6949. \end{figure}
  6950. \newcommand{\ASTXIfRacket}{
  6951. \begin{array}{lcl}
  6952. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6953. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6954. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  6955. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6956. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6957. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6958. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6959. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6960. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  6961. \end{array}
  6962. }
  6963. \begin{figure}[tp]
  6964. \fbox{
  6965. \begin{minipage}{0.96\textwidth}
  6966. \small
  6967. {\if\edition\racketEd
  6968. \[
  6969. \begin{array}{l}
  6970. \gray{\ASTXIntRacket} \\ \hline
  6971. \ASTXIfRacket \\
  6972. \begin{array}{lcl}
  6973. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  6974. \end{array}
  6975. \end{array}
  6976. \]
  6977. \fi}
  6978. %
  6979. {\if\edition\pythonEd
  6980. \[
  6981. \begin{array}{lcl}
  6982. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6983. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6984. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6985. \MID \BYTEREG{\itm{bytereg}} \\
  6986. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6987. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6988. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6989. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6990. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6991. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6992. \MID \PUSHQ{\Arg}} \\
  6993. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6994. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6995. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6996. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6997. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6998. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6999. \Block &::= & \Instr^{+} \\
  7000. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7001. \end{array}
  7002. \]
  7003. \fi}
  7004. \end{minipage}
  7005. }
  7006. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  7007. \label{fig:x86-1}
  7008. \end{figure}
  7009. Next we consider the x86 instructions that are relevant for compiling
  7010. the comparison operations. The \key{cmpq} instruction compares its two
  7011. arguments to determine whether one argument is less than, equal, or
  7012. greater than the other argument. The \key{cmpq} instruction is unusual
  7013. regarding the order of its arguments and where the result is
  7014. placed. The argument order is backwards: if you want to test whether
  7015. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7016. \key{cmpq} is placed in the special EFLAGS register. This register
  7017. cannot be accessed directly but it can be queried by a number of
  7018. instructions, including the \key{set} instruction. The instruction
  7019. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7020. depending on whether the contents of the EFLAGS register matches the
  7021. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7022. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7023. The \key{set} instruction has a quirk in that its destination argument
  7024. must be single byte register, such as \code{al} (L for lower bits) or
  7025. \code{ah} (H for higher bits), which are part of the \code{rax}
  7026. register. Thankfully, the \key{movzbq} instruction can be used to
  7027. move from a single byte register to a normal 64-bit register. The
  7028. abstract syntax for the \code{set} instruction differs from the
  7029. concrete syntax in that it separates the instruction name from the
  7030. condition code.
  7031. \python{The x86 instructions for jumping are relevant to the
  7032. compilation of \key{if} expressions.}
  7033. %
  7034. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7035. counter to the address of the instruction after the specified
  7036. label.}
  7037. %
  7038. \racket{The x86 instruction for conditional jump is relevant to the
  7039. compilation of \key{if} expressions.}
  7040. %
  7041. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7042. counter to point to the instruction after \itm{label} depending on
  7043. whether the result in the EFLAGS register matches the condition code
  7044. \itm{cc}, otherwise the jump instruction falls through to the next
  7045. instruction. Like the abstract syntax for \code{set}, the abstract
  7046. syntax for conditional jump separates the instruction name from the
  7047. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7048. corresponds to \code{jle foo}. Because the conditional jump instruction
  7049. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7050. a \key{cmpq} instruction to set the EFLAGS register.
  7051. \section{Shrink the \LangIf{} Language}
  7052. \label{sec:shrink-Lif}
  7053. The \LangIf{} language includes several features that are easily
  7054. expressible with other features. For example, \code{and} and \code{or}
  7055. are expressible using \code{if} as follows.
  7056. \begin{align*}
  7057. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7058. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7059. \end{align*}
  7060. By performing these translations in the front-end of the compiler,
  7061. subsequent passes of the compiler do not need to deal with these features,
  7062. making the passes shorter.
  7063. On the other hand, sometimes translations reduce the efficiency of the
  7064. generated code by increasing the number of instructions. For example,
  7065. expressing subtraction in terms of negation
  7066. \[
  7067. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7068. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7069. \]
  7070. produces code with two x86 instructions (\code{negq} and \code{addq})
  7071. instead of just one (\code{subq}).
  7072. \begin{exercise}\normalfont\normalsize
  7073. %
  7074. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7075. the language by translating them to \code{if} expressions in \LangIf{}.
  7076. %
  7077. Create four test programs that involve these operators.
  7078. %
  7079. {\if\edition\racketEd
  7080. In the \code{run-tests.rkt} script, add the following entry for
  7081. \code{shrink} to the list of passes (it should be the only pass at
  7082. this point).
  7083. \begin{lstlisting}
  7084. (list "shrink" shrink interp_Lif type-check-Lif)
  7085. \end{lstlisting}
  7086. This instructs \code{interp-tests} to run the intepreter
  7087. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7088. output of \code{shrink}.
  7089. \fi}
  7090. %
  7091. Run the script to test your compiler on all the test programs.
  7092. \end{exercise}
  7093. {\if\edition\racketEd
  7094. \section{Uniquify Variables}
  7095. \label{sec:uniquify-Lif}
  7096. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7097. \code{if} expressions.
  7098. \begin{exercise}\normalfont\normalsize
  7099. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7100. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7101. \begin{lstlisting}
  7102. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7103. \end{lstlisting}
  7104. Run the script to test your compiler.
  7105. \end{exercise}
  7106. \fi}
  7107. \section{Remove Complex Operands}
  7108. \label{sec:remove-complex-opera-Lif}
  7109. The output language of \code{remove\_complex\_operands} is
  7110. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the monadic
  7111. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7112. but the \code{if} expression is not. All three sub-expressions of an
  7113. \code{if} are allowed to be complex expressions but the operands of
  7114. \code{not} and the comparisons must be atomic.
  7115. %
  7116. \python{We add a new language form, the \code{Begin} expression, to aid
  7117. in the translation of \code{if} expressions. When we recursively
  7118. process the two branches of the \code{if}, we generate temporary
  7119. variables and their initializing expressions. However, these
  7120. expressions may contain side effects and should only be executed
  7121. when the condition of the \code{if} is true (for the ``then''
  7122. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7123. a way to initialize the temporary variables within the two branches
  7124. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7125. form execute the statements $ss$ and then returns the result of
  7126. expression $e$.}
  7127. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7128. the new features in \LangIf{}. When recursively processing
  7129. subexpressions, recall that you should invoke \code{rco\_atom} when
  7130. the output needs to be an \Atm{} (as specified in the grammar for
  7131. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7132. \Exp{}. Regarding \code{if}, it is particularly important to
  7133. \textbf{not} replace its condition with a temporary variable because
  7134. that would interfere with the generation of high-quality output in the
  7135. upcoming \code{explicate\_control} pass.
  7136. \newcommand{\LifMonadASTRacket}{
  7137. \begin{array}{rcl}
  7138. \Atm &::=& \BOOL{\itm{bool}}\\
  7139. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7140. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7141. \MID \IF{\Exp}{\Exp}{\Exp}
  7142. \end{array}
  7143. }
  7144. \newcommand{\LifMonadASTPython}{
  7145. \begin{array}{rcl}
  7146. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7147. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7148. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7149. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7150. \Atm &::=& \BOOL{\itm{bool}}\\
  7151. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7152. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7153. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7154. \end{array}
  7155. }
  7156. \begin{figure}[tp]
  7157. \centering
  7158. \fbox{
  7159. \begin{minipage}{0.96\textwidth}
  7160. {\if\edition\racketEd
  7161. \[
  7162. \begin{array}{l}
  7163. \gray{\LvarMonadASTRacket} \\ \hline
  7164. \LifMonadASTRacket \\
  7165. \begin{array}{rcl}
  7166. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7167. \end{array}
  7168. \end{array}
  7169. \]
  7170. \fi}
  7171. {\if\edition\pythonEd
  7172. \[
  7173. \begin{array}{l}
  7174. \gray{\LvarMonadASTPython} \\ \hline
  7175. \LifMonadASTPython \\
  7176. \begin{array}{rcl}
  7177. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7178. \end{array}
  7179. \end{array}
  7180. \]
  7181. \fi}
  7182. \end{minipage}
  7183. }
  7184. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7185. (extends \LangVarANF in Figure~\ref{fig:Lvar-anf-syntax}).}
  7186. \label{fig:Lif-anf-syntax}
  7187. \end{figure}
  7188. \begin{exercise}\normalfont\normalsize
  7189. %
  7190. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7191. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7192. %
  7193. Create three new \LangIf{} programs that exercise the interesting
  7194. code in this pass.
  7195. %
  7196. {\if\edition\racketEd
  7197. In the \code{run-tests.rkt} script, add the following entry to the
  7198. list of \code{passes} and then run the script to test your compiler.
  7199. \begin{lstlisting}
  7200. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7201. \end{lstlisting}
  7202. \fi}
  7203. \end{exercise}
  7204. \section{Explicate Control}
  7205. \label{sec:explicate-control-Lif}
  7206. \racket{Recall that the purpose of \code{explicate\_control} is to
  7207. make the order of evaluation explicit in the syntax of the program.
  7208. With the addition of \key{if} this gets more interesting.}
  7209. %
  7210. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7211. %
  7212. The main challenge to overcome is that the condition of an \key{if}
  7213. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7214. condition must be a comparison.
  7215. As a motivating example, consider the following program that has an
  7216. \key{if} expression nested in the condition of another \key{if}.%
  7217. \python{\footnote{Programmers rarely write nested \code{if}
  7218. expressions, but it is not uncommon for the condition of an
  7219. \code{if} statement to be a call of a function that also contains an
  7220. \code{if} statement. When such a function is inlined, the result is
  7221. a nested \code{if} that requires the techniques discussed in this
  7222. section.}}
  7223. % cond_test_41.rkt, if_lt_eq.py
  7224. \begin{center}
  7225. \begin{minipage}{0.96\textwidth}
  7226. {\if\edition\racketEd
  7227. \begin{lstlisting}
  7228. (let ([x (read)])
  7229. (let ([y (read)])
  7230. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7231. (+ y 2)
  7232. (+ y 10))))
  7233. \end{lstlisting}
  7234. \fi}
  7235. {\if\edition\pythonEd
  7236. \begin{lstlisting}
  7237. x = input_int()
  7238. y = input_int()
  7239. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7240. \end{lstlisting}
  7241. \fi}
  7242. \end{minipage}
  7243. \end{center}
  7244. %
  7245. The naive way to compile \key{if} and the comparison operations would
  7246. be to handle each of them in isolation, regardless of their context.
  7247. Each comparison would be translated into a \key{cmpq} instruction
  7248. followed by several instructions to move the result from the EFLAGS
  7249. register into a general purpose register or stack location. Each
  7250. \key{if} would be translated into a \key{cmpq} instruction followed by
  7251. a conditional jump. The generated code for the inner \key{if} in the
  7252. above example would be as follows.
  7253. \begin{center}
  7254. \begin{minipage}{0.96\textwidth}
  7255. \begin{lstlisting}
  7256. cmpq $1, x
  7257. setl %al
  7258. movzbq %al, tmp
  7259. cmpq $1, tmp
  7260. je then_branch_1
  7261. jmp else_branch_1
  7262. \end{lstlisting}
  7263. \end{minipage}
  7264. \end{center}
  7265. Notice that the three instructions starting with \code{setl} are
  7266. redundant: the conditional jump could come immediately after the first
  7267. \code{cmpq}.
  7268. Our goal will be to compile \key{if} expressions so that the relevant
  7269. comparison instruction appears directly before the conditional jump.
  7270. For example, we want to generate the following code for the inner
  7271. \code{if}.
  7272. \begin{center}
  7273. \begin{minipage}{0.96\textwidth}
  7274. \begin{lstlisting}
  7275. cmpq $1, x
  7276. jl then_branch_1
  7277. jmp else_branch_1
  7278. \end{lstlisting}
  7279. \end{minipage}
  7280. \end{center}
  7281. One way to achieve this goal is to reorganize the code at the level of
  7282. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7283. the following code.
  7284. \begin{center}
  7285. \begin{minipage}{0.96\textwidth}
  7286. {\if\edition\racketEd
  7287. \begin{lstlisting}
  7288. (let ([x (read)])
  7289. (let ([y (read)])
  7290. (if (< x 1)
  7291. (if (eq? x 0)
  7292. (+ y 2)
  7293. (+ y 10))
  7294. (if (eq? x 2)
  7295. (+ y 2)
  7296. (+ y 10)))))
  7297. \end{lstlisting}
  7298. \fi}
  7299. {\if\edition\pythonEd
  7300. \begin{lstlisting}
  7301. x = input_int()
  7302. y = intput_int()
  7303. print(((y + 2) if x == 0 else (y + 10)) \
  7304. if (x < 1) \
  7305. else ((y + 2) if (x == 2) else (y + 10)))
  7306. \end{lstlisting}
  7307. \fi}
  7308. \end{minipage}
  7309. \end{center}
  7310. Unfortunately, this approach duplicates the two branches from the
  7311. outer \code{if} and a compiler must never duplicate code! After all,
  7312. the two branches could be very large expressions.
  7313. How can we apply the above transformation but without duplicating
  7314. code? In other words, how can two different parts of a program refer
  7315. to one piece of code.
  7316. %
  7317. The answer is that we must move away from abstract syntax \emph{trees}
  7318. and instead use \emph{graphs}.
  7319. %
  7320. At the level of x86 assembly this is straightforward because we can
  7321. label the code for each branch and insert jumps in all the places that
  7322. need to execute the branch. In this way, jump instructions are edges
  7323. in the graph and the basic blocks are the nodes.
  7324. %
  7325. Likewise, our language \LangCIf{} provides the ability to label a
  7326. sequence of statements and to jump to a label via \code{goto}.
  7327. As a preview of what \code{explicate\_control} will do,
  7328. Figure~\ref{fig:explicate-control-s1-38} shows the output of
  7329. \code{explicate\_control} on the above example. Note how the condition
  7330. of every \code{if} is a comparison operation and that we have not
  7331. duplicated any code, but instead used labels and \code{goto} to enable
  7332. sharing of code.
  7333. \begin{figure}[tbp]
  7334. {\if\edition\racketEd
  7335. \begin{tabular}{lll}
  7336. \begin{minipage}{0.4\textwidth}
  7337. % cond_test_41.rkt
  7338. \begin{lstlisting}
  7339. (let ([x (read)])
  7340. (let ([y (read)])
  7341. (if (if (< x 1)
  7342. (eq? x 0)
  7343. (eq? x 2))
  7344. (+ y 2)
  7345. (+ y 10))))
  7346. \end{lstlisting}
  7347. \end{minipage}
  7348. &
  7349. $\Rightarrow$
  7350. &
  7351. \begin{minipage}{0.55\textwidth}
  7352. \begin{lstlisting}
  7353. start:
  7354. x = (read);
  7355. y = (read);
  7356. if (< x 1)
  7357. goto block_4;
  7358. else
  7359. goto block_5;
  7360. block_4:
  7361. if (eq? x 0)
  7362. goto block_2;
  7363. else
  7364. goto block_3;
  7365. block_5:
  7366. if (eq? x 2)
  7367. goto block_2;
  7368. else
  7369. goto block_3;
  7370. block_2:
  7371. return (+ y 2);
  7372. block_3:
  7373. return (+ y 10);
  7374. \end{lstlisting}
  7375. \end{minipage}
  7376. \end{tabular}
  7377. \fi}
  7378. {\if\edition\pythonEd
  7379. \begin{tabular}{lll}
  7380. \begin{minipage}{0.4\textwidth}
  7381. % cond_test_41.rkt
  7382. \begin{lstlisting}
  7383. x = input_int()
  7384. y = input_int()
  7385. print(y + 2 \
  7386. if (x == 0 \
  7387. if x < 1 \
  7388. else x == 2) \
  7389. else y + 10)
  7390. \end{lstlisting}
  7391. \end{minipage}
  7392. &
  7393. $\Rightarrow$
  7394. &
  7395. \begin{minipage}{0.55\textwidth}
  7396. \begin{lstlisting}
  7397. start:
  7398. x = input_int()
  7399. y = input_int()
  7400. if x < 1:
  7401. goto block_8
  7402. else:
  7403. goto block_9
  7404. block_8:
  7405. if x == 0:
  7406. goto block_4
  7407. else:
  7408. goto block_5
  7409. block_9:
  7410. if x == 2:
  7411. goto block_6
  7412. else:
  7413. goto block_7
  7414. block_4:
  7415. goto block_2
  7416. block_5:
  7417. goto block_3
  7418. block_6:
  7419. goto block_2
  7420. block_7:
  7421. goto block_3
  7422. block_2:
  7423. tmp_0 = y + 2
  7424. goto block_1
  7425. block_3:
  7426. tmp_0 = y + 10
  7427. goto block_1
  7428. block_1:
  7429. print(tmp_0)
  7430. return 0
  7431. \end{lstlisting}
  7432. \end{minipage}
  7433. \end{tabular}
  7434. \fi}
  7435. \caption{Translation from \LangIf{} to \LangCIf{}
  7436. via the \code{explicate\_control}.}
  7437. \label{fig:explicate-control-s1-38}
  7438. \end{figure}
  7439. {\if\edition\racketEd
  7440. %
  7441. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7442. \code{explicate\_control} for \LangVar{} using two recursive
  7443. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7444. former function translates expressions in tail position whereas the
  7445. later function translates expressions on the right-hand-side of a
  7446. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7447. have a new kind of position to deal with: the predicate position of
  7448. the \key{if}. We need another function, \code{explicate\_pred}, that
  7449. decides how to compile an \key{if} by analyzing its condition. So
  7450. \code{explicate\_pred} takes an \LangIf{} expression and two
  7451. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7452. tail. In the following paragraphs we discuss specific cases in the
  7453. \code{explicate\_tail}, \code{explicate\_assign}, and
  7454. \code{explicate\_pred} functions.
  7455. %
  7456. \fi}
  7457. %
  7458. {\if\edition\pythonEd
  7459. %
  7460. We recommend implementing \code{explicate\_control} using the
  7461. following four auxiliary functions.
  7462. \begin{description}
  7463. \item[\code{explicate\_effect}] generates code for expressions as
  7464. statements, so their result is ignored and only their side effects
  7465. matter.
  7466. \item[\code{explicate\_assign}] generates code for expressions
  7467. on the right-hand side of an assignment.
  7468. \item[\code{explicate\_pred}] generates code for an \code{if}
  7469. expression or statement by analyzing the condition expression.
  7470. \item[\code{explicate\_stmt}] generates code for statements.
  7471. \end{description}
  7472. These four functions should build the dictionary of basic blocks. The
  7473. following auxiliary function can be used to create a new basic block
  7474. from a list of statements. It returns a \code{goto} statement that
  7475. jumps to the new basic block.
  7476. \begin{center}
  7477. \begin{minipage}{\textwidth}
  7478. \begin{lstlisting}
  7479. def create_block(stmts, basic_blocks):
  7480. label = label_name(generate_name('block'))
  7481. basic_blocks[label] = stmts
  7482. return Goto(label)
  7483. \end{lstlisting}
  7484. \end{minipage}
  7485. \end{center}
  7486. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7487. \code{explicate\_control} pass.
  7488. The \code{explicate\_effect} function has three parameters: 1) the
  7489. expression to be compiled, 2) the already-compiled code for this
  7490. expression's \emph{continuation}, that is, the list of statements that
  7491. should execute after this expression, and 3) the dictionary of
  7492. generated basic blocks. The \code{explicate\_effect} function returns
  7493. a list of \LangCIf{} statements and it may add to the dictionary of
  7494. basic blocks.
  7495. %
  7496. Let's consider a few of the cases for the expression to be compiled.
  7497. If the expression to be compiled is a constant, then it can be
  7498. discarded because it has no side effects. If it's a \CREAD{}, then it
  7499. has a side-effect and should be preserved. So the expression should be
  7500. translated into a statement using the \code{Expr} AST class. If the
  7501. expression to be compiled is an \code{if} expression, we translate the
  7502. two branches using \code{explicate\_effect} and then translate the
  7503. condition expression using \code{explicate\_pred}, which generates
  7504. code for the entire \code{if}.
  7505. The \code{explicate\_assign} function has four parameters: 1) the
  7506. right-hand-side of the assignment, 2) the left-hand-side of the
  7507. assignment (the variable), 3) the continuation, and 4) the dictionary
  7508. of basic blocks. The \code{explicate\_assign} function returns a list
  7509. of \LangCIf{} statements and it may add to the dictionary of basic
  7510. blocks.
  7511. When the right-hand-side is an \code{if} expression, there is some
  7512. work to do. In particular, the two branches should be translated using
  7513. \code{explicate\_assign} and the condition expression should be
  7514. translated using \code{explicate\_pred}. Otherwise we can simply
  7515. generate an assignment statement, with the given left and right-hand
  7516. sides, concatenated with its continuation.
  7517. \begin{figure}[tbp]
  7518. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7519. def explicate_effect(e, cont, basic_blocks):
  7520. match e:
  7521. case IfExp(test, body, orelse):
  7522. ...
  7523. case Call(func, args):
  7524. ...
  7525. case Begin(body, result):
  7526. ...
  7527. case _:
  7528. ...
  7529. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7530. match rhs:
  7531. case IfExp(test, body, orelse):
  7532. ...
  7533. case Begin(body, result):
  7534. ...
  7535. case _:
  7536. return [Assign([lhs], rhs)] + cont
  7537. def explicate_pred(cnd, thn, els, basic_blocks):
  7538. match cnd:
  7539. case Compare(left, [op], [right]):
  7540. goto_thn = create_block(thn, basic_blocks)
  7541. goto_els = create_block(els, basic_blocks)
  7542. return [If(cnd, [goto_thn], [goto_els])]
  7543. case Constant(True):
  7544. return thn;
  7545. case Constant(False):
  7546. return els;
  7547. case UnaryOp(Not(), operand):
  7548. ...
  7549. case IfExp(test, body, orelse):
  7550. ...
  7551. case Begin(body, result):
  7552. ...
  7553. case _:
  7554. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7555. [create_block(els, basic_blocks)],
  7556. [create_block(thn, basic_blocks)])]
  7557. def explicate_stmt(s, cont, basic_blocks):
  7558. match s:
  7559. case Assign([lhs], rhs):
  7560. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7561. case Expr(value):
  7562. return explicate_effect(value, cont, basic_blocks)
  7563. case If(test, body, orelse):
  7564. ...
  7565. def explicate_control(p):
  7566. match p:
  7567. case Module(body):
  7568. new_body = [Return(Constant(0))]
  7569. basic_blocks = {}
  7570. for s in reversed(body):
  7571. new_body = explicate_stmt(s, new_body, basic_blocks)
  7572. basic_blocks[label_name('start')] = new_body
  7573. return CProgram(basic_blocks)
  7574. \end{lstlisting}
  7575. \caption{Skeleton for the \code{explicate\_control} pass.}
  7576. \label{fig:explicate-control-Lif}
  7577. \end{figure}
  7578. \fi}
  7579. {\if\edition\racketEd
  7580. \subsection{Explicate Tail and Assign}
  7581. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7582. additional cases for Boolean constants and \key{if}. The cases for
  7583. \code{if} should recursively compile the two branches using either
  7584. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7585. cases should then invoke \code{explicate\_pred} on the condition
  7586. expression, passing in the generated code for the two branches. For
  7587. example, consider the following program with an \code{if} in tail
  7588. position.
  7589. % cond_test_6.rkt
  7590. \begin{lstlisting}
  7591. (let ([x (read)])
  7592. (if (eq? x 0) 42 777))
  7593. \end{lstlisting}
  7594. The two branches are recursively compiled to return statements. We
  7595. then delegate to \code{explicate\_pred}, passing the condition
  7596. \code{(eq? x 0)} and the two return statements. We return to this
  7597. example shortly when we discuss \code{explicate\_pred}.
  7598. Next let us consider a program with an \code{if} on the right-hand
  7599. side of a \code{let}.
  7600. \begin{lstlisting}
  7601. (let ([y (read)])
  7602. (let ([x (if (eq? y 0) 40 777)])
  7603. (+ x 2)))
  7604. \end{lstlisting}
  7605. Note that the body of the inner \code{let} will have already been
  7606. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7607. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7608. to recursively process both branches of the \code{if}, and we do not
  7609. want to duplicate code, so we generate the following block using an
  7610. auxiliary function named \code{create\_block} that we discuss below.
  7611. \begin{lstlisting}
  7612. block_6:
  7613. return (+ x 2)
  7614. \end{lstlisting}
  7615. We then use \code{goto block\_6;} as the \code{cont} argument for
  7616. compiling the branches. So the two branches compile to
  7617. \begin{center}
  7618. \begin{minipage}{0.2\textwidth}
  7619. \begin{lstlisting}
  7620. x = 40;
  7621. goto block_6;
  7622. \end{lstlisting}
  7623. \end{minipage}
  7624. \hspace{0.5in} and \hspace{0.5in}
  7625. \begin{minipage}{0.2\textwidth}
  7626. \begin{lstlisting}
  7627. x = 777;
  7628. goto block_6;
  7629. \end{lstlisting}
  7630. \end{minipage}
  7631. \end{center}
  7632. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7633. \code{(eq? y 0)} and the above code for the branches.
  7634. \subsection{Create Block}
  7635. We recommend implementing the \code{create\_block} auxiliary function
  7636. as follows, using a global variable \code{basic-blocks} to store a
  7637. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7638. that \code{create\_block} generates a new label and then associates
  7639. the given \code{tail} with the new label in the \code{basic-blocks}
  7640. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7641. new label. However, if the given \code{tail} is already a \code{Goto},
  7642. then there is no need to generate a new label and entry in
  7643. \code{basic-blocks}; we can simply return that \code{Goto}.
  7644. %
  7645. \begin{lstlisting}
  7646. (define (create_block tail)
  7647. (match tail
  7648. [(Goto label) (Goto label)]
  7649. [else
  7650. (let ([label (gensym 'block)])
  7651. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7652. (Goto label))]))
  7653. \end{lstlisting}
  7654. \fi}
  7655. {\if\edition\racketEd
  7656. \subsection{Explicate Predicate}
  7657. \begin{figure}[tbp]
  7658. \begin{lstlisting}
  7659. (define (explicate_pred cnd thn els)
  7660. (match cnd
  7661. [(Var x) ___]
  7662. [(Let x rhs body) ___]
  7663. [(Prim 'not (list e)) ___]
  7664. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7665. (IfStmt (Prim op es) (create_block thn)
  7666. (create_block els))]
  7667. [(Bool b) (if b thn els)]
  7668. [(If cnd^ thn^ els^) ___]
  7669. [else (error "explicate_pred unhandled case" cnd)]))
  7670. \end{lstlisting}
  7671. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7672. \label{fig:explicate-pred}
  7673. \end{figure}
  7674. \fi}
  7675. \racket{The skeleton for the \code{explicate\_pred} function is given
  7676. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7677. 1) \code{cnd}, the condition expression of the \code{if},
  7678. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7679. and 3) \code{els}, the code generated by
  7680. explicate for the ``else'' branch. The \code{explicate\_pred}
  7681. function should match on \code{cnd} with a case for
  7682. every kind of expression that can have type \code{Boolean}.}
  7683. %
  7684. \python{The \code{explicate\_pred} function has four parameters: 1)
  7685. the condition expression, 2) the generated statements for the
  7686. ``then'' branch, 3) the generated statements for the ``else''
  7687. branch, and 4) the dictionary of basic blocks. The
  7688. \code{explicate\_pred} function returns a list of \LangCIf{}
  7689. statements and it may add to the dictionary of basic blocks.}
  7690. Consider the case for comparison operators. We translate the
  7691. comparison to an \code{if} statement whose branches are \code{goto}
  7692. statements created by applying \code{create\_block} to the code
  7693. generated for the \code{thn} and \code{els} branches. Let us
  7694. illustrate this translation by returning to the program with an
  7695. \code{if} expression in tail position, shown again below. We invoke
  7696. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7697. \python{\code{x == 0}}.
  7698. %
  7699. {\if\edition\racketEd
  7700. \begin{lstlisting}
  7701. (let ([x (read)])
  7702. (if (eq? x 0) 42 777))
  7703. \end{lstlisting}
  7704. \fi}
  7705. %
  7706. {\if\edition\pythonEd
  7707. \begin{lstlisting}
  7708. x = input_int()
  7709. 42 if x == 0 else 777
  7710. \end{lstlisting}
  7711. \fi}
  7712. %
  7713. \noindent The two branches \code{42} and \code{777} were already
  7714. compiled to \code{return} statements, from which we now create the
  7715. following blocks.
  7716. %
  7717. \begin{center}
  7718. \begin{minipage}{\textwidth}
  7719. \begin{lstlisting}
  7720. block_1:
  7721. return 42;
  7722. block_2:
  7723. return 777;
  7724. \end{lstlisting}
  7725. \end{minipage}
  7726. \end{center}
  7727. %
  7728. After that, \code{explicate\_pred} compiles the comparison
  7729. \racket{\code{(eq? x 0)}}
  7730. \python{\code{x == 0}}
  7731. to the following \code{if} statement.
  7732. %
  7733. {\if\edition\racketEd
  7734. \begin{center}
  7735. \begin{minipage}{\textwidth}
  7736. \begin{lstlisting}
  7737. if (eq? x 0)
  7738. goto block_1;
  7739. else
  7740. goto block_2;
  7741. \end{lstlisting}
  7742. \end{minipage}
  7743. \end{center}
  7744. \fi}
  7745. {\if\edition\pythonEd
  7746. \begin{center}
  7747. \begin{minipage}{\textwidth}
  7748. \begin{lstlisting}
  7749. if x == 0:
  7750. goto block_1;
  7751. else
  7752. goto block_2;
  7753. \end{lstlisting}
  7754. \end{minipage}
  7755. \end{center}
  7756. \fi}
  7757. Next consider the case for Boolean constants. We perform a kind of
  7758. partial evaluation\index{subject}{partial evaluation} and output
  7759. either the \code{thn} or \code{els} branch depending on whether the
  7760. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7761. following program.
  7762. {\if\edition\racketEd
  7763. \begin{lstlisting}
  7764. (if #t 42 777)
  7765. \end{lstlisting}
  7766. \fi}
  7767. {\if\edition\pythonEd
  7768. \begin{lstlisting}
  7769. 42 if True else 777
  7770. \end{lstlisting}
  7771. \fi}
  7772. %
  7773. \noindent Again, the two branches \code{42} and \code{777} were
  7774. compiled to \code{return} statements, so \code{explicate\_pred}
  7775. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7776. code for the ``then'' branch.
  7777. \begin{lstlisting}
  7778. return 42;
  7779. \end{lstlisting}
  7780. This case demonstrates that we sometimes discard the \code{thn} or
  7781. \code{els} blocks that are input to \code{explicate\_pred}.
  7782. The case for \key{if} expressions in \code{explicate\_pred} is
  7783. particularly illuminating because it deals with the challenges we
  7784. discussed above regarding nested \key{if} expressions
  7785. (Figure~\ref{fig:explicate-control-s1-38}). The
  7786. \racket{\lstinline{thn^}}\python{\code{body}} and
  7787. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7788. \key{if} inherit their context from the current one, that is,
  7789. predicate context. So you should recursively apply
  7790. \code{explicate\_pred} to the
  7791. \racket{\lstinline{thn^}}\python{\code{body}} and
  7792. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7793. those recursive calls, pass \code{thn} and \code{els} as the extra
  7794. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7795. inside each recursive call. As discussed above, to avoid duplicating
  7796. code, we need to add them to the dictionary of basic blocks so that we
  7797. can instead refer to them by name and execute them with a \key{goto}.
  7798. {\if\edition\pythonEd
  7799. %
  7800. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7801. three parameters: 1) the statement to be compiled, 2) the code for its
  7802. continuation, and 3) the dictionary of basic blocks. The
  7803. \code{explicate\_stmt} returns a list of statements and it may add to
  7804. the dictionary of basic blocks. The cases for assignment and an
  7805. expression-statement are given in full in the skeleton code: they
  7806. simply dispatch to \code{explicate\_assign} and
  7807. \code{explicate\_effect}, respectively. The case for \code{if}
  7808. statements is not given, and is similar to the case for \code{if}
  7809. expressions.
  7810. The \code{explicate\_control} function itself is given in
  7811. Figure~\ref{fig:explicate-control-Lif}. It applies
  7812. \code{explicate\_stmt} to each statement in the program, from back to
  7813. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7814. used as the continuation parameter in the next call to
  7815. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7816. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7817. the dictionary of basic blocks, labeling it as the ``start'' block.
  7818. %
  7819. \fi}
  7820. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7821. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7822. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7823. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7824. %% results from the two recursive calls. We complete the case for
  7825. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7826. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7827. %% the result $B_5$.
  7828. %% \[
  7829. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7830. %% \quad\Rightarrow\quad
  7831. %% B_5
  7832. %% \]
  7833. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7834. %% inherit the current context, so they are in tail position. Thus, the
  7835. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7836. %% \code{explicate\_tail}.
  7837. %% %
  7838. %% We need to pass $B_0$ as the accumulator argument for both of these
  7839. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7840. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7841. %% to the control-flow graph and obtain a promised goto $G_0$.
  7842. %% %
  7843. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7844. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7845. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7846. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7847. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7848. %% \[
  7849. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7850. %% \]
  7851. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7852. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7853. %% should not be confused with the labels for the blocks that appear in
  7854. %% the generated code. We initially construct unlabeled blocks; we only
  7855. %% attach labels to blocks when we add them to the control-flow graph, as
  7856. %% we see in the next case.
  7857. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7858. %% function. The context of the \key{if} is an assignment to some
  7859. %% variable $x$ and then the control continues to some promised block
  7860. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7861. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7862. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7863. %% branches of the \key{if} inherit the current context, so they are in
  7864. %% assignment positions. Let $B_2$ be the result of applying
  7865. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7866. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7867. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7868. %% the result of applying \code{explicate\_pred} to the predicate
  7869. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7870. %% translates to the promise $B_4$.
  7871. %% \[
  7872. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7873. %% \]
  7874. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7875. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7876. \code{remove\_complex\_operands} pass and then the
  7877. \code{explicate\_control} pass on the example program. We walk through
  7878. the output program.
  7879. %
  7880. Following the order of evaluation in the output of
  7881. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7882. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7883. in the predicate of the inner \key{if}. In the output of
  7884. \code{explicate\_control}, in the
  7885. block labeled \code{start}, are two assignment statements followed by a
  7886. \code{if} statement that branches to \code{block\_4} or
  7887. \code{block\_5}. The blocks associated with those labels contain the
  7888. translations of the code
  7889. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7890. and
  7891. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7892. respectively. In particular, we start \code{block\_4} with the
  7893. comparison
  7894. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7895. and then branch to \code{block\_2} or \code{block\_3},
  7896. which correspond to the two branches of the outer \key{if}, i.e.,
  7897. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7898. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7899. %
  7900. The story for \code{block\_5} is similar to that of \code{block\_4}.
  7901. %
  7902. \python{The \code{block\_1} corresponds to the \code{print} statment
  7903. at the end of the program.}
  7904. {\if\edition\racketEd
  7905. \subsection{Interactions between Explicate and Shrink}
  7906. The way in which the \code{shrink} pass transforms logical operations
  7907. such as \code{and} and \code{or} can impact the quality of code
  7908. generated by \code{explicate\_control}. For example, consider the
  7909. following program.
  7910. % cond_test_21.rkt, and_eq_input.py
  7911. \begin{lstlisting}
  7912. (if (and (eq? (read) 0) (eq? (read) 1))
  7913. 0
  7914. 42)
  7915. \end{lstlisting}
  7916. The \code{and} operation should transform into something that the
  7917. \code{explicate\_pred} function can still analyze and descend through to
  7918. reach the underlying \code{eq?} conditions. Ideally, your
  7919. \code{explicate\_control} pass should generate code similar to the
  7920. following for the above program.
  7921. \begin{center}
  7922. \begin{lstlisting}
  7923. start:
  7924. tmp1 = (read);
  7925. if (eq? tmp1 0) goto block40;
  7926. else goto block39;
  7927. block40:
  7928. tmp2 = (read);
  7929. if (eq? tmp2 1) goto block38;
  7930. else goto block39;
  7931. block38:
  7932. return 0;
  7933. block39:
  7934. return 42;
  7935. \end{lstlisting}
  7936. \end{center}
  7937. \fi}
  7938. \begin{exercise}\normalfont\normalsize
  7939. \racket{
  7940. Implement the pass \code{explicate\_control} by adding the cases for
  7941. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7942. \code{explicate\_assign} functions. Implement the auxiliary function
  7943. \code{explicate\_pred} for predicate contexts.}
  7944. \python{Implement \code{explicate\_control} pass with its
  7945. four auxiliary functions.}
  7946. %
  7947. Create test cases that exercise all of the new cases in the code for
  7948. this pass.
  7949. %
  7950. {\if\edition\racketEd
  7951. Add the following entry to the list of \code{passes} in
  7952. \code{run-tests.rkt} and then run this script to test your compiler.
  7953. \begin{lstlisting}
  7954. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7955. \end{lstlisting}
  7956. \fi}
  7957. \end{exercise}
  7958. \clearpage
  7959. \section{Select Instructions}
  7960. \label{sec:select-Lif}
  7961. \index{subject}{instruction selection}
  7962. The \code{select\_instructions} pass translates \LangCIf{} to
  7963. \LangXIfVar{}.
  7964. %
  7965. \racket{Recall that we implement this pass using three auxiliary
  7966. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7967. $\Tail$ in \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  7968. %
  7969. \racket{For $\Atm$, we have new cases for the Booleans.}
  7970. %
  7971. \python{We begin with the Boolean constants.}
  7972. We take the usual approach of encoding them as integers.
  7973. \[
  7974. \TRUE{} \quad\Rightarrow\quad \key{1}
  7975. \qquad\qquad
  7976. \FALSE{} \quad\Rightarrow\quad \key{0}
  7977. \]
  7978. For translating statements, we discuss some of the cases. The
  7979. \code{not} operation can be implemented in terms of \code{xorq} as we
  7980. discussed at the beginning of this section. Given an assignment, if
  7981. the left-hand side variable is the same as the argument of \code{not},
  7982. then just the \code{xorq} instruction suffices.
  7983. \[
  7984. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7985. \quad\Rightarrow\quad
  7986. \key{xorq}~\key{\$}1\key{,}~\Var
  7987. \]
  7988. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7989. semantics of x86. In the following translation, let $\Arg$ be the
  7990. result of translating $\Atm$ to x86.
  7991. \[
  7992. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7993. \quad\Rightarrow\quad
  7994. \begin{array}{l}
  7995. \key{movq}~\Arg\key{,}~\Var\\
  7996. \key{xorq}~\key{\$}1\key{,}~\Var
  7997. \end{array}
  7998. \]
  7999. Next consider the cases for equality comparisons. Translating this
  8000. operation to x86 is slightly involved due to the unusual nature of the
  8001. \key{cmpq} instruction that we discussed in Section~\ref{sec:x86-if}.
  8002. We recommend translating an assignment with an equality on the
  8003. right-hand side into a sequence of three instructions. \\
  8004. \begin{tabular}{lll}
  8005. \begin{minipage}{0.4\textwidth}
  8006. \begin{lstlisting}
  8007. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8008. \end{lstlisting}
  8009. \end{minipage}
  8010. &
  8011. $\Rightarrow$
  8012. &
  8013. \begin{minipage}{0.4\textwidth}
  8014. \begin{lstlisting}
  8015. cmpq |$\Arg_2$|, |$\Arg_1$|
  8016. sete %al
  8017. movzbq %al, |$\Var$|
  8018. \end{lstlisting}
  8019. \end{minipage}
  8020. \end{tabular} \\
  8021. The translations for the other comparison operators are similar to the
  8022. above but use different condition codes for the \code{set} instruction.
  8023. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8024. \key{goto} and \key{if} statements. Both are straightforward to
  8025. translate to x86.}
  8026. %
  8027. A \key{goto} statement becomes a jump instruction.
  8028. \[
  8029. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8030. \]
  8031. %
  8032. An \key{if} statement becomes a compare instruction followed by a
  8033. conditional jump (for the ``then'' branch) and the fall-through is to
  8034. a regular jump (for the ``else'' branch).\\
  8035. \begin{tabular}{lll}
  8036. \begin{minipage}{0.4\textwidth}
  8037. \begin{lstlisting}
  8038. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8039. goto |$\ell_1$||$\racket{\key{;}}$|
  8040. else|$\python{\key{:}}$|
  8041. goto |$\ell_2$||$\racket{\key{;}}$|
  8042. \end{lstlisting}
  8043. \end{minipage}
  8044. &
  8045. $\Rightarrow$
  8046. &
  8047. \begin{minipage}{0.4\textwidth}
  8048. \begin{lstlisting}
  8049. cmpq |$\Arg_2$|, |$\Arg_1$|
  8050. je |$\ell_1$|
  8051. jmp |$\ell_2$|
  8052. \end{lstlisting}
  8053. \end{minipage}
  8054. \end{tabular} \\
  8055. Again, the translations for the other comparison operators are similar to the
  8056. above but use different condition codes for the conditional jump instruction.
  8057. \python{Regarding the \key{return} statement, we recommend treating it
  8058. as an assignment to the \key{rax} register followed by a jump to the
  8059. conclusion of the \code{main} function.}
  8060. \begin{exercise}\normalfont\normalsize
  8061. Expand your \code{select\_instructions} pass to handle the new
  8062. features of the \LangCIf{} language.
  8063. %
  8064. {\if\edition\racketEd
  8065. Add the following entry to the list of \code{passes} in
  8066. \code{run-tests.rkt}
  8067. \begin{lstlisting}
  8068. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8069. \end{lstlisting}
  8070. \fi}
  8071. %
  8072. Run the script to test your compiler on all the test programs.
  8073. \end{exercise}
  8074. \section{Register Allocation}
  8075. \label{sec:register-allocation-Lif}
  8076. \index{subject}{register allocation}
  8077. The changes required for compiling \LangIf{} affect liveness analysis,
  8078. building the interference graph, and assigning homes, but the graph
  8079. coloring algorithm itself does not change.
  8080. \subsection{Liveness Analysis}
  8081. \label{sec:liveness-analysis-Lif}
  8082. \index{subject}{liveness analysis}
  8083. Recall that for \LangVar{} we implemented liveness analysis for a
  8084. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8085. the addition of \key{if} expressions to \LangIf{},
  8086. \code{explicate\_control} produces many basic blocks.
  8087. %% We recommend that you create a new auxiliary function named
  8088. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8089. %% control-flow graph.
  8090. The first question is: in what order should we process the basic blocks?
  8091. Recall that to perform liveness analysis on a basic block we need to
  8092. know the live-after set for the last instruction in the block. If a
  8093. basic block has no successors (i.e. contains no jumps to other
  8094. blocks), then it has an empty live-after set and we can immediately
  8095. apply liveness analysis to it. If a basic block has some successors,
  8096. then we need to complete liveness analysis on those blocks
  8097. first. These ordering contraints are the reverse of a
  8098. \emph{topological order}\index{subject}{topological order} on a graph
  8099. representation of the program. In particular, the \emph{control flow
  8100. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8101. of a program has a node for each basic block and an edge for each jump
  8102. from one block to another. It is straightforward to generate a CFG
  8103. from the dictionary of basic blocks. One then transposes the CFG and
  8104. applies the topological sort algorithm.
  8105. %
  8106. %
  8107. \racket{We recommend using the \code{tsort} and \code{transpose}
  8108. functions of the Racket \code{graph} package to accomplish this.}
  8109. %
  8110. \python{We provide implementations of \code{topological\_sort} and
  8111. \code{transpose} in the file \code{graph.py} of the support code.}
  8112. %
  8113. As an aside, a topological ordering is only guaranteed to exist if the
  8114. graph does not contain any cycles. This is the case for the
  8115. control-flow graphs that we generate from \LangIf{} programs.
  8116. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8117. and learn how to handle cycles in the control-flow graph.
  8118. \racket{You'll need to construct a directed graph to represent the
  8119. control-flow graph. Do not use the \code{directed-graph} of the
  8120. \code{graph} package because that only allows at most one edge
  8121. between each pair of vertices, but a control-flow graph may have
  8122. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8123. file in the support code implements a graph representation that
  8124. allows multiple edges between a pair of vertices.}
  8125. {\if\edition\racketEd
  8126. The next question is how to analyze jump instructions. Recall that in
  8127. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8128. \code{label->live} that maps each label to the set of live locations
  8129. at the beginning of its block. We use \code{label->live} to determine
  8130. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8131. that we have many basic blocks, \code{label->live} needs to be updated
  8132. as we process the blocks. In particular, after performing liveness
  8133. analysis on a block, we take the live-before set of its first
  8134. instruction and associate that with the block's label in the
  8135. \code{label->live} alist.
  8136. \fi}
  8137. %
  8138. {\if\edition\pythonEd
  8139. %
  8140. The next question is how to analyze jump instructions. The locations
  8141. that are live before a \code{jmp} should be the locations in
  8142. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8143. maintaining a dictionary named \code{live\_before\_block} that maps each
  8144. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8145. block. After performing liveness analysis on each block, we take the
  8146. live-before set of its first instruction and associate that with the
  8147. block's label in the \code{live\_before\_block} dictionary.
  8148. %
  8149. \fi}
  8150. In \LangXIfVar{} we also have the conditional jump
  8151. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8152. this instruction is particularly interesting because, during
  8153. compilation, we do not know which way a conditional jump will go. So
  8154. we do not know whether to use the live-before set for the block
  8155. associated with the $\itm{label}$ or the live-before set for the
  8156. following instruction. However, there is no harm to the correctness
  8157. of the generated code if we classify more locations as live than the
  8158. ones that are truly live during one particular execution of the
  8159. instruction. Thus, we can take the union of the live-before sets from
  8160. the following instruction and from the mapping for $\itm{label}$ in
  8161. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8162. The auxiliary functions for computing the variables in an
  8163. instruction's argument and for computing the variables read-from ($R$)
  8164. or written-to ($W$) by an instruction need to be updated to handle the
  8165. new kinds of arguments and instructions in \LangXIfVar{}.
  8166. \begin{exercise}\normalfont\normalsize
  8167. {\if\edition\racketEd
  8168. %
  8169. Update the \code{uncover\_live} pass to apply liveness analysis to
  8170. every basic block in the program.
  8171. %
  8172. Add the following entry to the list of \code{passes} in the
  8173. \code{run-tests.rkt} script.
  8174. \begin{lstlisting}
  8175. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8176. \end{lstlisting}
  8177. \fi}
  8178. {\if\edition\pythonEd
  8179. %
  8180. Update the \code{uncover\_live} function to perform liveness analysis,
  8181. in reverse topological order, on all of the basic blocks in the
  8182. program.
  8183. %
  8184. \fi}
  8185. % Check that the live-after sets that you generate for
  8186. % example X matches the following... -Jeremy
  8187. \end{exercise}
  8188. \subsection{Build the Interference Graph}
  8189. \label{sec:build-interference-Lif}
  8190. Many of the new instructions in \LangXIfVar{} can be handled in the
  8191. same way as the instructions in \LangXVar{}.
  8192. % Thus, if your code was
  8193. % already quite general, it will not need to be changed to handle the
  8194. % new instructions. If your code is not general enough, we recommend that
  8195. % you change your code to be more general. For example, you can factor
  8196. % out the computing of the the read and write sets for each kind of
  8197. % instruction into auxiliary functions.
  8198. %
  8199. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8200. similar to the \key{movq} instruction. See rule number 1 in
  8201. Section~\ref{sec:build-interference}.
  8202. \begin{exercise}\normalfont\normalsize
  8203. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8204. {\if\edition\racketEd
  8205. Add the following entries to the list of \code{passes} in the
  8206. \code{run-tests.rkt} script.
  8207. \begin{lstlisting}
  8208. (list "build_interference" build_interference interp-pseudo-x86-1)
  8209. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8210. \end{lstlisting}
  8211. \fi}
  8212. % Check that the interference graph that you generate for
  8213. % example X matches the following graph G... -Jeremy
  8214. \end{exercise}
  8215. \section{Patch Instructions}
  8216. The new instructions \key{cmpq} and \key{movzbq} have some special
  8217. restrictions that need to be handled in the \code{patch\_instructions}
  8218. pass.
  8219. %
  8220. The second argument of the \key{cmpq} instruction must not be an
  8221. immediate value (such as an integer). So if you are comparing two
  8222. immediates, we recommend inserting a \key{movq} instruction to put the
  8223. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8224. one memory reference.
  8225. %
  8226. The second argument of the \key{movzbq} must be a register.
  8227. \begin{exercise}\normalfont\normalsize
  8228. %
  8229. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8230. %
  8231. {\if\edition\racketEd
  8232. Add the following entry to the list of \code{passes} in
  8233. \code{run-tests.rkt} and then run this script to test your compiler.
  8234. \begin{lstlisting}
  8235. (list "patch_instructions" patch_instructions interp-x86-1)
  8236. \end{lstlisting}
  8237. \fi}
  8238. \end{exercise}
  8239. {\if\edition\pythonEd
  8240. \section{Prelude and Conclusion}
  8241. \label{sec:prelude-conclusion-cond}
  8242. The generation of the \code{main} function with its prelude and
  8243. conclusion must change to accomodate how the program now consists of
  8244. one or more basic blocks. After the prelude in \code{main}, jump to
  8245. the \code{start} block. Place the conclusion in a basic block labelled
  8246. with \code{conclusion}.
  8247. \fi}
  8248. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8249. \LangIf{} translated to x86, showing the results of
  8250. \code{explicate\_control}, \code{select\_instructions}, and the final
  8251. x86 assembly.
  8252. \begin{figure}[tbp]
  8253. {\if\edition\racketEd
  8254. \begin{tabular}{lll}
  8255. \begin{minipage}{0.4\textwidth}
  8256. % cond_test_20.rkt, eq_input.py
  8257. \begin{lstlisting}
  8258. (if (eq? (read) 1) 42 0)
  8259. \end{lstlisting}
  8260. $\Downarrow$
  8261. \begin{lstlisting}
  8262. start:
  8263. tmp7951 = (read);
  8264. if (eq? tmp7951 1)
  8265. goto block7952;
  8266. else
  8267. goto block7953;
  8268. block7952:
  8269. return 42;
  8270. block7953:
  8271. return 0;
  8272. \end{lstlisting}
  8273. $\Downarrow$
  8274. \begin{lstlisting}
  8275. start:
  8276. callq read_int
  8277. movq %rax, tmp7951
  8278. cmpq $1, tmp7951
  8279. je block7952
  8280. jmp block7953
  8281. block7953:
  8282. movq $0, %rax
  8283. jmp conclusion
  8284. block7952:
  8285. movq $42, %rax
  8286. jmp conclusion
  8287. \end{lstlisting}
  8288. \end{minipage}
  8289. &
  8290. $\Rightarrow\qquad$
  8291. \begin{minipage}{0.4\textwidth}
  8292. \begin{lstlisting}
  8293. start:
  8294. callq read_int
  8295. movq %rax, %rcx
  8296. cmpq $1, %rcx
  8297. je block7952
  8298. jmp block7953
  8299. block7953:
  8300. movq $0, %rax
  8301. jmp conclusion
  8302. block7952:
  8303. movq $42, %rax
  8304. jmp conclusion
  8305. .globl main
  8306. main:
  8307. pushq %rbp
  8308. movq %rsp, %rbp
  8309. pushq %r13
  8310. pushq %r12
  8311. pushq %rbx
  8312. pushq %r14
  8313. subq $0, %rsp
  8314. jmp start
  8315. conclusion:
  8316. addq $0, %rsp
  8317. popq %r14
  8318. popq %rbx
  8319. popq %r12
  8320. popq %r13
  8321. popq %rbp
  8322. retq
  8323. \end{lstlisting}
  8324. \end{minipage}
  8325. \end{tabular}
  8326. \fi}
  8327. {\if\edition\pythonEd
  8328. \begin{tabular}{lll}
  8329. \begin{minipage}{0.4\textwidth}
  8330. % cond_test_20.rkt, eq_input.py
  8331. \begin{lstlisting}
  8332. print(42 if input_int() == 1 else 0)
  8333. \end{lstlisting}
  8334. $\Downarrow$
  8335. \begin{lstlisting}
  8336. start:
  8337. tmp_0 = input_int()
  8338. if tmp_0 == 1:
  8339. goto block_3
  8340. else:
  8341. goto block_4
  8342. block_3:
  8343. tmp_1 = 42
  8344. goto block_2
  8345. block_4:
  8346. tmp_1 = 0
  8347. goto block_2
  8348. block_2:
  8349. print(tmp_1)
  8350. return 0
  8351. \end{lstlisting}
  8352. $\Downarrow$
  8353. \begin{lstlisting}
  8354. start:
  8355. callq read_int
  8356. movq %rax, tmp_0
  8357. cmpq 1, tmp_0
  8358. je block_3
  8359. jmp block_4
  8360. block_3:
  8361. movq 42, tmp_1
  8362. jmp block_2
  8363. block_4:
  8364. movq 0, tmp_1
  8365. jmp block_2
  8366. block_2:
  8367. movq tmp_1, %rdi
  8368. callq print_int
  8369. movq 0, %rax
  8370. jmp conclusion
  8371. \end{lstlisting}
  8372. \end{minipage}
  8373. &
  8374. $\Rightarrow\qquad$
  8375. \begin{minipage}{0.4\textwidth}
  8376. \begin{lstlisting}
  8377. .globl main
  8378. main:
  8379. pushq %rbp
  8380. movq %rsp, %rbp
  8381. subq $0, %rsp
  8382. jmp start
  8383. start:
  8384. callq read_int
  8385. movq %rax, %rcx
  8386. cmpq $1, %rcx
  8387. je block_3
  8388. jmp block_4
  8389. block_3:
  8390. movq $42, %rcx
  8391. jmp block_2
  8392. block_4:
  8393. movq $0, %rcx
  8394. jmp block_2
  8395. block_2:
  8396. movq %rcx, %rdi
  8397. callq print_int
  8398. movq $0, %rax
  8399. jmp conclusion
  8400. conclusion:
  8401. addq $0, %rsp
  8402. popq %rbp
  8403. retq
  8404. \end{lstlisting}
  8405. \end{minipage}
  8406. \end{tabular}
  8407. \fi}
  8408. \caption{Example compilation of an \key{if} expression to x86, showing
  8409. the results of \code{explicate\_control},
  8410. \code{select\_instructions}, and the final x86 assembly code. }
  8411. \label{fig:if-example-x86}
  8412. \end{figure}
  8413. \begin{figure}[tbp]
  8414. {\if\edition\racketEd
  8415. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8416. \node (Lif) at (0,2) {\large \LangIf{}};
  8417. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8418. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8419. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8420. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8421. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8422. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8423. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8424. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8425. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8426. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8427. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8428. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8429. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8430. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8431. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8432. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8433. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8434. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8435. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8436. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8437. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8438. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8439. \end{tikzpicture}
  8440. \fi}
  8441. {\if\edition\pythonEd
  8442. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8443. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8444. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8445. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8446. \node (C-1) at (3,0) {\large \LangCIf{}};
  8447. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8448. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8449. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8450. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8451. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8452. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8453. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8454. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8455. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8456. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8457. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8458. \end{tikzpicture}
  8459. \fi}
  8460. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8461. \label{fig:Lif-passes}
  8462. \end{figure}
  8463. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8464. compilation of \LangIf{}.
  8465. \section{Challenge: Optimize Blocks and Remove Jumps}
  8466. \label{sec:opt-jumps}
  8467. We discuss two optional challenges that involve optimizing the
  8468. control-flow of the program.
  8469. \subsection{Optimize Blocks}
  8470. The algorithm for \code{explicate\_control} that we discussed in
  8471. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8472. blocks. It creates a basic block whenever a continuation \emph{might}
  8473. get used more than once (e.g., whenever the \code{cont} parameter is
  8474. passed into two or more recursive calls). However, some continuation
  8475. arguments may not be used at all. For example, consider the case for
  8476. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8477. \code{els} continuation.
  8478. %
  8479. {\if\edition\racketEd
  8480. The following example program falls into this
  8481. case, and it creates two unused blocks.
  8482. \begin{center}
  8483. \begin{tabular}{lll}
  8484. \begin{minipage}{0.4\textwidth}
  8485. % cond_test_82.rkt
  8486. \begin{lstlisting}
  8487. (let ([y (if #t
  8488. (read)
  8489. (if (eq? (read) 0)
  8490. 777
  8491. (let ([x (read)])
  8492. (+ 1 x))))])
  8493. (+ y 2))
  8494. \end{lstlisting}
  8495. \end{minipage}
  8496. &
  8497. $\Rightarrow$
  8498. &
  8499. \begin{minipage}{0.55\textwidth}
  8500. \begin{lstlisting}
  8501. start:
  8502. y = (read);
  8503. goto block_5;
  8504. block_5:
  8505. return (+ y 2);
  8506. block_6:
  8507. y = 777;
  8508. goto block_5;
  8509. block_7:
  8510. x = (read);
  8511. y = (+ 1 x2);
  8512. goto block_5;
  8513. \end{lstlisting}
  8514. \end{minipage}
  8515. \end{tabular}
  8516. \end{center}
  8517. \fi}
  8518. So the question is how can we decide whether to create a basic block?
  8519. \emph{Lazy evaluation}\index{subject}{lazy
  8520. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8521. delaying the creation of a basic block until the point in time where
  8522. we know it will be used.
  8523. %
  8524. {\if\edition\racketEd
  8525. %
  8526. Racket provides support for
  8527. lazy evaluation with the
  8528. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8529. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8530. \index{subject}{delay} creates a
  8531. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8532. expressions is postponed. When \key{(force}
  8533. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8534. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8535. result of $e_n$ is cached in the promise and returned. If \code{force}
  8536. is applied again to the same promise, then the cached result is
  8537. returned. If \code{force} is applied to an argument that is not a
  8538. promise, \code{force} simply returns the argument.
  8539. %
  8540. \fi}
  8541. %
  8542. {\if\edition\pythonEd
  8543. %
  8544. While Python does not provide direct support for lazy evaluation, it
  8545. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8546. by wrapping it inside a function with no parameters. We can
  8547. \emph{force} its evaluation by calling the function. However, in some
  8548. cases of \code{explicate\_pred}, etc., we will return a list of
  8549. statements and in other cases we will return a function that computes
  8550. a list of statements. We use the term \emph{promise} to refer to a
  8551. value that may be delayed. To uniformly deal with
  8552. promises, we define the following \code{force} function that checks
  8553. whether its input is delayed (i.e., whether it is a function) and then
  8554. either 1) calls the function, or 2) returns the input.
  8555. \begin{lstlisting}
  8556. def force(promise):
  8557. if isinstance(promise, types.FunctionType):
  8558. return promise()
  8559. else:
  8560. return promise
  8561. \end{lstlisting}
  8562. %
  8563. \fi}
  8564. We use promises for the input and output of the functions
  8565. \code{explicate\_pred}, \code{explicate\_assign},
  8566. %
  8567. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8568. %
  8569. So instead of taking and returning \racket{$\Tail$
  8570. expressions}\python{lists of statments}, they take and return
  8571. promises. Furthermore, when we come to a situation in which a
  8572. continuation might be used more than once, as in the case for
  8573. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8574. that creates a basic block for each continuation (if there is not
  8575. already one) and then returns a \code{goto} statement to that basic
  8576. block. When we come to a situation where we have a promise but need an
  8577. actual piece of code, e.g. to create a larger piece of code with a
  8578. constructor such as \code{Seq}, then insert a call to \code{force}.
  8579. %
  8580. {\if\edition\racketEd
  8581. %
  8582. Also we must modify the \code{create\_block} function to begin with
  8583. \code{delay} to create a promise. When forced, this promise forces the
  8584. original promise. If that returns a \code{Goto} (because the block was
  8585. already added to \code{basic-blocks}), then we return the
  8586. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8587. return a \code{Goto} to the new label.
  8588. \begin{center}
  8589. \begin{minipage}{\textwidth}
  8590. \begin{lstlisting}
  8591. (define (create_block tail)
  8592. (delay
  8593. (define t (force tail))
  8594. (match t
  8595. [(Goto label) (Goto label)]
  8596. [else
  8597. (let ([label (gensym 'block)])
  8598. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8599. (Goto label))]))
  8600. \end{lstlisting}
  8601. \end{minipage}
  8602. \end{center}
  8603. \fi}
  8604. {\if\edition\pythonEd
  8605. %
  8606. Here is the new version of the \code{create\_block} auxiliary function
  8607. that works on promises and that checks whether the block consists of a
  8608. solitary \code{goto} statement.\\
  8609. \begin{minipage}{\textwidth}
  8610. \begin{lstlisting}
  8611. def create_block(promise, basic_blocks):
  8612. stmts = force(promise)
  8613. match stmts:
  8614. case [Goto(l)]:
  8615. return Goto(l)
  8616. case _:
  8617. label = label_name(generate_name('block'))
  8618. basic_blocks[label] = stmts
  8619. return Goto(label)
  8620. \end{lstlisting}
  8621. \end{minipage}
  8622. \fi}
  8623. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8624. improved \code{explicate\_control} on the above example. As you can
  8625. see, the number of basic blocks has been reduced from 4 blocks (see
  8626. Figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8627. \begin{figure}[tbp]
  8628. {\if\edition\racketEd
  8629. \begin{tabular}{lll}
  8630. \begin{minipage}{0.4\textwidth}
  8631. % cond_test_82.rkt
  8632. \begin{lstlisting}
  8633. (let ([y (if #t
  8634. (read)
  8635. (if (eq? (read) 0)
  8636. 777
  8637. (let ([x (read)])
  8638. (+ 1 x))))])
  8639. (+ y 2))
  8640. \end{lstlisting}
  8641. \end{minipage}
  8642. &
  8643. $\Rightarrow$
  8644. &
  8645. \begin{minipage}{0.55\textwidth}
  8646. \begin{lstlisting}
  8647. start:
  8648. y = (read);
  8649. goto block_5;
  8650. block_5:
  8651. return (+ y 2);
  8652. \end{lstlisting}
  8653. \end{minipage}
  8654. \end{tabular}
  8655. \fi}
  8656. {\if\edition\pythonEd
  8657. \begin{tabular}{lll}
  8658. \begin{minipage}{0.4\textwidth}
  8659. % cond_test_41.rkt
  8660. \begin{lstlisting}
  8661. x = input_int()
  8662. y = input_int()
  8663. print(y + 2 \
  8664. if (x == 0 \
  8665. if x < 1 \
  8666. else x == 2) \
  8667. else y + 10)
  8668. \end{lstlisting}
  8669. \end{minipage}
  8670. &
  8671. $\Rightarrow$
  8672. &
  8673. \begin{minipage}{0.55\textwidth}
  8674. \begin{lstlisting}
  8675. start:
  8676. x = input_int()
  8677. y = input_int()
  8678. if x < 1:
  8679. goto block_4
  8680. else:
  8681. goto block_5
  8682. block_4:
  8683. if x == 0:
  8684. goto block_2
  8685. else:
  8686. goto block_3
  8687. block_5:
  8688. if x == 2:
  8689. goto block_2
  8690. else:
  8691. goto block_3
  8692. block_2:
  8693. tmp_0 = y + 2
  8694. goto block_1
  8695. block_3:
  8696. tmp_0 = y + 10
  8697. goto block_1
  8698. block_1:
  8699. print(tmp_0)
  8700. return 0
  8701. \end{lstlisting}
  8702. \end{minipage}
  8703. \end{tabular}
  8704. \fi}
  8705. \caption{Translation from \LangIf{} to \LangCIf{}
  8706. via the improved \code{explicate\_control}.}
  8707. \label{fig:explicate-control-challenge}
  8708. \end{figure}
  8709. %% Recall that in the example output of \code{explicate\_control} in
  8710. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8711. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8712. %% block. The first goal of this challenge assignment is to remove those
  8713. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8714. %% \code{explicate\_control} on the left and shows the result of bypassing
  8715. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8716. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8717. %% \code{block55}. The optimized code on the right of
  8718. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8719. %% \code{then} branch jumping directly to \code{block55}. The story is
  8720. %% similar for the \code{else} branch, as well as for the two branches in
  8721. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8722. %% have been optimized in this way, there are no longer any jumps to
  8723. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8724. %% \begin{figure}[tbp]
  8725. %% \begin{tabular}{lll}
  8726. %% \begin{minipage}{0.4\textwidth}
  8727. %% \begin{lstlisting}
  8728. %% block62:
  8729. %% tmp54 = (read);
  8730. %% if (eq? tmp54 2) then
  8731. %% goto block59;
  8732. %% else
  8733. %% goto block60;
  8734. %% block61:
  8735. %% tmp53 = (read);
  8736. %% if (eq? tmp53 0) then
  8737. %% goto block57;
  8738. %% else
  8739. %% goto block58;
  8740. %% block60:
  8741. %% goto block56;
  8742. %% block59:
  8743. %% goto block55;
  8744. %% block58:
  8745. %% goto block56;
  8746. %% block57:
  8747. %% goto block55;
  8748. %% block56:
  8749. %% return (+ 700 77);
  8750. %% block55:
  8751. %% return (+ 10 32);
  8752. %% start:
  8753. %% tmp52 = (read);
  8754. %% if (eq? tmp52 1) then
  8755. %% goto block61;
  8756. %% else
  8757. %% goto block62;
  8758. %% \end{lstlisting}
  8759. %% \end{minipage}
  8760. %% &
  8761. %% $\Rightarrow$
  8762. %% &
  8763. %% \begin{minipage}{0.55\textwidth}
  8764. %% \begin{lstlisting}
  8765. %% block62:
  8766. %% tmp54 = (read);
  8767. %% if (eq? tmp54 2) then
  8768. %% goto block55;
  8769. %% else
  8770. %% goto block56;
  8771. %% block61:
  8772. %% tmp53 = (read);
  8773. %% if (eq? tmp53 0) then
  8774. %% goto block55;
  8775. %% else
  8776. %% goto block56;
  8777. %% block56:
  8778. %% return (+ 700 77);
  8779. %% block55:
  8780. %% return (+ 10 32);
  8781. %% start:
  8782. %% tmp52 = (read);
  8783. %% if (eq? tmp52 1) then
  8784. %% goto block61;
  8785. %% else
  8786. %% goto block62;
  8787. %% \end{lstlisting}
  8788. %% \end{minipage}
  8789. %% \end{tabular}
  8790. %% \caption{Optimize jumps by removing trivial blocks.}
  8791. %% \label{fig:optimize-jumps}
  8792. %% \end{figure}
  8793. %% The name of this pass is \code{optimize-jumps}. We recommend
  8794. %% implementing this pass in two phases. The first phrase builds a hash
  8795. %% table that maps labels to possibly improved labels. The second phase
  8796. %% changes the target of each \code{goto} to use the improved label. If
  8797. %% the label is for a trivial block, then the hash table should map the
  8798. %% label to the first non-trivial block that can be reached from this
  8799. %% label by jumping through trivial blocks. If the label is for a
  8800. %% non-trivial block, then the hash table should map the label to itself;
  8801. %% we do not want to change jumps to non-trivial blocks.
  8802. %% The first phase can be accomplished by constructing an empty hash
  8803. %% table, call it \code{short-cut}, and then iterating over the control
  8804. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8805. %% then update the hash table, mapping the block's source to the target
  8806. %% of the \code{goto}. Also, the hash table may already have mapped some
  8807. %% labels to the block's source, to you must iterate through the hash
  8808. %% table and update all of those so that they instead map to the target
  8809. %% of the \code{goto}.
  8810. %% For the second phase, we recommend iterating through the $\Tail$ of
  8811. %% each block in the program, updating the target of every \code{goto}
  8812. %% according to the mapping in \code{short-cut}.
  8813. \begin{exercise}\normalfont\normalsize
  8814. Implement the improvements to the \code{explicate\_control} pass.
  8815. Check that it removes trivial blocks in a few example programs. Then
  8816. check that your compiler still passes all of your tests.
  8817. \end{exercise}
  8818. \subsection{Remove Jumps}
  8819. There is an opportunity for removing jumps that is apparent in the
  8820. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8821. ends with a jump to \code{block\_5} and there are no other jumps to
  8822. \code{block\_5} in the rest of the program. In this situation we can
  8823. avoid the runtime overhead of this jump by merging \code{block\_5}
  8824. into the preceding block, in this case the \code{start} block.
  8825. Figure~\ref{fig:remove-jumps} shows the output of
  8826. \code{allocate\_registers} on the left and the result of this
  8827. optimization on the right.
  8828. \begin{figure}[tbp]
  8829. {\if\edition\racketEd
  8830. \begin{tabular}{lll}
  8831. \begin{minipage}{0.5\textwidth}
  8832. % cond_test_82.rkt
  8833. \begin{lstlisting}
  8834. start:
  8835. callq read_int
  8836. movq %rax, %rcx
  8837. jmp block_5
  8838. block_5:
  8839. movq %rcx, %rax
  8840. addq $2, %rax
  8841. jmp conclusion
  8842. \end{lstlisting}
  8843. \end{minipage}
  8844. &
  8845. $\Rightarrow\qquad$
  8846. \begin{minipage}{0.4\textwidth}
  8847. \begin{lstlisting}
  8848. start:
  8849. callq read_int
  8850. movq %rax, %rcx
  8851. movq %rcx, %rax
  8852. addq $2, %rax
  8853. jmp conclusion
  8854. \end{lstlisting}
  8855. \end{minipage}
  8856. \end{tabular}
  8857. \fi}
  8858. {\if\edition\pythonEd
  8859. \begin{tabular}{lll}
  8860. \begin{minipage}{0.5\textwidth}
  8861. % cond_test_20.rkt
  8862. \begin{lstlisting}
  8863. start:
  8864. callq read_int
  8865. movq %rax, tmp_0
  8866. cmpq 1, tmp_0
  8867. je block_3
  8868. jmp block_4
  8869. block_3:
  8870. movq 42, tmp_1
  8871. jmp block_2
  8872. block_4:
  8873. movq 0, tmp_1
  8874. jmp block_2
  8875. block_2:
  8876. movq tmp_1, %rdi
  8877. callq print_int
  8878. movq 0, %rax
  8879. jmp conclusion
  8880. \end{lstlisting}
  8881. \end{minipage}
  8882. &
  8883. $\Rightarrow\qquad$
  8884. \begin{minipage}{0.4\textwidth}
  8885. \begin{lstlisting}
  8886. start:
  8887. callq read_int
  8888. movq %rax, tmp_0
  8889. cmpq 1, tmp_0
  8890. je block_3
  8891. movq 0, tmp_1
  8892. jmp block_2
  8893. block_3:
  8894. movq 42, tmp_1
  8895. jmp block_2
  8896. block_2:
  8897. movq tmp_1, %rdi
  8898. callq print_int
  8899. movq 0, %rax
  8900. jmp conclusion
  8901. \end{lstlisting}
  8902. \end{minipage}
  8903. \end{tabular}
  8904. \fi}
  8905. \caption{Merging basic blocks by removing unnecessary jumps.}
  8906. \label{fig:remove-jumps}
  8907. \end{figure}
  8908. \begin{exercise}\normalfont\normalsize
  8909. %
  8910. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8911. into their preceding basic block, when there is only one preceding
  8912. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8913. %
  8914. {\if\edition\racketEd
  8915. In the \code{run-tests.rkt} script, add the following entry to the
  8916. list of \code{passes} between \code{allocate\_registers}
  8917. and \code{patch\_instructions}.
  8918. \begin{lstlisting}
  8919. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8920. \end{lstlisting}
  8921. \fi}
  8922. %
  8923. Run the script to test your compiler.
  8924. %
  8925. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8926. blocks on several test programs.
  8927. \end{exercise}
  8928. \section{Further Reading}
  8929. \label{sec:cond-further-reading}
  8930. The algorithm for the \code{explicate\_control} pass is based on the
  8931. \code{explose-basic-blocks} pass in the course notes of
  8932. \citet{Dybvig:2010aa}.
  8933. %
  8934. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8935. \citet{Appel:2003fk}, and is related to translations into continuation
  8936. passing
  8937. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8938. %
  8939. The treatment of conditionals in the \code{explicate\_control} pass is
  8940. similar to short-cut boolean
  8941. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8942. and the case-of-case transformation~\citep{PeytonJones:1998}.
  8943. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8944. \chapter{Loops and Dataflow Analysis}
  8945. \label{ch:Lwhile}
  8946. % TODO: define R'_8
  8947. % TODO: multi-graph
  8948. {\if\edition\racketEd
  8949. %
  8950. In this chapter we study two features that are the hallmarks of
  8951. imperative programming languages: loops and assignments to local
  8952. variables. The following example demonstrates these new features by
  8953. computing the sum of the first five positive integers.
  8954. % similar to loop_test_1.rkt
  8955. \begin{lstlisting}
  8956. (let ([sum 0])
  8957. (let ([i 5])
  8958. (begin
  8959. (while (> i 0)
  8960. (begin
  8961. (set! sum (+ sum i))
  8962. (set! i (- i 1))))
  8963. sum)))
  8964. \end{lstlisting}
  8965. The \code{while} loop consists of a condition and a
  8966. body\footnote{The \code{while} loop is not a built-in
  8967. feature of the Racket language, but Racket includes many looping
  8968. constructs and it is straightforward to define \code{while} as a
  8969. macro.}. The body is evaluated repeatedly so long as the condition
  8970. remains true.
  8971. %
  8972. The \code{set!} consists of a variable and a right-hand-side
  8973. expression. The \code{set!} updates value of the variable to the
  8974. value of the right-hand-side.
  8975. %
  8976. The primary purpose of both the \code{while} loop and \code{set!} is
  8977. to cause side effects, so they do not have a meaningful result
  8978. value. Instead their result is the \code{\#<void>} value. The
  8979. expression \code{(void)} is an explicit way to create the
  8980. \code{\#<void>} value and it has type \code{Void}. The
  8981. \code{\#<void>} value can be passed around just like other values
  8982. inside an \LangLoop{} program and it can be compared for equality with
  8983. another \code{\#<void>} value. However, there are no other operations
  8984. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  8985. Racket defines the \code{void?} predicate that returns \code{\#t}
  8986. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  8987. %
  8988. \footnote{Racket's \code{Void} type corresponds to what is often
  8989. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  8990. by a single value \code{\#<void>} which corresponds to \code{unit}
  8991. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  8992. %
  8993. With the addition of side-effecting features such as \code{while} loop
  8994. and \code{set!}, it is helpful to also include in a language feature
  8995. for sequencing side effects: the \code{begin} expression. It consists
  8996. of one or more subexpressions that are evaluated left-to-right.
  8997. %
  8998. \fi}
  8999. {\if\edition\pythonEd
  9000. %
  9001. In this chapter we study loops, one of the hallmarks of imperative
  9002. programming languages. The following example demonstrates the
  9003. \code{while} loop by computing the sum of the first five positive
  9004. integers.
  9005. \begin{lstlisting}
  9006. sum = 0
  9007. i = 5
  9008. while i > 0:
  9009. sum = sum + i
  9010. i = i - 1
  9011. print(sum)
  9012. \end{lstlisting}
  9013. The \code{while} loop consists of a condition expression and a body (a
  9014. sequence of statements). The body is evaluated repeatedly so long as
  9015. the condition remains true.
  9016. %
  9017. \fi}
  9018. \section{The \LangLoop{} Language}
  9019. \newcommand{\LwhileGrammarRacket}{
  9020. \begin{array}{lcl}
  9021. \Type &::=& \key{Void}\\
  9022. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9023. \MID \CBEGIN{\Exp\ldots}{\Exp}
  9024. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9025. \end{array}
  9026. }
  9027. \newcommand{\LwhileASTRacket}{
  9028. \begin{array}{lcl}
  9029. \Type &::=& \key{Void}\\
  9030. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  9031. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  9032. \end{array}
  9033. }
  9034. \newcommand{\LwhileGrammarPython}{
  9035. \begin{array}{rcl}
  9036. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9037. \end{array}
  9038. }
  9039. \newcommand{\LwhileASTPython}{
  9040. \begin{array}{lcl}
  9041. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9042. \end{array}
  9043. }
  9044. \begin{figure}[tp]
  9045. \centering
  9046. \fbox{
  9047. \begin{minipage}{0.96\textwidth}
  9048. \small
  9049. {\if\edition\racketEd
  9050. \[
  9051. \begin{array}{l}
  9052. \gray{\LintGrammarRacket{}} \\ \hline
  9053. \gray{\LvarGrammarRacket{}} \\ \hline
  9054. \gray{\LifGrammarRacket{}} \\ \hline
  9055. \LwhileGrammarRacket \\
  9056. \begin{array}{lcl}
  9057. \LangLoopM{} &::=& \Exp
  9058. \end{array}
  9059. \end{array}
  9060. \]
  9061. \fi}
  9062. {\if\edition\pythonEd
  9063. \[
  9064. \begin{array}{l}
  9065. \gray{\LintGrammarPython} \\ \hline
  9066. \gray{\LvarGrammarPython} \\ \hline
  9067. \gray{\LifGrammarPython} \\ \hline
  9068. \LwhileGrammarPython \\
  9069. \begin{array}{rcl}
  9070. \LangLoopM{} &::=& \Stmt^{*}
  9071. \end{array}
  9072. \end{array}
  9073. \]
  9074. \fi}
  9075. \end{minipage}
  9076. }
  9077. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9078. \label{fig:Lwhile-concrete-syntax}
  9079. \end{figure}
  9080. \begin{figure}[tp]
  9081. \centering
  9082. \fbox{
  9083. \begin{minipage}{0.96\textwidth}
  9084. \small
  9085. {\if\edition\racketEd
  9086. \[
  9087. \begin{array}{l}
  9088. \gray{\LintOpAST} \\ \hline
  9089. \gray{\LvarASTRacket{}} \\ \hline
  9090. \gray{\LifASTRacket{}} \\ \hline
  9091. \LwhileASTRacket{} \\
  9092. \begin{array}{lcl}
  9093. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9094. \end{array}
  9095. \end{array}
  9096. \]
  9097. \fi}
  9098. {\if\edition\pythonEd
  9099. \[
  9100. \begin{array}{l}
  9101. \gray{\LintASTPython} \\ \hline
  9102. \gray{\LvarASTPython} \\ \hline
  9103. \gray{\LifASTPython} \\ \hline
  9104. \LwhileASTPython \\
  9105. \begin{array}{lcl}
  9106. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9107. \end{array}
  9108. \end{array}
  9109. \]
  9110. \fi}
  9111. \end{minipage}
  9112. }
  9113. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9114. \label{fig:Lwhile-syntax}
  9115. \end{figure}
  9116. The concrete syntax of \LangLoop{} is defined in
  9117. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9118. in Figure~\ref{fig:Lwhile-syntax}.
  9119. %
  9120. The definitional interpreter for \LangLoop{} is shown in
  9121. Figure~\ref{fig:interp-Lwhile}.
  9122. %
  9123. {\if\edition\racketEd
  9124. %
  9125. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9126. and \code{Void} and we make changes to the cases for \code{Var} and
  9127. \code{Let} regarding variables. To support assignment to variables and
  9128. to make their lifetimes indefinite (see the second example in
  9129. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9130. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9131. value.
  9132. %
  9133. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9134. variable in the environment to obtain a boxed value and then we change
  9135. it using \code{set-box!} to the result of evaluating the right-hand
  9136. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9137. %
  9138. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9139. if the result is true, 2) evaluate the body.
  9140. The result value of a \code{while} loop is also \code{\#<void>}.
  9141. %
  9142. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9143. subexpressions \itm{es} for their effects and then evaluates
  9144. and returns the result from \itm{body}.
  9145. %
  9146. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9147. %
  9148. \fi}
  9149. {\if\edition\pythonEd
  9150. %
  9151. We add a new case for \code{While} in the \code{interp\_stmts}
  9152. function, where we repeatedly interpret the \code{body} so long as the
  9153. \code{test} expression remains true.
  9154. %
  9155. \fi}
  9156. \begin{figure}[tbp]
  9157. {\if\edition\racketEd
  9158. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9159. (define interp-Lwhile-class
  9160. (class interp-Lif-class
  9161. (super-new)
  9162. (define/override ((interp-exp env) e)
  9163. (define recur (interp-exp env))
  9164. (match e
  9165. [(Let x e body)
  9166. (define new-env (dict-set env x (box (recur e))))
  9167. ((interp-exp new-env) body)]
  9168. [(Var x) (unbox (dict-ref env x))]
  9169. [(SetBang x rhs)
  9170. (set-box! (dict-ref env x) (recur rhs))]
  9171. [(WhileLoop cnd body)
  9172. (define (loop)
  9173. (cond [(recur cnd) (recur body) (loop)]
  9174. [else (void)]))
  9175. (loop)]
  9176. [(Begin es body)
  9177. (for ([e es]) (recur e))
  9178. (recur body)]
  9179. [(Void) (void)]
  9180. [else ((super interp-exp env) e)]))
  9181. ))
  9182. (define (interp-Lwhile p)
  9183. (send (new interp-Lwhile-class) interp-program p))
  9184. \end{lstlisting}
  9185. \fi}
  9186. {\if\edition\pythonEd
  9187. \begin{lstlisting}
  9188. class InterpLwhile(InterpLif):
  9189. def interp_stmts(self, ss, env):
  9190. if len(ss) == 0:
  9191. return
  9192. match ss[0]:
  9193. case While(test, body, []):
  9194. while self.interp_exp(test, env):
  9195. self.interp_stmts(body, env)
  9196. return self.interp_stmts(ss[1:], env)
  9197. case _:
  9198. return super().interp_stmts(ss, env)
  9199. \end{lstlisting}
  9200. \fi}
  9201. \caption{Interpreter for \LangLoop{}.}
  9202. \label{fig:interp-Lwhile}
  9203. \end{figure}
  9204. The type checker for \LangLoop{} is defined in
  9205. Figure~\ref{fig:type-check-Lwhile}.
  9206. %
  9207. {\if\edition\racketEd
  9208. %
  9209. The type checking of the \code{SetBang} expression requires the type
  9210. of the variable and the right-hand-side to agree. The result type is
  9211. \code{Void}. For \code{while}, the condition must be a \code{Boolean}
  9212. and the result type is \code{Void}. For \code{Begin}, the result type
  9213. is the type of its last subexpression.
  9214. %
  9215. \fi}
  9216. %
  9217. {\if\edition\pythonEd
  9218. %
  9219. A \code{while} loop is well typed if the type of the \code{test}
  9220. expression is \code{bool} and the statements in the \code{body} are
  9221. well typed.
  9222. %
  9223. \fi}
  9224. \begin{figure}[tbp]
  9225. {\if\edition\racketEd
  9226. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9227. (define type-check-Lwhile-class
  9228. (class type-check-Lif-class
  9229. (super-new)
  9230. (inherit check-type-equal?)
  9231. (define/override (type-check-exp env)
  9232. (lambda (e)
  9233. (define recur (type-check-exp env))
  9234. (match e
  9235. [(SetBang x rhs)
  9236. (define-values (rhs^ rhsT) (recur rhs))
  9237. (define varT (dict-ref env x))
  9238. (check-type-equal? rhsT varT e)
  9239. (values (SetBang x rhs^) 'Void)]
  9240. [(WhileLoop cnd body)
  9241. (define-values (cnd^ Tc) (recur cnd))
  9242. (check-type-equal? Tc 'Boolean e)
  9243. (define-values (body^ Tbody) ((type-check-exp env) body))
  9244. (values (WhileLoop cnd^ body^) 'Void)]
  9245. [(Begin es body)
  9246. (define-values (es^ ts)
  9247. (for/lists (l1 l2) ([e es]) (recur e)))
  9248. (define-values (body^ Tbody) (recur body))
  9249. (values (Begin es^ body^) Tbody)]
  9250. [else ((super type-check-exp env) e)])))
  9251. ))
  9252. (define (type-check-Lwhile p)
  9253. (send (new type-check-Lwhile-class) type-check-program p))
  9254. \end{lstlisting}
  9255. \fi}
  9256. {\if\edition\pythonEd
  9257. \begin{lstlisting}
  9258. class TypeCheckLwhile(TypeCheckLif):
  9259. def type_check_stmts(self, ss, env):
  9260. if len(ss) == 0:
  9261. return
  9262. match ss[0]:
  9263. case While(test, body, []):
  9264. test_t = self.type_check_exp(test, env)
  9265. check_type_equal(bool, test_t, test)
  9266. body_t = self.type_check_stmts(body, env)
  9267. return self.type_check_stmts(ss[1:], env)
  9268. case _:
  9269. return super().type_check_stmts(ss, env)
  9270. \end{lstlisting}
  9271. \fi}
  9272. \caption{Type checker for the \LangLoop{} language.}
  9273. \label{fig:type-check-Lwhile}
  9274. \end{figure}
  9275. {\if\edition\racketEd
  9276. %
  9277. At first glance, the translation of these language features to x86
  9278. seems straightforward because the \LangCIf{} intermediate language
  9279. already supports all of the ingredients that we need: assignment,
  9280. \code{goto}, conditional branching, and sequencing. However, there are
  9281. complications that arise which we discuss in the next section. After
  9282. that we introduce the changes necessary to the existing passes.
  9283. %
  9284. \fi}
  9285. {\if\edition\pythonEd
  9286. %
  9287. At first glance, the translation of \code{while} loops to x86 seems
  9288. straightforward because the \LangCIf{} intermediate language already
  9289. supports \code{goto} and conditional branching. However, there are
  9290. complications that arise which we discuss in the next section. After
  9291. that we introduce the changes necessary to the existing passes.
  9292. %
  9293. \fi}
  9294. \section{Cyclic Control Flow and Dataflow Analysis}
  9295. \label{sec:dataflow-analysis}
  9296. Up until this point the programs generated in
  9297. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9298. \code{while} loop introduces a cycle. But does that matter?
  9299. %
  9300. Indeed it does. Recall that for register allocation, the compiler
  9301. performs liveness analysis to determine which variables can share the
  9302. same register. To accomplish this we analyzed the control-flow graph
  9303. in reverse topological order
  9304. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9305. only well-defined for acyclic graphs.
  9306. Let us return to the example of computing the sum of the first five
  9307. positive integers. Here is the program after instruction selection but
  9308. before register allocation.
  9309. \begin{center}
  9310. {\if\edition\racketEd
  9311. \begin{minipage}{0.45\textwidth}
  9312. \begin{lstlisting}
  9313. (define (main) : Integer
  9314. mainstart:
  9315. movq $0, sum
  9316. movq $5, i
  9317. jmp block5
  9318. block5:
  9319. movq i, tmp3
  9320. cmpq tmp3, $0
  9321. jl block7
  9322. jmp block8
  9323. \end{lstlisting}
  9324. \end{minipage}
  9325. \begin{minipage}{0.45\textwidth}
  9326. \begin{lstlisting}
  9327. block7:
  9328. addq i, sum
  9329. movq $1, tmp4
  9330. negq tmp4
  9331. addq tmp4, i
  9332. jmp block5
  9333. block8:
  9334. movq $27, %rax
  9335. addq sum, %rax
  9336. jmp mainconclusion
  9337. )
  9338. \end{lstlisting}
  9339. \end{minipage}
  9340. \fi}
  9341. {\if\edition\pythonEd
  9342. \begin{minipage}{0.45\textwidth}
  9343. \begin{lstlisting}
  9344. mainstart:
  9345. movq $0, sum
  9346. movq $5, i
  9347. jmp block5
  9348. block5:
  9349. cmpq $0, i
  9350. jg block7
  9351. jmp block8
  9352. \end{lstlisting}
  9353. \end{minipage}
  9354. \begin{minipage}{0.45\textwidth}
  9355. \begin{lstlisting}
  9356. block7:
  9357. addq i, sum
  9358. subq $1, i
  9359. jmp block5
  9360. block8:
  9361. movq sum, %rdi
  9362. callq print_int
  9363. movq $0, %rax
  9364. jmp mainconclusion
  9365. \end{lstlisting}
  9366. \end{minipage}
  9367. \fi}
  9368. \end{center}
  9369. Recall that liveness analysis works backwards, starting at the end
  9370. of each function. For this example we could start with \code{block8}
  9371. because we know what is live at the beginning of the conclusion,
  9372. just \code{rax} and \code{rsp}. So the live-before set
  9373. for \code{block8} is \code{\{rsp,sum\}}.
  9374. %
  9375. Next we might try to analyze \code{block5} or \code{block7}, but
  9376. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9377. we are stuck.
  9378. The way out of this impasse is to realize that we can compute an
  9379. under-approximation of each live-before set by starting with empty
  9380. live-after sets. By \emph{under-approximation}, we mean that the set
  9381. only contains variables that are live for some execution of the
  9382. program, but the set may be missing some variables that are live.
  9383. Next, the under-approximations for each block can be improved by 1)
  9384. updating the live-after set for each block using the approximate
  9385. live-before sets from the other blocks and 2) perform liveness
  9386. analysis again on each block. In fact, by iterating this process, the
  9387. under-approximations eventually become the correct solutions!
  9388. %
  9389. This approach of iteratively analyzing a control-flow graph is
  9390. applicable to many static analysis problems and goes by the name
  9391. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9392. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9393. Washington.
  9394. Let us apply this approach to the above example. We use the empty set
  9395. for the initial live-before set for each block. Let $m_0$ be the
  9396. following mapping from label names to sets of locations (variables and
  9397. registers).
  9398. \begin{center}
  9399. \begin{lstlisting}
  9400. mainstart: {}, block5: {}, block7: {}, block8: {}
  9401. \end{lstlisting}
  9402. \end{center}
  9403. Using the above live-before approximations, we determine the
  9404. live-after for each block and then apply liveness analysis to each
  9405. block. This produces our next approximation $m_1$ of the live-before
  9406. sets.
  9407. \begin{center}
  9408. \begin{lstlisting}
  9409. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9410. \end{lstlisting}
  9411. \end{center}
  9412. For the second round, the live-after for \code{mainstart} is the
  9413. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9414. liveness analysis for \code{mainstart} computes the empty set. The
  9415. live-after for \code{block5} is the union of the live-before sets for
  9416. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9417. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9418. sum\}}. The live-after for \code{block7} is the live-before for
  9419. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9420. So the liveness analysis for \code{block7} remains \code{\{i,
  9421. sum\}}. Together these yield the following approximation $m_2$ of
  9422. the live-before sets.
  9423. \begin{center}
  9424. \begin{lstlisting}
  9425. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9426. \end{lstlisting}
  9427. \end{center}
  9428. In the preceding iteration, only \code{block5} changed, so we can
  9429. limit our attention to \code{mainstart} and \code{block7}, the two
  9430. blocks that jump to \code{block5}. As a result, the live-before sets
  9431. for \code{mainstart} and \code{block7} are updated to include
  9432. \code{rsp}, yielding the following approximation $m_3$.
  9433. \begin{center}
  9434. \begin{lstlisting}
  9435. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9436. \end{lstlisting}
  9437. \end{center}
  9438. Because \code{block7} changed, we analyze \code{block5} once more, but
  9439. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9440. our approximations have converged, so $m_3$ is the solution.
  9441. This iteration process is guaranteed to converge to a solution by the
  9442. Kleene Fixed-Point Theorem, a general theorem about functions on
  9443. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9444. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9445. elements, a least element $\bot$ (pronounced bottom), and a join
  9446. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9447. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9448. working with join semi-lattices.} When two elements are ordered $m_i
  9449. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9450. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9451. approximation than $m_i$. The bottom element $\bot$ represents the
  9452. complete lack of information, i.e., the worst approximation. The join
  9453. operator takes two lattice elements and combines their information,
  9454. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9455. bound}
  9456. A dataflow analysis typically involves two lattices: one lattice to
  9457. represent abstract states and another lattice that aggregates the
  9458. abstract states of all the blocks in the control-flow graph. For
  9459. liveness analysis, an abstract state is a set of locations. We form
  9460. the lattice $L$ by taking its elements to be sets of locations, the
  9461. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9462. set, and the join operator to be set union.
  9463. %
  9464. We form a second lattice $M$ by taking its elements to be mappings
  9465. from the block labels to sets of locations (elements of $L$). We
  9466. order the mappings point-wise, using the ordering of $L$. So given any
  9467. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9468. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9469. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9470. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9471. We can think of one iteration of liveness analysis applied to the
  9472. whole program as being a function $f$ on the lattice $M$. It takes a
  9473. mapping as input and computes a new mapping.
  9474. \[
  9475. f(m_i) = m_{i+1}
  9476. \]
  9477. Next let us think for a moment about what a final solution $m_s$
  9478. should look like. If we perform liveness analysis using the solution
  9479. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9480. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9481. \[
  9482. f(m_s) = m_s
  9483. \]
  9484. Furthermore, the solution should only include locations that are
  9485. forced to be there by performing liveness analysis on the program, so
  9486. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9487. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9488. monotone (better inputs produce better outputs), then the least fixed
  9489. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9490. chain} obtained by starting at $\bot$ and iterating $f$ as
  9491. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9492. \[
  9493. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9494. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9495. \]
  9496. When a lattice contains only finitely-long ascending chains, then
  9497. every Kleene chain tops out at some fixed point after some number of
  9498. iterations of $f$.
  9499. \[
  9500. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9501. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9502. \]
  9503. The liveness analysis is indeed a monotone function and the lattice
  9504. $M$ only has finitely-long ascending chains because there are only a
  9505. finite number of variables and blocks in the program. Thus we are
  9506. guaranteed that iteratively applying liveness analysis to all blocks
  9507. in the program will eventually produce the least fixed point solution.
  9508. Next let us consider dataflow analysis in general and discuss the
  9509. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9510. %
  9511. The algorithm has four parameters: the control-flow graph \code{G}, a
  9512. function \code{transfer} that applies the analysis to one block, the
  9513. \code{bottom} and \code{join} operator for the lattice of abstract
  9514. states. The \code{analyze\_dataflow} function is formulated as a
  9515. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9516. function come from the predecessor nodes in the control-flow
  9517. graph. However, liveness analysis is a \emph{backward} dataflow
  9518. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9519. function with the transpose of the control-flow graph.
  9520. The algorithm begins by creating the bottom mapping, represented by a
  9521. hash table. It then pushes all of the nodes in the control-flow graph
  9522. onto the work list (a queue). The algorithm repeats the \code{while}
  9523. loop as long as there are items in the work list. In each iteration, a
  9524. node is popped from the work list and processed. The \code{input} for
  9525. the node is computed by taking the join of the abstract states of all
  9526. the predecessor nodes. The \code{transfer} function is then applied to
  9527. obtain the \code{output} abstract state. If the output differs from
  9528. the previous state for this block, the mapping for this block is
  9529. updated and its successor nodes are pushed onto the work list.
  9530. \begin{figure}[tb]
  9531. {\if\edition\racketEd
  9532. \begin{lstlisting}
  9533. (define (analyze_dataflow G transfer bottom join)
  9534. (define mapping (make-hash))
  9535. (for ([v (in-vertices G)])
  9536. (dict-set! mapping v bottom))
  9537. (define worklist (make-queue))
  9538. (for ([v (in-vertices G)])
  9539. (enqueue! worklist v))
  9540. (define trans-G (transpose G))
  9541. (while (not (queue-empty? worklist))
  9542. (define node (dequeue! worklist))
  9543. (define input (for/fold ([state bottom])
  9544. ([pred (in-neighbors trans-G node)])
  9545. (join state (dict-ref mapping pred))))
  9546. (define output (transfer node input))
  9547. (cond [(not (equal? output (dict-ref mapping node)))
  9548. (dict-set! mapping node output)
  9549. (for ([v (in-neighbors G node)])
  9550. (enqueue! worklist v))]))
  9551. mapping)
  9552. \end{lstlisting}
  9553. \fi}
  9554. {\if\edition\pythonEd
  9555. \begin{lstlisting}
  9556. def analyze_dataflow(G, transfer, bottom, join):
  9557. trans_G = transpose(G)
  9558. mapping = dict((v, bottom) for v in G.vertices())
  9559. worklist = deque(G.vertices)
  9560. while worklist:
  9561. node = worklist.pop()
  9562. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9563. output = transfer(node, input)
  9564. if output != mapping[node]:
  9565. mapping[node] = output
  9566. worklist.extend(G.adjacent(node))
  9567. \end{lstlisting}
  9568. \fi}
  9569. \caption{Generic work list algorithm for dataflow analysis}
  9570. \label{fig:generic-dataflow}
  9571. \end{figure}
  9572. {\if\edition\racketEd
  9573. \section{Mutable Variables \& Remove Complex Operands}
  9574. There is a subtle interaction between the
  9575. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9576. and the left-to-right order of evaluation of Racket. Consider the
  9577. following example.
  9578. \begin{lstlisting}
  9579. (let ([x 2])
  9580. (+ x (begin (set! x 40) x)))
  9581. \end{lstlisting}
  9582. The result of this program is \code{42} because the first read from
  9583. \code{x} produces \code{2} and the second produces \code{40}. However,
  9584. if we naively apply the \code{remove\_complex\_operands} pass to this
  9585. example we obtain the following program whose result is \code{80}!
  9586. \begin{lstlisting}
  9587. (let ([x 2])
  9588. (let ([tmp (begin (set! x 40) x)])
  9589. (+ x tmp)))
  9590. \end{lstlisting}
  9591. The problem is that, with mutable variables, the ordering between
  9592. reads and writes is important, and the
  9593. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9594. before the first read of \code{x}.
  9595. We recommend solving this problem by giving special treatment to reads
  9596. from mutable variables, that is, variables that occur on the left-hand
  9597. side of a \code{set!}. We mark each read from a mutable variable with
  9598. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9599. that the read operation is effectful in that it can produce different
  9600. results at different points in time. Let's apply this idea to the
  9601. following variation that also involves a variable that is not mutated.
  9602. % loop_test_24.rkt
  9603. \begin{lstlisting}
  9604. (let ([x 2])
  9605. (let ([y 0])
  9606. (+ y (+ x (begin (set! x 40) x)))))
  9607. \end{lstlisting}
  9608. We first analyze the above program to discover that variable \code{x}
  9609. is mutable but \code{y} is not. We then transform the program as
  9610. follows, replacing each occurence of \code{x} with \code{(get! x)}.
  9611. \begin{lstlisting}
  9612. (let ([x 2])
  9613. (let ([y 0])
  9614. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9615. \end{lstlisting}
  9616. Now that we have a clear distinction between reads from mutable and
  9617. immutable variables, we can apply the \code{remove\_complex\_operands}
  9618. pass, where reads from immutable variables are still classified as
  9619. atomic expressions but reads from mutable variables are classified as
  9620. complex. Thus, \code{remove\_complex\_operands} yields the following
  9621. program.\\
  9622. \begin{minipage}{\textwidth}
  9623. \begin{lstlisting}
  9624. (let ([x 2])
  9625. (let ([y 0])
  9626. (+ y (let ([t1 (get! x)])
  9627. (let ([t2 (begin (set! x 40) (get! x))])
  9628. (+ t1 t2))))))
  9629. \end{lstlisting}
  9630. \end{minipage}
  9631. The temporary variable \code{t1} gets the value of \code{x} before the
  9632. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9633. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9634. do not generate a temporary variable for the occurence of \code{y}
  9635. because it's an immutable variable. We want to avoid such unnecessary
  9636. extra temporaries because they would needless increase the number of
  9637. variables, making it more likely for some of them to be spilled. The
  9638. result of this program is \code{42}, the same as the result prior to
  9639. \code{remove\_complex\_operands}.
  9640. The approach that we've sketched above requires only a small
  9641. modification to \code{remove\_complex\_operands} to handle
  9642. \code{get!}. However, it requires a new pass, called
  9643. \code{uncover-get!}, that we discuss in
  9644. Section~\ref{sec:uncover-get-bang}.
  9645. As an aside, this problematic interaction between \code{set!} and the
  9646. pass \code{remove\_complex\_operands} is particular to Racket and not
  9647. its predecessor, the Scheme language. The key difference is that
  9648. Scheme does not specify an order of evaluation for the arguments of an
  9649. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9650. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9651. would be correct results for the example program. Interestingly,
  9652. Racket is implemented on top of the Chez Scheme
  9653. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9654. presented in this section (using extra \code{let} bindings to control
  9655. the order of evaluation) is used in the translation from Racket to
  9656. Scheme~\citep{Flatt:2019tb}.
  9657. \fi} % racket
  9658. Having discussed the complications that arise from adding support for
  9659. assignment and loops, we turn to discussing the individual compilation
  9660. passes.
  9661. {\if\edition\racketEd
  9662. \section{Uncover \texttt{get!}}
  9663. \label{sec:uncover-get-bang}
  9664. The goal of this pass it to mark uses of mutable variables so that
  9665. \code{remove\_complex\_operands} can treat them as complex expressions
  9666. and thereby preserve their ordering relative to the side-effects in
  9667. other operands. So the first step is to collect all the mutable
  9668. variables. We recommend creating an auxilliary function for this,
  9669. named \code{collect-set!}, that recursively traverses expressions,
  9670. returning the set of all variables that occur on the left-hand side of a
  9671. \code{set!}. Here's an exerpt of its implementation.
  9672. \begin{center}
  9673. \begin{minipage}{\textwidth}
  9674. \begin{lstlisting}
  9675. (define (collect-set! e)
  9676. (match e
  9677. [(Var x) (set)]
  9678. [(Int n) (set)]
  9679. [(Let x rhs body)
  9680. (set-union (collect-set! rhs) (collect-set! body))]
  9681. [(SetBang var rhs)
  9682. (set-union (set var) (collect-set! rhs))]
  9683. ...))
  9684. \end{lstlisting}
  9685. \end{minipage}
  9686. \end{center}
  9687. By placing this pass after \code{uniquify}, we need not worry about
  9688. variable shadowing and our logic for \code{Let} can remain simple, as
  9689. in the exerpt above.
  9690. The second step is to mark the occurences of the mutable variables
  9691. with the new \code{GetBang} AST node (\code{get!} in concrete
  9692. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9693. function, which takes two parameters: the set of mutable varaibles
  9694. \code{set!-vars}, and the expression \code{e} to be processed. The
  9695. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9696. mutable variable or leaves it alone if not.
  9697. \begin{center}
  9698. \begin{minipage}{\textwidth}
  9699. \begin{lstlisting}
  9700. (define ((uncover-get!-exp set!-vars) e)
  9701. (match e
  9702. [(Var x)
  9703. (if (set-member? set!-vars x)
  9704. (GetBang x)
  9705. (Var x))]
  9706. ...))
  9707. \end{lstlisting}
  9708. \end{minipage}
  9709. \end{center}
  9710. To wrap things up, define the \code{uncover-get!} function for
  9711. processing a whole program, using \code{collect-set!} to obtain the
  9712. set of mutable variables and then \code{uncover-get!-exp} to replace
  9713. their occurences with \code{GetBang}.
  9714. \fi}
  9715. \section{Remove Complex Operands}
  9716. \label{sec:rco-loop}
  9717. {\if\edition\racketEd
  9718. %
  9719. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9720. \code{while} are all complex expressions. The subexpressions of
  9721. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9722. %
  9723. \fi}
  9724. {\if\edition\pythonEd
  9725. %
  9726. The change needed for this pass is to add a case for the \code{while}
  9727. statement. The condition of a \code{while} loop is allowed to be a
  9728. complex expression, just like the condition of the \code{if}
  9729. statement.
  9730. %
  9731. \fi}
  9732. %
  9733. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9734. \LangLoopANF{} of this pass.
  9735. \newcommand{\LwhileMonadASTRacket}{
  9736. \begin{array}{rcl}
  9737. \Atm &::=& \VOID{} \\
  9738. \Exp &::=& \GETBANG{\Var}
  9739. \MID \SETBANG{\Var}{\Exp}
  9740. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9741. &\MID& \WHILE{\Exp}{\Exp}
  9742. \end{array}
  9743. }
  9744. \newcommand{\LwhileMonadASTPython}{
  9745. \begin{array}{rcl}
  9746. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9747. \end{array}
  9748. }
  9749. \begin{figure}[tp]
  9750. \centering
  9751. \fbox{
  9752. \begin{minipage}{0.96\textwidth}
  9753. \small
  9754. {\if\edition\racketEd
  9755. \[
  9756. \begin{array}{l}
  9757. \gray{\LvarMonadASTRacket} \\
  9758. \gray{\LifMonadASTRacket} \\ \hline
  9759. \LwhileMonadASTRacket \\
  9760. \begin{array}{rcl}
  9761. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9762. \end{array}
  9763. \end{array}
  9764. \]
  9765. \fi}
  9766. {\if\edition\pythonEd
  9767. \[
  9768. \begin{array}{l}
  9769. \gray{\LvarMonadASTPython} \\ \hline
  9770. \gray{\LifMonadASTPython} \\ \hline
  9771. \LwhileMonadASTPython \\
  9772. \begin{array}{rcl}
  9773. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9774. \end{array}
  9775. \end{array}
  9776. %% \begin{array}{rcl}
  9777. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9778. %% \Exp &::=& \Atm \MID \READ{} \\
  9779. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9780. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9781. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9782. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9783. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9784. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9785. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9786. %% \end{array}
  9787. \]
  9788. \fi}
  9789. \end{minipage}
  9790. }
  9791. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9792. \label{fig:Lwhile-anf-syntax}
  9793. \end{figure}
  9794. {\if\edition\racketEd
  9795. %
  9796. As usual, when a complex expression appears in a grammar position that
  9797. needs to be atomic, such as the argument of a primitive operator, we
  9798. must introduce a temporary variable and bind it to the complex
  9799. expression. This approach applies, unchanged, to handle the new
  9800. language forms. For example, in the following code there are two
  9801. \code{begin} expressions appearing as arguments to the \code{+}
  9802. operator. The output of \code{rco\_exp} is shown below, in which the
  9803. \code{begin} expressions have been bound to temporary
  9804. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9805. allowed to have arbitrary expressions in their right-hand-side
  9806. expression, so it is fine to place \code{begin} there.
  9807. %
  9808. \begin{center}
  9809. \begin{tabular}{lcl}
  9810. \begin{minipage}{0.4\textwidth}
  9811. \begin{lstlisting}
  9812. (let ([x2 10])
  9813. (let ([y3 0])
  9814. (+ (+ (begin
  9815. (set! y3 (read))
  9816. (get! x2))
  9817. (begin
  9818. (set! x2 (read))
  9819. (get! y3)))
  9820. (get! x2))))
  9821. \end{lstlisting}
  9822. \end{minipage}
  9823. &
  9824. $\Rightarrow$
  9825. &
  9826. \begin{minipage}{0.4\textwidth}
  9827. \begin{lstlisting}
  9828. (let ([x2 10])
  9829. (let ([y3 0])
  9830. (let ([tmp4 (begin
  9831. (set! y3 (read))
  9832. x2)])
  9833. (let ([tmp5 (begin
  9834. (set! x2 (read))
  9835. y3)])
  9836. (let ([tmp6 (+ tmp4 tmp5)])
  9837. (let ([tmp7 x2])
  9838. (+ tmp6 tmp7)))))))
  9839. \end{lstlisting}
  9840. \end{minipage}
  9841. \end{tabular}
  9842. \end{center}
  9843. \fi}
  9844. \section{Explicate Control \racket{and \LangCLoop{}}}
  9845. \label{sec:explicate-loop}
  9846. \newcommand{\CloopASTRacket}{
  9847. \begin{array}{lcl}
  9848. \Atm &::=& \VOID \\
  9849. \Stmt &::=& \READ{}
  9850. \end{array}
  9851. }
  9852. {\if\edition\racketEd
  9853. Recall that in the \code{explicate\_control} pass we define one helper
  9854. function for each kind of position in the program. For the \LangVar{}
  9855. language of integers and variables we needed assignment and tail
  9856. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9857. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9858. another kind of position: effect position. Except for the last
  9859. subexpression, the subexpressions inside a \code{begin} are evaluated
  9860. only for their effect. Their result values are discarded. We can
  9861. generate better code by taking this fact into account.
  9862. The output language of \code{explicate\_control} is \LangCLoop{}
  9863. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9864. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9865. and that \code{read} may appear as a statement. The most significant
  9866. difference between the programs generated by \code{explicate\_control}
  9867. in Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9868. chapter is that the control-flow graphs of the later may contain
  9869. cycles.
  9870. \begin{figure}[tp]
  9871. \fbox{
  9872. \begin{minipage}{0.96\textwidth}
  9873. \small
  9874. \[
  9875. \begin{array}{l}
  9876. \gray{\CvarASTRacket} \\ \hline
  9877. \gray{\CifASTRacket} \\ \hline
  9878. \CloopASTRacket \\
  9879. \begin{array}{lcl}
  9880. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9881. \end{array}
  9882. \end{array}
  9883. \]
  9884. \end{minipage}
  9885. }
  9886. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9887. \label{fig:c7-syntax}
  9888. \end{figure}
  9889. The new auxiliary function \code{explicate\_effect} takes an
  9890. expression (in an effect position) and the code for its
  9891. continuation. The function returns a $\Tail$ that includes the
  9892. generated code for the input expression followed by the
  9893. continuation. If the expression is obviously pure, that is, never
  9894. causes side effects, then the expression can be removed, so the result
  9895. is just the continuation.
  9896. %
  9897. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  9898. interesting; the generated code is depicted in the following diagram.
  9899. \begin{center}
  9900. \begin{minipage}{0.3\textwidth}
  9901. \xymatrix{
  9902. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  9903. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  9904. & *+[F]{\txt{\itm{cont}}} \\
  9905. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  9906. }
  9907. \end{minipage}
  9908. \end{center}
  9909. We start by creating a fresh label $\itm{loop}$ for the top of the
  9910. loop. Next, recursively process the \itm{body} (in effect position)
  9911. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  9912. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  9913. \itm{body'} as the then-branch and the continuation block as the
  9914. else-branch. The result should be added to the dictionary of
  9915. \code{basic-blocks} with the label \itm{loop}. The result for the
  9916. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  9917. The auxiliary functions for tail, assignment, and predicate positions
  9918. need to be updated. The three new language forms, \code{while},
  9919. \code{set!}, and \code{begin}, can appear in assignment and tail
  9920. positions. Only \code{begin} may appear in predicate positions; the
  9921. other two have result type \code{Void}.
  9922. \fi}
  9923. %
  9924. {\if\edition\pythonEd
  9925. %
  9926. The output of this pass is the language \LangCIf{}. No new language
  9927. features are needed in the output because a \code{while} loop can be
  9928. expressed in terms of \code{goto} and \code{if} statements, which are
  9929. already in \LangCIf{}.
  9930. %
  9931. Add a case for the \code{while} statement to the
  9932. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9933. the condition expression.
  9934. %
  9935. \fi}
  9936. {\if\edition\racketEd
  9937. \section{Select Instructions}
  9938. \label{sec:select-instructions-loop}
  9939. Only three small additions are needed in the
  9940. \code{select\_instructions} pass to handle the changes to
  9941. \LangCLoop{}. That is, a call to
  9942. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9943. stand-alone statement instead of only appearing on the right-hand side
  9944. of an assignment statement. The code generation is nearly identical;
  9945. just leave off the instruction for moving the result into the
  9946. left-hand side.
  9947. \fi}
  9948. \section{Register Allocation}
  9949. \label{sec:register-allocation-loop}
  9950. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9951. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9952. which complicates the liveness analysis needed for register
  9953. allocation.
  9954. \subsection{Liveness Analysis}
  9955. \label{sec:liveness-analysis-r8}
  9956. We recommend using the generic \code{analyze\_dataflow} function that
  9957. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9958. perform liveness analysis, replacing the code in
  9959. \code{uncover\_live} that processed the basic blocks in topological
  9960. order (Section~\ref{sec:liveness-analysis-Lif}).
  9961. The \code{analyze\_dataflow} function has four parameters.
  9962. \begin{enumerate}
  9963. \item The first parameter \code{G} should be a directed graph from the
  9964. \racket{
  9965. \code{racket/graph} package (see the sidebar in
  9966. Section~\ref{sec:build-interference})}
  9967. \python{\code{graph.py} file in the support code}
  9968. that represents the
  9969. control-flow graph.
  9970. \item The second parameter \code{transfer} is a function that applies
  9971. liveness analysis to a basic block. It takes two parameters: the
  9972. label for the block to analyze and the live-after set for that
  9973. block. The transfer function should return the live-before set for
  9974. the block.
  9975. %
  9976. \racket{Also, as a side-effect, it should update the block's
  9977. $\itm{info}$ with the liveness information for each instruction.}
  9978. %
  9979. \python{Also, as a side-effect, it should update the live-before and
  9980. live-after sets for each instruction.}
  9981. %
  9982. To implement the \code{transfer} function, you should be able to
  9983. reuse the code you already have for analyzing basic blocks.
  9984. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9985. \code{bottom} and \code{join} for the lattice of abstract states,
  9986. i.e. sets of locations. The bottom of the lattice is the empty set
  9987. and the join operator is set union.
  9988. \end{enumerate}
  9989. \begin{figure}[p]
  9990. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9991. \node (Lfun) at (0,2) {\large \LangLoop{}};
  9992. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  9993. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  9994. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9995. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9996. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9997. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9998. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9999. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10000. \node (F1-6) at (12,2) {\large \LangLoopANF{}};
  10001. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10002. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10003. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10004. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10005. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10006. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10007. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10008. %% \path[->,bend left=15] (Lfun) edge [above] node
  10009. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10010. \path[->,bend left=15] (Lfun) edge [above] node
  10011. {\ttfamily\footnotesize shrink} (Lfun-2);
  10012. \path[->,bend left=15] (Lfun-2) edge [above] node
  10013. {\ttfamily\footnotesize uniquify} (F1-4);
  10014. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10015. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10016. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10017. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10018. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10019. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10020. %% \path[->,bend right=15] (F1-2) edge [above] node
  10021. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10022. %% \path[->,bend right=15] (F1-3) edge [above] node
  10023. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10024. \path[->,bend left=15] (F1-4) edge [above] node
  10025. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10026. \path[->,bend left=15] (F1-5) edge [above] node
  10027. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10028. \path[->,bend left=15] (F1-6) edge [right] node
  10029. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10030. \path[->,bend left=15] (C3-2) edge [left] node
  10031. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10032. \path[->,bend right=15] (x86-2) edge [left] node
  10033. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10034. \path[->,bend right=15] (x86-2-1) edge [below] node
  10035. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10036. \path[->,bend right=15] (x86-2-2) edge [left] node
  10037. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10038. \path[->,bend left=15] (x86-3) edge [above] node
  10039. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10040. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  10041. \end{tikzpicture}
  10042. \caption{Diagram of the passes for \LangLoop{}.}
  10043. \label{fig:Lwhile-passes}
  10044. \end{figure}
  10045. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10046. for the compilation of \LangLoop{}.
  10047. % Further Reading: dataflow analysis
  10048. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10049. \chapter{Tuples and Garbage Collection}
  10050. \label{ch:Lvec}
  10051. \index{subject}{tuple}
  10052. \index{subject}{vector}
  10053. \index{subject}{allocate}
  10054. \index{subject}{heap allocate}
  10055. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10056. %% all the IR grammars are spelled out! \\ --Jeremy}
  10057. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10058. %% the root stack. \\ --Jeremy}
  10059. In this chapter we study the implementation of
  10060. tuples\racket{, called vectors in Racket}.
  10061. %
  10062. This language feature is the first to use the computer's
  10063. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10064. indefinite, that is, a tuple lives forever from the programmer's
  10065. viewpoint. Of course, from an implementer's viewpoint, it is important
  10066. to reclaim the space associated with a tuple when it is no longer
  10067. needed, which is why we also study \emph{garbage collection}
  10068. \index{garbage collection} techniques in this chapter.
  10069. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10070. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10071. language of Chapter~\ref{ch:Lwhile} with tuples.
  10072. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10073. copying live tuples back and forth between two halves of the heap. The
  10074. garbage collector requires coordination with the compiler so that it
  10075. can find all of the live tuples.
  10076. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10077. discuss the necessary changes and additions to the compiler passes,
  10078. including a new compiler pass named \code{expose\_allocation}.
  10079. \section{The \LangVec{} Language}
  10080. \label{sec:r3}
  10081. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10082. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10083. %
  10084. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10085. creating a tuple, \code{vector-ref} for reading an element of a
  10086. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10087. \code{vector-length} for obtaining the number of elements of a
  10088. tuple.}
  10089. %
  10090. \python{The \LangVec{} language adds 1) tuple creation via a
  10091. comma-separated list of expressions, 2) accessing an element of a
  10092. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10093. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10094. operator, and 4) obtaining the number of elements (the length) of a
  10095. tuple. In this chapter, we restrict access indices to constant
  10096. integers.}
  10097. %
  10098. The program below shows an example use of tuples. It creates a tuple
  10099. \code{t} containing the elements \code{40},
  10100. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10101. contains just \code{2}. The element at index $1$ of \code{t} is
  10102. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10103. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10104. to which we add \code{2}, the element at index $0$ of the tuple. So
  10105. the result of the program is \code{42}.
  10106. %
  10107. {\if\edition\racketEd
  10108. \begin{lstlisting}
  10109. (let ([t (vector 40 #t (vector 2))])
  10110. (if (vector-ref t 1)
  10111. (+ (vector-ref t 0)
  10112. (vector-ref (vector-ref t 2) 0))
  10113. 44))
  10114. \end{lstlisting}
  10115. \fi}
  10116. {\if\edition\pythonEd
  10117. \begin{lstlisting}
  10118. t = 40, True, (2,)
  10119. print( t[0] + t[2][0] if t[1] else 44 )
  10120. \end{lstlisting}
  10121. \fi}
  10122. \newcommand{\LtupGrammarRacket}{
  10123. \begin{array}{lcl}
  10124. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10125. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  10126. \MID \LP\key{vector-length}\;\Exp\RP \\
  10127. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10128. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10129. \end{array}
  10130. }
  10131. \newcommand{\LtupASTRacket}{
  10132. \begin{array}{lcl}
  10133. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10134. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10135. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10136. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10137. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10138. \end{array}
  10139. }
  10140. \newcommand{\LtupGrammarPython}{
  10141. \begin{array}{rcl}
  10142. \itm{cmp} &::= & \key{is} \\
  10143. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10144. \end{array}
  10145. }
  10146. \newcommand{\LtupASTPython}{
  10147. \begin{array}{lcl}
  10148. \itm{cmp} &::= & \code{Is()} \\
  10149. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10150. &\MID& \LEN{\Exp}
  10151. \end{array}
  10152. }
  10153. \begin{figure}[tbp]
  10154. \centering
  10155. \fbox{
  10156. \begin{minipage}{0.96\textwidth}
  10157. {\if\edition\racketEd
  10158. \[
  10159. \begin{array}{l}
  10160. \gray{\LintGrammarRacket{}} \\ \hline
  10161. \gray{\LvarGrammarRacket{}} \\ \hline
  10162. \gray{\LifGrammarRacket{}} \\ \hline
  10163. \gray{\LwhileGrammarRacket} \\ \hline
  10164. \LtupGrammarRacket \\
  10165. \begin{array}{lcl}
  10166. \LangVecM{} &::=& \Exp
  10167. \end{array}
  10168. \end{array}
  10169. \]
  10170. \fi}
  10171. {\if\edition\pythonEd
  10172. \[
  10173. \begin{array}{l}
  10174. \gray{\LintGrammarPython{}} \\ \hline
  10175. \gray{\LvarGrammarPython{}} \\ \hline
  10176. \gray{\LifGrammarPython{}} \\ \hline
  10177. \gray{\LwhileGrammarPython} \\ \hline
  10178. \LtupGrammarPython \\
  10179. \begin{array}{rcl}
  10180. \LangVecM{} &::=& \Stmt^{*}
  10181. \end{array}
  10182. \end{array}
  10183. \]
  10184. \fi}
  10185. \end{minipage}
  10186. }
  10187. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10188. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10189. \label{fig:Lvec-concrete-syntax}
  10190. \end{figure}
  10191. \begin{figure}[tp]
  10192. \centering
  10193. \fbox{
  10194. \begin{minipage}{0.96\textwidth}
  10195. {\if\edition\racketEd
  10196. \[
  10197. \begin{array}{l}
  10198. \gray{\LintOpAST} \\ \hline
  10199. \gray{\LvarASTRacket{}} \\ \hline
  10200. \gray{\LifASTRacket{}} \\ \hline
  10201. \gray{\LwhileASTRacket{}} \\ \hline
  10202. \LtupASTRacket{} \\
  10203. \begin{array}{lcl}
  10204. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10205. \end{array}
  10206. \end{array}
  10207. \]
  10208. \fi}
  10209. {\if\edition\pythonEd
  10210. \[
  10211. \begin{array}{l}
  10212. \gray{\LintASTPython} \\ \hline
  10213. \gray{\LvarASTPython} \\ \hline
  10214. \gray{\LifASTPython} \\ \hline
  10215. \gray{\LwhileASTPython} \\ \hline
  10216. \LtupASTPython \\
  10217. \begin{array}{lcl}
  10218. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10219. \end{array}
  10220. \end{array}
  10221. \]
  10222. \fi}
  10223. \end{minipage}
  10224. }
  10225. \caption{The abstract syntax of \LangVec{}.}
  10226. \label{fig:Lvec-syntax}
  10227. \end{figure}
  10228. Tuples raise several interesting new issues. First, variable binding
  10229. performs a shallow-copy when dealing with tuples, which means that
  10230. different variables can refer to the same tuple, that is, two
  10231. variables can be \emph{aliases}\index{subject}{alias} for the same
  10232. entity. Consider the following example in which both \code{t1} and
  10233. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10234. different tuple value but with equal elements. The result of the
  10235. program is \code{42}.
  10236. \begin{center}
  10237. \begin{minipage}{0.96\textwidth}
  10238. {\if\edition\racketEd
  10239. \begin{lstlisting}
  10240. (let ([t1 (vector 3 7)])
  10241. (let ([t2 t1])
  10242. (let ([t3 (vector 3 7)])
  10243. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10244. 42
  10245. 0))))
  10246. \end{lstlisting}
  10247. \fi}
  10248. {\if\edition\pythonEd
  10249. \begin{lstlisting}
  10250. t1 = 3, 7
  10251. t2 = t1
  10252. t3 = 3, 7
  10253. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10254. \end{lstlisting}
  10255. \fi}
  10256. \end{minipage}
  10257. \end{center}
  10258. {\if\edition\racketEd
  10259. Whether two variables are aliased or not affects what happens
  10260. when the underlying tuple is mutated\index{subject}{mutation}.
  10261. Consider the following example in which \code{t1} and \code{t2}
  10262. again refer to the same tuple value.
  10263. \begin{center}
  10264. \begin{minipage}{0.96\textwidth}
  10265. \begin{lstlisting}
  10266. (let ([t1 (vector 3 7)])
  10267. (let ([t2 t1])
  10268. (let ([_ (vector-set! t2 0 42)])
  10269. (vector-ref t1 0))))
  10270. \end{lstlisting}
  10271. \end{minipage}
  10272. \end{center}
  10273. The mutation through \code{t2} is visible when referencing the tuple
  10274. from \code{t1}, so the result of this program is \code{42}.
  10275. \fi}
  10276. The next issue concerns the lifetime of tuples. When does their
  10277. lifetime end? Notice that \LangVec{} does not include an operation
  10278. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10279. to any notion of static scoping.
  10280. %
  10281. {\if\edition\racketEd
  10282. %
  10283. For example, the following program returns \code{42} even though the
  10284. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10285. that reads from the vector it was bound to.
  10286. \begin{center}
  10287. \begin{minipage}{0.96\textwidth}
  10288. \begin{lstlisting}
  10289. (let ([v (vector (vector 44))])
  10290. (let ([x (let ([w (vector 42)])
  10291. (let ([_ (vector-set! v 0 w)])
  10292. 0))])
  10293. (+ x (vector-ref (vector-ref v 0) 0))))
  10294. \end{lstlisting}
  10295. \end{minipage}
  10296. \end{center}
  10297. \fi}
  10298. %
  10299. {\if\edition\pythonEd
  10300. %
  10301. For example, the following program returns \code{42} even though the
  10302. variable \code{x} goes out of scope when the function returns, prior
  10303. to reading the tuple element at index zero. (We study the compilation
  10304. of functions in Chapter~\ref{ch:Lfun}.)
  10305. %
  10306. \begin{center}
  10307. \begin{minipage}{0.96\textwidth}
  10308. \begin{lstlisting}
  10309. def f():
  10310. x = 42, 43
  10311. return x
  10312. t = f()
  10313. print( t[0] )
  10314. \end{lstlisting}
  10315. \end{minipage}
  10316. \end{center}
  10317. \fi}
  10318. %
  10319. From the perspective of programmer-observable behavior, tuples live
  10320. forever. However, if they really lived forever then many long-running
  10321. programs would run out of memory. To solve this problem, the
  10322. language's runtime system performs automatic garbage collection.
  10323. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10324. \LangVec{} language.
  10325. %
  10326. \racket{We define the \code{vector}, \code{vector-ref},
  10327. \code{vector-set!}, and \code{vector-length} operations for
  10328. \LangVec{} in terms of the corresponding operations in Racket. One
  10329. subtle point is that the \code{vector-set!} operation returns the
  10330. \code{\#<void>} value.}
  10331. %
  10332. \python{We represent tuples with Python lists in the interpreter
  10333. because we need to write to them
  10334. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10335. immutable.) We define element access, the \code{is} operator, and
  10336. the \code{len} operator for \LangVec{} in terms of the corresponding
  10337. operations in Python.}
  10338. \begin{figure}[tbp]
  10339. {\if\edition\racketEd
  10340. \begin{lstlisting}
  10341. (define interp-Lvec-class
  10342. (class interp-Lif-class
  10343. (super-new)
  10344. (define/override (interp-op op)
  10345. (match op
  10346. ['eq? (lambda (v1 v2)
  10347. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10348. (and (boolean? v1) (boolean? v2))
  10349. (and (vector? v1) (vector? v2))
  10350. (and (void? v1) (void? v2)))
  10351. (eq? v1 v2)]))]
  10352. ['vector vector]
  10353. ['vector-length vector-length]
  10354. ['vector-ref vector-ref]
  10355. ['vector-set! vector-set!]
  10356. [else (super interp-op op)]
  10357. ))
  10358. (define/override ((interp-exp env) e)
  10359. (define recur (interp-exp env))
  10360. (match e
  10361. [(HasType e t) (recur e)]
  10362. [(Void) (void)]
  10363. [else ((super interp-exp env) e)]
  10364. ))
  10365. ))
  10366. (define (interp-Lvec p)
  10367. (send (new interp-Lvec-class) interp-program p))
  10368. \end{lstlisting}
  10369. \fi}
  10370. %
  10371. {\if\edition\pythonEd
  10372. \begin{lstlisting}
  10373. class InterpLtup(InterpLwhile):
  10374. def interp_cmp(self, cmp):
  10375. match cmp:
  10376. case Is():
  10377. return lambda x, y: x is y
  10378. case _:
  10379. return super().interp_cmp(cmp)
  10380. def interp_exp(self, e, env):
  10381. match e:
  10382. case Tuple(es, Load()):
  10383. return tuple([self.interp_exp(e, env) for e in es])
  10384. case Subscript(tup, index, Load()):
  10385. t = self.interp_exp(tup, env)
  10386. n = self.interp_exp(index, env)
  10387. return t[n]
  10388. case _:
  10389. return super().interp_exp(e, env)
  10390. \end{lstlisting}
  10391. \fi}
  10392. \caption{Interpreter for the \LangVec{} language.}
  10393. \label{fig:interp-Lvec}
  10394. \end{figure}
  10395. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10396. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10397. we need to know which elements of the tuple are themselves tuples for
  10398. the purposes of garbage collection. We can obtain this information
  10399. during type checking. The type checker in
  10400. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10401. expression, it also
  10402. %
  10403. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10404. where $T$ is the vector's type.
  10405. To create the s-expression for the \code{Vector} type in
  10406. Figure~\ref{fig:type-check-Lvec}, we use the
  10407. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10408. operator} \code{,@} to insert the list \code{t*} without its usual
  10409. start and end parentheses. \index{subject}{unquote-slicing}}
  10410. %
  10411. \python{records the type of each tuple expression in a new field
  10412. named \code{has\_type}. Because the type checker has to compute the type
  10413. of each tuple access, the index must be a constant.}
  10414. \begin{figure}[tp]
  10415. {\if\edition\racketEd
  10416. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10417. (define type-check-Lvec-class
  10418. (class type-check-Lif-class
  10419. (super-new)
  10420. (inherit check-type-equal?)
  10421. (define/override (type-check-exp env)
  10422. (lambda (e)
  10423. (define recur (type-check-exp env))
  10424. (match e
  10425. [(Void) (values (Void) 'Void)]
  10426. [(Prim 'vector es)
  10427. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10428. (define t `(Vector ,@t*))
  10429. (values (HasType (Prim 'vector e*) t) t)]
  10430. [(Prim 'vector-ref (list e1 (Int i)))
  10431. (define-values (e1^ t) (recur e1))
  10432. (match t
  10433. [`(Vector ,ts ...)
  10434. (unless (and (0 . <= . i) (i . < . (length ts)))
  10435. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10436. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10437. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10438. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10439. (define-values (e-vec t-vec) (recur e1))
  10440. (define-values (e-arg^ t-arg) (recur arg))
  10441. (match t-vec
  10442. [`(Vector ,ts ...)
  10443. (unless (and (0 . <= . i) (i . < . (length ts)))
  10444. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10445. (check-type-equal? (list-ref ts i) t-arg e)
  10446. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10447. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10448. [(Prim 'vector-length (list e))
  10449. (define-values (e^ t) (recur e))
  10450. (match t
  10451. [`(Vector ,ts ...)
  10452. (values (Prim 'vector-length (list e^)) 'Integer)]
  10453. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10454. [(Prim 'eq? (list arg1 arg2))
  10455. (define-values (e1 t1) (recur arg1))
  10456. (define-values (e2 t2) (recur arg2))
  10457. (match* (t1 t2)
  10458. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10459. [(other wise) (check-type-equal? t1 t2 e)])
  10460. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10461. [(HasType (Prim 'vector es) t)
  10462. ((type-check-exp env) (Prim 'vector es))]
  10463. [(HasType e1 t)
  10464. (define-values (e1^ t^) (recur e1))
  10465. (check-type-equal? t t^ e)
  10466. (values (HasType e1^ t) t)]
  10467. [else ((super type-check-exp env) e)]
  10468. )))
  10469. ))
  10470. (define (type-check-Lvec p)
  10471. (send (new type-check-Lvec-class) type-check-program p))
  10472. \end{lstlisting}
  10473. \fi}
  10474. {\if\edition\pythonEd
  10475. \begin{lstlisting}
  10476. class TypeCheckLtup(TypeCheckLwhile):
  10477. def type_check_exp(self, e, env):
  10478. match e:
  10479. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10480. l = self.type_check_exp(left, env)
  10481. r = self.type_check_exp(right, env)
  10482. check_type_equal(l, r, e)
  10483. return bool
  10484. case Tuple(es, Load()):
  10485. ts = [self.type_check_exp(e, env) for e in es]
  10486. e.has_type = tuple(ts)
  10487. return e.has_type
  10488. case Subscript(tup, Constant(index), Load()):
  10489. tup_ty = self.type_check_exp(tup, env)
  10490. index_ty = self.type_check_exp(Constant(index), env)
  10491. check_type_equal(index_ty, int, index)
  10492. match tup_ty:
  10493. case tuple(ts):
  10494. return ts[index]
  10495. case _:
  10496. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10497. case _:
  10498. return super().type_check_exp(e, env)
  10499. \end{lstlisting}
  10500. \fi}
  10501. \caption{Type checker for the \LangVec{} language.}
  10502. \label{fig:type-check-Lvec}
  10503. \end{figure}
  10504. \section{Garbage Collection}
  10505. \label{sec:GC}
  10506. Garbage collection is a runtime technique for reclaiming space on the
  10507. heap that will not be used in the future of the running program. We
  10508. use the term \emph{object}\index{subject}{object} to refer to any
  10509. value that is stored in the heap, which for now only includes
  10510. tuples.%
  10511. %
  10512. \footnote{The term ``object'' as used in the context of
  10513. object-oriented programming has a more specific meaning than how we
  10514. are using the term here.}
  10515. %
  10516. Unfortunately, it is impossible to know precisely which objects will
  10517. be accessed in the future and which will not. Instead, garbage
  10518. collectors overapproximate the set of objects that will be accessed by
  10519. identifying which objects can possibly be accessed. The running
  10520. program can directly access objects that are in registers and on the
  10521. procedure call stack. It can also transitively access the elements of
  10522. tuples, starting with a tuple whose address is in a register or on the
  10523. procedure call stack. We define the \emph{root
  10524. set}\index{subject}{root set} to be all the tuple addresses that are
  10525. in registers or on the procedure call stack. We define the \emph{live
  10526. objects}\index{subject}{live objects} to be the objects that are
  10527. reachable from the root set. Garbage collectors reclaim the space that
  10528. is allocated to objects that are no longer live. That means that some
  10529. objects may not get reclaimed as soon as they could be, but at least
  10530. garbage collectors do not reclaim the space dedicated to objects that
  10531. will be accessed in the future! The programmer can influence which
  10532. objects get reclaimed by causing them to become unreachable.
  10533. So the goal of the garbage collector is twofold:
  10534. \begin{enumerate}
  10535. \item preserve all the live objects, and
  10536. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10537. \end{enumerate}
  10538. \subsection{Two-Space Copying Collector}
  10539. Here we study a relatively simple algorithm for garbage collection
  10540. that is the basis of many state-of-the-art garbage
  10541. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10542. particular, we describe a two-space copying
  10543. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10544. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10545. collector} \index{subject}{two-space copying collector}
  10546. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10547. what happens in a two-space collector, showing two time steps, prior
  10548. to garbage collection (on the top) and after garbage collection (on
  10549. the bottom). In a two-space collector, the heap is divided into two
  10550. parts named the FromSpace\index{subject}{FromSpace} and the
  10551. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10552. FromSpace until there is not enough room for the next allocation
  10553. request. At that point, the garbage collector goes to work to room for
  10554. the next allocation.
  10555. A copying collector makes more room by copying all of the live objects
  10556. from the FromSpace into the ToSpace and then performs a sleight of
  10557. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10558. as the new ToSpace. In the example of
  10559. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10560. root set, one in a register and two on the stack. All of the live
  10561. objects have been copied to the ToSpace (the right-hand side of
  10562. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10563. pointer relationships. For example, the pointer in the register still
  10564. points to a tuple that in turn points to two other tuples. There are
  10565. four tuples that are not reachable from the root set and therefore do
  10566. not get copied into the ToSpace.
  10567. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10568. created by a well-typed program in \LangVec{} because it contains a
  10569. cycle. However, creating cycles will be possible once we get to
  10570. \LangDyn{}. We design the garbage collector to deal with cycles to
  10571. begin with so we will not need to revisit this issue.
  10572. \begin{figure}[tbp]
  10573. \centering
  10574. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10575. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10576. \\[5ex]
  10577. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10578. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10579. \caption{A copying collector in action.}
  10580. \label{fig:copying-collector}
  10581. \end{figure}
  10582. \subsection{Graph Copying via Cheney's Algorithm}
  10583. \label{sec:cheney}
  10584. \index{subject}{Cheney's algorithm}
  10585. Let us take a closer look at the copying of the live objects. The
  10586. allocated objects and pointers can be viewed as a graph and we need to
  10587. copy the part of the graph that is reachable from the root set. To
  10588. make sure we copy all of the reachable vertices in the graph, we need
  10589. an exhaustive graph traversal algorithm, such as depth-first search or
  10590. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10591. such algorithms take into account the possibility of cycles by marking
  10592. which vertices have already been visited, so as to ensure termination
  10593. of the algorithm. These search algorithms also use a data structure
  10594. such as a stack or queue as a to-do list to keep track of the vertices
  10595. that need to be visited. We use breadth-first search and a trick
  10596. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10597. and copying tuples into the ToSpace.
  10598. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10599. copy progresses. The queue is represented by a chunk of contiguous
  10600. memory at the beginning of the ToSpace, using two pointers to track
  10601. the front and the back of the queue, called the \emph{free pointer}
  10602. and the \emph{scan pointer} respectively. The algorithm starts by
  10603. copying all tuples that are immediately reachable from the root set
  10604. into the ToSpace to form the initial queue. When we copy a tuple, we
  10605. mark the old tuple to indicate that it has been visited. We discuss
  10606. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10607. that any pointers inside the copied tuples in the queue still point
  10608. back to the FromSpace. Once the initial queue has been created, the
  10609. algorithm enters a loop in which it repeatedly processes the tuple at
  10610. the front of the queue and pops it off the queue. To process a tuple,
  10611. the algorithm copies all the tuple that are directly reachable from it
  10612. to the ToSpace, placing them at the back of the queue. The algorithm
  10613. then updates the pointers in the popped tuple so they point to the
  10614. newly copied tuples.
  10615. \begin{figure}[tbp]
  10616. \centering
  10617. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10618. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10619. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10620. \label{fig:cheney}
  10621. \end{figure}
  10622. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10623. tuple whose second element is $42$ to the back of the queue. The other
  10624. pointer goes to a tuple that has already been copied, so we do not
  10625. need to copy it again, but we do need to update the pointer to the new
  10626. location. This can be accomplished by storing a \emph{forwarding
  10627. pointer}\index{subect}{forwarding pointer} to the new location in the
  10628. old tuple, back when we initially copied the tuple into the
  10629. ToSpace. This completes one step of the algorithm. The algorithm
  10630. continues in this way until the queue is empty, that is, when the scan
  10631. pointer catches up with the free pointer.
  10632. \subsection{Data Representation}
  10633. \label{sec:data-rep-gc}
  10634. The garbage collector places some requirements on the data
  10635. representations used by our compiler. First, the garbage collector
  10636. needs to distinguish between pointers and other kinds of data such as
  10637. integers. There are several ways to accomplish this.
  10638. \begin{enumerate}
  10639. \item Attached a tag to each object that identifies what type of
  10640. object it is~\citep{McCarthy:1960dz}.
  10641. \item Store different types of objects in different
  10642. regions~\citep{Steele:1977ab}.
  10643. \item Use type information from the program to either generate
  10644. type-specific code for collecting or to generate tables that can
  10645. guide the
  10646. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10647. \end{enumerate}
  10648. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10649. need to tag objects anyways, so option 1 is a natural choice for those
  10650. languages. However, \LangVec{} is a statically typed language, so it
  10651. would be unfortunate to require tags on every object, especially small
  10652. and pervasive objects like integers and Booleans. Option 3 is the
  10653. best-performing choice for statically typed languages, but comes with
  10654. a relatively high implementation complexity. To keep this chapter
  10655. within a reasonable time budget, we recommend a combination of options
  10656. 1 and 2, using separate strategies for the stack and the heap.
  10657. Regarding the stack, we recommend using a separate stack for pointers,
  10658. which we call the \emph{root stack}\index{subject}{root stack}
  10659. (a.k.a. ``shadow
  10660. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10661. is, when a local variable needs to be spilled and is of type
  10662. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10663. root stack instead of putting it on the procedure call
  10664. stack. Furthermore, we always spill tuple-typed variables if they are
  10665. live during a call to the collector, thereby ensuring that no pointers
  10666. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10667. reproduces the example from Figure~\ref{fig:copying-collector} and
  10668. contrasts it with the data layout using a root stack. The root stack
  10669. contains the two pointers from the regular stack and also the pointer
  10670. in the second register.
  10671. \begin{figure}[tbp]
  10672. \centering
  10673. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10674. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10675. \caption{Maintaining a root stack to facilitate garbage collection.}
  10676. \label{fig:shadow-stack}
  10677. \end{figure}
  10678. The problem of distinguishing between pointers and other kinds of data
  10679. also arises inside of each tuple on the heap. We solve this problem by
  10680. attaching a tag, an extra 64-bits, to each
  10681. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10682. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10683. that we have drawn the bits in a big-endian way, from right-to-left,
  10684. with bit location 0 (the least significant bit) on the far right,
  10685. which corresponds to the direction of the x86 shifting instructions
  10686. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10687. is dedicated to specifying which elements of the tuple are pointers,
  10688. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10689. indicates there is a pointer and a 0 bit indicates some other kind of
  10690. data. The pointer mask starts at bit location 7. We limit tuples to a
  10691. maximum size of 50 elements, so we just need 50 bits for the pointer
  10692. mask.%
  10693. %
  10694. \footnote{A production-quality compiler would handle
  10695. arbitrary-sized tuples and use a more complex approach.}
  10696. %
  10697. The tag also contains two other pieces of information. The length of
  10698. the tuple (number of elements) is stored in bits location 1 through
  10699. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10700. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10701. has not yet been copied. If the bit has value 0 then the entire tag
  10702. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10703. zero anyways because our tuples are 8-byte aligned.)
  10704. \begin{figure}[tbp]
  10705. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10706. \caption{Representation of tuples in the heap.}
  10707. \label{fig:tuple-rep}
  10708. \end{figure}
  10709. \subsection{Implementation of the Garbage Collector}
  10710. \label{sec:organize-gz}
  10711. \index{subject}{prelude}
  10712. An implementation of the copying collector is provided in the
  10713. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10714. interface to the garbage collector that is used by the compiler. The
  10715. \code{initialize} function creates the FromSpace, ToSpace, and root
  10716. stack and should be called in the prelude of the \code{main}
  10717. function. The arguments of \code{initialize} are the root stack size
  10718. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10719. good choice for both. The \code{initialize} function puts the address
  10720. of the beginning of the FromSpace into the global variable
  10721. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10722. the address that is 1-past the last element of the FromSpace. (We use
  10723. half-open intervals to represent chunks of
  10724. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10725. points to the first element of the root stack.
  10726. As long as there is room left in the FromSpace, your generated code
  10727. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10728. %
  10729. The amount of room left in FromSpace is the difference between the
  10730. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10731. function should be called when there is not enough room left in the
  10732. FromSpace for the next allocation. The \code{collect} function takes
  10733. a pointer to the current top of the root stack (one past the last item
  10734. that was pushed) and the number of bytes that need to be
  10735. allocated. The \code{collect} function performs the copying collection
  10736. and leaves the heap in a state such that the next allocation will
  10737. succeed.
  10738. \begin{figure}[tbp]
  10739. \begin{lstlisting}
  10740. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10741. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10742. int64_t* free_ptr;
  10743. int64_t* fromspace_begin;
  10744. int64_t* fromspace_end;
  10745. int64_t** rootstack_begin;
  10746. \end{lstlisting}
  10747. \caption{The compiler's interface to the garbage collector.}
  10748. \label{fig:gc-header}
  10749. \end{figure}
  10750. %% \begin{exercise}
  10751. %% In the file \code{runtime.c} you will find the implementation of
  10752. %% \code{initialize} and a partial implementation of \code{collect}.
  10753. %% The \code{collect} function calls another function, \code{cheney},
  10754. %% to perform the actual copy, and that function is left to the reader
  10755. %% to implement. The following is the prototype for \code{cheney}.
  10756. %% \begin{lstlisting}
  10757. %% static void cheney(int64_t** rootstack_ptr);
  10758. %% \end{lstlisting}
  10759. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10760. %% rootstack (which is an array of pointers). The \code{cheney} function
  10761. %% also communicates with \code{collect} through the global
  10762. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10763. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10764. %% the ToSpace:
  10765. %% \begin{lstlisting}
  10766. %% static int64_t* tospace_begin;
  10767. %% static int64_t* tospace_end;
  10768. %% \end{lstlisting}
  10769. %% The job of the \code{cheney} function is to copy all the live
  10770. %% objects (reachable from the root stack) into the ToSpace, update
  10771. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10772. %% update the root stack so that it points to the objects in the
  10773. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10774. %% and ToSpace.
  10775. %% \end{exercise}
  10776. The introduction of garbage collection has a non-trivial impact on our
  10777. compiler passes. We introduce a new compiler pass named
  10778. \code{expose\_allocation}. We make significant changes to
  10779. \code{select\_instructions}, \code{build\_interference},
  10780. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10781. make minor changes in several more passes. The following program will
  10782. serve as our running example. It creates two tuples, one nested
  10783. inside the other. Both tuples have length one. The program accesses
  10784. the element in the inner tuple.
  10785. % tests/vectors_test_17.rkt
  10786. {\if\edition\racketEd
  10787. \begin{lstlisting}
  10788. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10789. \end{lstlisting}
  10790. \fi}
  10791. {\if\edition\pythonEd
  10792. \begin{lstlisting}
  10793. print( ((42,),)[0][0] )
  10794. \end{lstlisting}
  10795. \fi}
  10796. {\if\edition\racketEd
  10797. \section{Shrink}
  10798. \label{sec:shrink-Lvec}
  10799. Recall that the \code{shrink} pass translates the primitives operators
  10800. into a smaller set of primitives.
  10801. %
  10802. This pass comes after type checking and the type checker adds a
  10803. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10804. need to add a case for \code{HasType} to the \code{shrink} pass.
  10805. \fi}
  10806. \section{Expose Allocation}
  10807. \label{sec:expose-allocation}
  10808. The pass \code{expose\_allocation} lowers tuple creation into a
  10809. conditional call to the collector followed by allocating the
  10810. appropriate amount of memory and initializing it. We choose to place
  10811. the \code{expose\_allocation} pass before
  10812. \code{remove\_complex\_operands} because the code generated by
  10813. \code{expose\_allocation} contains complex operands.
  10814. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10815. that extends \LangVec{} with new forms that we use in the translation
  10816. of tuple creation.
  10817. %
  10818. {\if\edition\racketEd
  10819. \[
  10820. \begin{array}{lcl}
  10821. \Exp &::=& \cdots
  10822. \MID (\key{collect} \,\itm{int})
  10823. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10824. \MID (\key{global-value} \,\itm{name})
  10825. \end{array}
  10826. \]
  10827. \fi}
  10828. {\if\edition\pythonEd
  10829. \[
  10830. \begin{array}{lcl}
  10831. \Exp &::=& \cdots\\
  10832. &\MID& \key{collect}(\itm{int})
  10833. \MID \key{allocate}(\itm{int},\itm{type})
  10834. \MID \key{global\_value}(\itm{name}) \\
  10835. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10836. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10837. \end{array}
  10838. \]
  10839. \fi}
  10840. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10841. make sure that there are $n$ bytes ready to be allocated. During
  10842. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10843. the \code{collect} function in \code{runtime.c}.
  10844. %
  10845. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10846. space at the front for the 64 bit tag), but the elements are not
  10847. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10848. of the tuple:
  10849. %
  10850. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10851. %
  10852. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10853. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10854. as \code{free\_ptr}.
  10855. %
  10856. \python{The \code{begin} form is an expression that executes a
  10857. sequence of statements and then produces the value of the expression
  10858. at the end.}
  10859. The following shows the transformation of tuple creation into 1) a
  10860. sequence of temporary variables bindings for the initializing
  10861. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10862. \code{allocate}, and 4) the initialization of the tuple. The
  10863. \itm{len} placeholder refers to the length of the tuple and
  10864. \itm{bytes} is how many total bytes need to be allocated for the
  10865. tuple, which is 8 for the tag plus \itm{len} times 8.
  10866. %
  10867. \python{The \itm{type} needed for the second argument of the
  10868. \code{allocate} form can be obtained from the \code{has\_type} field
  10869. of the tuple AST node, which is stored there by running the type
  10870. checker for \LangVec{} immediately before this pass.}
  10871. %
  10872. \begin{center}
  10873. \begin{minipage}{\textwidth}
  10874. {\if\edition\racketEd
  10875. \begin{lstlisting}
  10876. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10877. |$\Longrightarrow$|
  10878. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10879. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10880. (global-value fromspace_end))
  10881. (void)
  10882. (collect |\itm{bytes}|))])
  10883. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10884. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10885. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10886. |$v$|) ... )))) ...)
  10887. \end{lstlisting}
  10888. \fi}
  10889. {\if\edition\pythonEd
  10890. \begin{lstlisting}
  10891. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10892. |$\Longrightarrow$|
  10893. begin:
  10894. |$x_0$| = |$e_0$|
  10895. |$\vdots$|
  10896. |$x_{n-1}$| = |$e_{n-1}$|
  10897. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10898. 0
  10899. else:
  10900. collect(|\itm{bytes}|)
  10901. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10902. |$v$|[0] = |$x_0$|
  10903. |$\vdots$|
  10904. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10905. |$v$|
  10906. \end{lstlisting}
  10907. \fi}
  10908. \end{minipage}
  10909. \end{center}
  10910. %
  10911. \noindent The sequencing of the initializing expressions
  10912. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10913. they may trigger garbage collection and we cannot have an allocated
  10914. but uninitialized tuple on the heap during a collection.
  10915. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10916. \code{expose\_allocation} pass on our running example.
  10917. \begin{figure}[tbp]
  10918. % tests/s2_17.rkt
  10919. {\if\edition\racketEd
  10920. \begin{lstlisting}
  10921. (vector-ref
  10922. (vector-ref
  10923. (let ([vecinit7976
  10924. (let ([vecinit7972 42])
  10925. (let ([collectret7974
  10926. (if (< (+ (global-value free_ptr) 16)
  10927. (global-value fromspace_end))
  10928. (void)
  10929. (collect 16)
  10930. )])
  10931. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10932. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10933. alloc7971))))])
  10934. (let ([collectret7978
  10935. (if (< (+ (global-value free_ptr) 16)
  10936. (global-value fromspace_end))
  10937. (void)
  10938. (collect 16)
  10939. )])
  10940. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10941. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10942. alloc7975))))
  10943. 0)
  10944. 0)
  10945. \end{lstlisting}
  10946. \fi}
  10947. {\if\edition\pythonEd
  10948. \begin{lstlisting}
  10949. print( |$T_1$|[0][0] )
  10950. \end{lstlisting}
  10951. where $T_1$ is
  10952. \begin{lstlisting}
  10953. begin:
  10954. tmp.1 = |$T_2$|
  10955. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10956. 0
  10957. else:
  10958. collect(16)
  10959. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10960. tmp.2[0] = tmp.1
  10961. tmp.2
  10962. \end{lstlisting}
  10963. and $T_2$ is
  10964. \begin{lstlisting}
  10965. begin:
  10966. tmp.3 = 42
  10967. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10968. 0
  10969. else:
  10970. collect(16)
  10971. tmp.4 = allocate(1, TupleType([int]))
  10972. tmp.4[0] = tmp.3
  10973. tmp.4
  10974. \end{lstlisting}
  10975. \fi}
  10976. \caption{Output of the \code{expose\_allocation} pass.}
  10977. \label{fig:expose-alloc-output}
  10978. \end{figure}
  10979. \section{Remove Complex Operands}
  10980. \label{sec:remove-complex-opera-Lvec}
  10981. {\if\edition\racketEd
  10982. %
  10983. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10984. should be treated as complex operands.
  10985. %
  10986. \fi}
  10987. %
  10988. {\if\edition\pythonEd
  10989. %
  10990. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10991. and tuple access should be treated as complex operands. The
  10992. sub-expressions of tuple access must be atomic.
  10993. %
  10994. \fi}
  10995. %% A new case for
  10996. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10997. %% handled carefully to prevent the \code{Prim} node from being separated
  10998. %% from its enclosing \code{HasType}.
  10999. Figure~\ref{fig:Lvec-anf-syntax}
  11000. shows the grammar for the output language \LangAllocANF{} of this
  11001. pass, which is \LangAlloc{} in monadic normal form.
  11002. \newcommand{\LtupMonadASTPython}{
  11003. \begin{array}{rcl}
  11004. \Exp &::=& \GET{\Atm}{\Atm} \\
  11005. &\MID& \LEN{\Atm}\\
  11006. &\MID& \ALLOCATE{\Int}{\Type}
  11007. \MID \GLOBALVALUE{\Var} \\
  11008. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11009. &\MID& \COLLECT{\Int}
  11010. \end{array}
  11011. }
  11012. \begin{figure}[tp]
  11013. \centering
  11014. \fbox{
  11015. \begin{minipage}{0.96\textwidth}
  11016. \small
  11017. {\if\edition\racketEd
  11018. \[
  11019. \begin{array}{rcl}
  11020. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11021. \MID \VOID{} } \\
  11022. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  11023. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  11024. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11025. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  11026. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  11027. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11028. \MID \GLOBALVALUE{\Var}\\
  11029. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  11030. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  11031. \end{array}
  11032. \]
  11033. \fi}
  11034. {\if\edition\pythonEd
  11035. \[
  11036. \begin{array}{l}
  11037. \gray{\LvarMonadASTPython} \\ \hline
  11038. \gray{\LifMonadASTPython} \\ \hline
  11039. \gray{\LwhileMonadASTPython} \\ \hline
  11040. \LtupMonadASTPython \\
  11041. \begin{array}{rcl}
  11042. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11043. \end{array}
  11044. \end{array}
  11045. %% \begin{array}{lcl}
  11046. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  11047. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  11048. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  11049. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  11050. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  11051. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  11052. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  11053. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  11054. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  11055. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  11056. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  11057. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  11058. %% &\MID& \GET{\Atm}{\Atm} \\
  11059. %% &\MID& \LEN{\Exp}\\
  11060. %% &\MID& \ALLOCATE{\Int}{\Type}
  11061. %% \MID \GLOBALVALUE{\Var}\RP\\
  11062. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  11063. %% % why have \LET?
  11064. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  11065. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  11066. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  11067. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  11068. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  11069. %% \MID \COLLECT{\Int} \\
  11070. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11071. %% \end{array}
  11072. \]
  11073. \fi}
  11074. \end{minipage}
  11075. }
  11076. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11077. \label{fig:Lvec-anf-syntax}
  11078. \end{figure}
  11079. \section{Explicate Control and the \LangCVec{} language}
  11080. \label{sec:explicate-control-r3}
  11081. \newcommand{\CtupASTRacket}{
  11082. \begin{array}{lcl}
  11083. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11084. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11085. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11086. &\MID& \VECLEN{\Atm} \\
  11087. &\MID& \GLOBALVALUE{\Var} \\
  11088. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11089. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11090. \end{array}
  11091. }
  11092. \newcommand{\CtupASTPython}{
  11093. \begin{array}{lcl}
  11094. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11095. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11096. \Stmt &::=& \COLLECT{\Int} \\
  11097. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11098. \end{array}
  11099. }
  11100. \begin{figure}[tp]
  11101. \fbox{
  11102. \begin{minipage}{0.96\textwidth}
  11103. \small
  11104. {\if\edition\racketEd
  11105. \[
  11106. \begin{array}{l}
  11107. \gray{\CvarASTRacket} \\ \hline
  11108. \gray{\CifASTRacket} \\ \hline
  11109. \gray{\CloopASTRacket} \\ \hline
  11110. \CtupASTRacket \\
  11111. \begin{array}{lcl}
  11112. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11113. \end{array}
  11114. \end{array}
  11115. \]
  11116. \fi}
  11117. {\if\edition\pythonEd
  11118. \[
  11119. \begin{array}{l}
  11120. \gray{\CifASTPython} \\ \hline
  11121. \CtupASTPython \\
  11122. \begin{array}{lcl}
  11123. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11124. \end{array}
  11125. \end{array}
  11126. \]
  11127. \fi}
  11128. \end{minipage}
  11129. }
  11130. \caption{The abstract syntax of \LangCVec{}, extending
  11131. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11132. (Figure~\ref{fig:c1-syntax})}.}
  11133. \label{fig:c2-syntax}
  11134. \end{figure}
  11135. The output of \code{explicate\_control} is a program in the
  11136. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11137. Figure~\ref{fig:c2-syntax}.
  11138. %
  11139. \racket{(The concrete syntax is defined in
  11140. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11141. %
  11142. The new expressions of \LangCVec{} include \key{allocate},
  11143. %
  11144. \racket{\key{vector-ref}, and \key{vector-set!},}
  11145. %
  11146. \python{accessing tuple elements,}
  11147. %
  11148. and \key{global\_value}.
  11149. %
  11150. \python{\LangCVec{} also includes the \code{collect} statement and
  11151. assignment to a tuple element.}
  11152. %
  11153. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11154. %
  11155. The \code{explicate\_control} pass can treat these new forms much like
  11156. the other forms that we've already encoutered.
  11157. \section{Select Instructions and the \LangXGlobal{} Language}
  11158. \label{sec:select-instructions-gc}
  11159. \index{subject}{instruction selection}
  11160. %% void (rep as zero)
  11161. %% allocate
  11162. %% collect (callq collect)
  11163. %% vector-ref
  11164. %% vector-set!
  11165. %% vector-length
  11166. %% global (postpone)
  11167. In this pass we generate x86 code for most of the new operations that
  11168. were needed to compile tuples, including \code{Allocate},
  11169. \code{Collect}, and accessing tuple elements.
  11170. %
  11171. We compile \code{GlobalValue} to \code{Global} because the later has a
  11172. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11173. \ref{fig:x86-2}). \index{subject}{x86}
  11174. The tuple read and write forms translate into \code{movq}
  11175. instructions. (The plus one in the offset is to get past the tag at
  11176. the beginning of the tuple representation.)
  11177. %
  11178. \begin{center}
  11179. \begin{minipage}{\textwidth}
  11180. {\if\edition\racketEd
  11181. \begin{lstlisting}
  11182. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11183. |$\Longrightarrow$|
  11184. movq |$\itm{tup}'$|, %r11
  11185. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11186. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11187. |$\Longrightarrow$|
  11188. movq |$\itm{tup}'$|, %r11
  11189. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11190. movq $0, |$\itm{lhs'}$|
  11191. \end{lstlisting}
  11192. \fi}
  11193. {\if\edition\pythonEd
  11194. \begin{lstlisting}
  11195. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11196. |$\Longrightarrow$|
  11197. movq |$\itm{tup}'$|, %r11
  11198. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11199. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11200. |$\Longrightarrow$|
  11201. movq |$\itm{tup}'$|, %r11
  11202. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11203. \end{lstlisting}
  11204. \fi}
  11205. \end{minipage}
  11206. \end{center}
  11207. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11208. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11209. are obtained by translating from \LangCVec{} to x86.
  11210. %
  11211. The move of $\itm{tup}'$ to
  11212. register \code{r11} ensures that offset expression
  11213. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11214. removing \code{r11} from consideration by the register allocating.
  11215. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11216. \code{rax}. Then the generated code for tuple assignment would be
  11217. \begin{lstlisting}
  11218. movq |$\itm{tup}'$|, %rax
  11219. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11220. \end{lstlisting}
  11221. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11222. \code{patch\_instructions} would insert a move through \code{rax}
  11223. as follows.
  11224. \begin{lstlisting}
  11225. movq |$\itm{tup}'$|, %rax
  11226. movq |$\itm{rhs}'$|, %rax
  11227. movq %rax, |$8(n+1)$|(%rax)
  11228. \end{lstlisting}
  11229. But the above sequence of instructions does not work because we're
  11230. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11231. $\itm{rhs}'$) at the same time!
  11232. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11233. be translated into a sequence of instructions that read the tag of the
  11234. tuple and extract the six bits that represent the tuple length, which
  11235. are the bits starting at index 1 and going up to and including bit 6.
  11236. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11237. (shift right) can be used to accomplish this.
  11238. We compile the \code{allocate} form to operations on the
  11239. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11240. allocation} as it implements allocation without a function call, by
  11241. simply bumping the allocation pointer. It is much more efficient than
  11242. calling a function for each allocation. The address in the
  11243. \code{free\_ptr} is the next free address in the FromSpace, so we copy
  11244. it into \code{r11} and then move it forward by enough space for the
  11245. tuple being allocated, which is $8(\itm{len}+1)$ bytes because each
  11246. element is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11247. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11248. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11249. tag is organized.
  11250. %
  11251. \racket{We recommend using the Racket operations
  11252. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11253. during compilation.}
  11254. %
  11255. \python{We recommend using the bitwise-or operator \code{|} and the
  11256. shift-left operator \code{<<} to compute the tag during
  11257. compilation.}
  11258. %
  11259. The type annotation in the \code{allocate} form is used to determine
  11260. the pointer mask region of the tag.
  11261. %
  11262. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11263. address of the \code{free\_ptr} global variable but uses a special
  11264. instruction-pointer relative addressing mode of the x86-64 processor.
  11265. In particular, the assembler computes the distance $d$ between the
  11266. address of \code{free\_ptr} and where the \code{rip} would be at that
  11267. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11268. \code{$d$(\%rip)}, which at runtime will compute the address of
  11269. \code{free\_ptr}.
  11270. %
  11271. {\if\edition\racketEd
  11272. \begin{lstlisting}
  11273. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11274. |$\Longrightarrow$|
  11275. movq free_ptr(%rip), %r11
  11276. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11277. movq $|$\itm{tag}$|, 0(%r11)
  11278. movq %r11, |$\itm{lhs}'$|
  11279. \end{lstlisting}
  11280. \fi}
  11281. {\if\edition\pythonEd
  11282. \begin{lstlisting}
  11283. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11284. |$\Longrightarrow$|
  11285. movq free_ptr(%rip), %r11
  11286. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11287. movq $|$\itm{tag}$|, 0(%r11)
  11288. movq %r11, |$\itm{lhs}'$|
  11289. \end{lstlisting}
  11290. \fi}
  11291. The \code{collect} form is compiled to a call to the \code{collect}
  11292. function in the runtime. The arguments to \code{collect} are 1) the
  11293. top of the root stack and 2) the number of bytes that need to be
  11294. allocated. We use another dedicated register, \code{r15}, to
  11295. store the pointer to the top of the root stack. So \code{r15} is not
  11296. available for use by the register allocator.
  11297. {\if\edition\racketEd
  11298. \begin{lstlisting}
  11299. (collect |$\itm{bytes}$|)
  11300. |$\Longrightarrow$|
  11301. movq %r15, %rdi
  11302. movq $|\itm{bytes}|, %rsi
  11303. callq collect
  11304. \end{lstlisting}
  11305. \fi}
  11306. {\if\edition\pythonEd
  11307. \begin{lstlisting}
  11308. collect(|$\itm{bytes}$|)
  11309. |$\Longrightarrow$|
  11310. movq %r15, %rdi
  11311. movq $|\itm{bytes}|, %rsi
  11312. callq collect
  11313. \end{lstlisting}
  11314. \fi}
  11315. \begin{figure}[tp]
  11316. \fbox{
  11317. \begin{minipage}{0.96\textwidth}
  11318. \[
  11319. \begin{array}{lcl}
  11320. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11321. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11322. & & \gray{ \key{main:} \; \Instr^{*} }
  11323. \end{array}
  11324. \]
  11325. \end{minipage}
  11326. }
  11327. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11328. \label{fig:x86-2-concrete}
  11329. \end{figure}
  11330. \begin{figure}[tp]
  11331. \fbox{
  11332. \begin{minipage}{0.96\textwidth}
  11333. \small
  11334. \[
  11335. \begin{array}{lcl}
  11336. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11337. \MID \BYTEREG{\Reg}} \\
  11338. &\MID& \GLOBAL{\Var} \\
  11339. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11340. \end{array}
  11341. \]
  11342. \end{minipage}
  11343. }
  11344. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11345. \label{fig:x86-2}
  11346. \end{figure}
  11347. The concrete and abstract syntax of the \LangXGlobal{} language is
  11348. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11349. differs from \LangXIf{} just in the addition of global variables.
  11350. %
  11351. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11352. \code{select\_instructions} pass on the running example.
  11353. \begin{figure}[tbp]
  11354. \centering
  11355. % tests/s2_17.rkt
  11356. \begin{minipage}[t]{0.5\textwidth}
  11357. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11358. block35:
  11359. movq free_ptr(%rip), alloc9024
  11360. addq $16, free_ptr(%rip)
  11361. movq alloc9024, %r11
  11362. movq $131, 0(%r11)
  11363. movq alloc9024, %r11
  11364. movq vecinit9025, 8(%r11)
  11365. movq $0, initret9026
  11366. movq alloc9024, %r11
  11367. movq 8(%r11), tmp9034
  11368. movq tmp9034, %r11
  11369. movq 8(%r11), %rax
  11370. jmp conclusion
  11371. block36:
  11372. movq $0, collectret9027
  11373. jmp block35
  11374. block38:
  11375. movq free_ptr(%rip), alloc9020
  11376. addq $16, free_ptr(%rip)
  11377. movq alloc9020, %r11
  11378. movq $3, 0(%r11)
  11379. movq alloc9020, %r11
  11380. movq vecinit9021, 8(%r11)
  11381. movq $0, initret9022
  11382. movq alloc9020, vecinit9025
  11383. movq free_ptr(%rip), tmp9031
  11384. movq tmp9031, tmp9032
  11385. addq $16, tmp9032
  11386. movq fromspace_end(%rip), tmp9033
  11387. cmpq tmp9033, tmp9032
  11388. jl block36
  11389. jmp block37
  11390. block37:
  11391. movq %r15, %rdi
  11392. movq $16, %rsi
  11393. callq 'collect
  11394. jmp block35
  11395. block39:
  11396. movq $0, collectret9023
  11397. jmp block38
  11398. \end{lstlisting}
  11399. \end{minipage}
  11400. \begin{minipage}[t]{0.45\textwidth}
  11401. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11402. start:
  11403. movq $42, vecinit9021
  11404. movq free_ptr(%rip), tmp9028
  11405. movq tmp9028, tmp9029
  11406. addq $16, tmp9029
  11407. movq fromspace_end(%rip), tmp9030
  11408. cmpq tmp9030, tmp9029
  11409. jl block39
  11410. jmp block40
  11411. block40:
  11412. movq %r15, %rdi
  11413. movq $16, %rsi
  11414. callq 'collect
  11415. jmp block38
  11416. \end{lstlisting}
  11417. \end{minipage}
  11418. \caption{Output of the \code{select\_instructions} pass.}
  11419. \label{fig:select-instr-output-gc}
  11420. \end{figure}
  11421. \clearpage
  11422. \section{Register Allocation}
  11423. \label{sec:reg-alloc-gc}
  11424. \index{subject}{register allocation}
  11425. As discussed earlier in this chapter, the garbage collector needs to
  11426. access all the pointers in the root set, that is, all variables that
  11427. are tuples. It will be the responsibility of the register allocator
  11428. to make sure that:
  11429. \begin{enumerate}
  11430. \item the root stack is used for spilling tuple-typed variables, and
  11431. \item if a tuple-typed variable is live during a call to the
  11432. collector, it must be spilled to ensure it is visible to the
  11433. collector.
  11434. \end{enumerate}
  11435. The later responsibility can be handled during construction of the
  11436. interference graph, by adding interference edges between the call-live
  11437. tuple-typed variables and all the callee-saved registers. (They
  11438. already interfere with the caller-saved registers.)
  11439. %
  11440. \racket{The type information for variables is in the \code{Program}
  11441. form, so we recommend adding another parameter to the
  11442. \code{build\_interference} function to communicate this alist.}
  11443. %
  11444. \python{The type information for variables is generated by the type
  11445. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11446. the \code{CProgram} AST mode. You'll need to propagate that
  11447. information so that it is available in this pass.}
  11448. The spilling of tuple-typed variables to the root stack can be handled
  11449. after graph coloring, when choosing how to assign the colors
  11450. (integers) to registers and stack locations. The
  11451. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11452. changes to also record the number of spills to the root stack.
  11453. % build-interference
  11454. %
  11455. % callq
  11456. % extra parameter for var->type assoc. list
  11457. % update 'program' and 'if'
  11458. % allocate-registers
  11459. % allocate spilled vectors to the rootstack
  11460. % don't change color-graph
  11461. % TODO:
  11462. %\section{Patch Instructions}
  11463. %[mention that global variables are memory references]
  11464. \section{Prelude and Conclusion}
  11465. \label{sec:print-x86-gc}
  11466. \label{sec:prelude-conclusion-x86-gc}
  11467. \index{subject}{prelude}\index{subject}{conclusion}
  11468. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11469. \code{prelude\_and\_conclusion} pass on the running example. In the
  11470. prelude and conclusion of the \code{main} function, we allocate space
  11471. on the root stack to make room for the spills of tuple-typed
  11472. variables. We do so by bumping the root stack
  11473. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11474. example, there was just one spill so we increment \code{r15} by 8
  11475. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11476. One issue that deserves special care is that there may be a call to
  11477. \code{collect} prior to the initializing assignments for all the
  11478. variables in the root stack. We do not want the garbage collector to
  11479. accidentally think that some uninitialized variable is a pointer that
  11480. needs to be followed. Thus, we zero-out all locations on the root
  11481. stack in the prelude of \code{main}. In
  11482. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11483. %
  11484. \lstinline{movq $0, 0(%r15)}
  11485. %
  11486. is sufficient to accomplish this task because there is only one spill.
  11487. In general, we have to clear as many words as there are spills of
  11488. tuple-typed variables. The garbage collector tests each root to see
  11489. if it is null prior to dereferencing it.
  11490. \begin{figure}[htbp]
  11491. % TODO: Python Version -Jeremy
  11492. \begin{minipage}[t]{0.5\textwidth}
  11493. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11494. block35:
  11495. movq free_ptr(%rip), %rcx
  11496. addq $16, free_ptr(%rip)
  11497. movq %rcx, %r11
  11498. movq $131, 0(%r11)
  11499. movq %rcx, %r11
  11500. movq -8(%r15), %rax
  11501. movq %rax, 8(%r11)
  11502. movq $0, %rdx
  11503. movq %rcx, %r11
  11504. movq 8(%r11), %rcx
  11505. movq %rcx, %r11
  11506. movq 8(%r11), %rax
  11507. jmp conclusion
  11508. block36:
  11509. movq $0, %rcx
  11510. jmp block35
  11511. block38:
  11512. movq free_ptr(%rip), %rcx
  11513. addq $16, free_ptr(%rip)
  11514. movq %rcx, %r11
  11515. movq $3, 0(%r11)
  11516. movq %rcx, %r11
  11517. movq %rbx, 8(%r11)
  11518. movq $0, %rdx
  11519. movq %rcx, -8(%r15)
  11520. movq free_ptr(%rip), %rcx
  11521. addq $16, %rcx
  11522. movq fromspace_end(%rip), %rdx
  11523. cmpq %rdx, %rcx
  11524. jl block36
  11525. movq %r15, %rdi
  11526. movq $16, %rsi
  11527. callq collect
  11528. jmp block35
  11529. block39:
  11530. movq $0, %rcx
  11531. jmp block38
  11532. \end{lstlisting}
  11533. \end{minipage}
  11534. \begin{minipage}[t]{0.45\textwidth}
  11535. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11536. start:
  11537. movq $42, %rbx
  11538. movq free_ptr(%rip), %rdx
  11539. addq $16, %rdx
  11540. movq fromspace_end(%rip), %rcx
  11541. cmpq %rcx, %rdx
  11542. jl block39
  11543. movq %r15, %rdi
  11544. movq $16, %rsi
  11545. callq collect
  11546. jmp block38
  11547. .globl main
  11548. main:
  11549. pushq %rbp
  11550. movq %rsp, %rbp
  11551. pushq %r13
  11552. pushq %r12
  11553. pushq %rbx
  11554. pushq %r14
  11555. subq $0, %rsp
  11556. movq $16384, %rdi
  11557. movq $16384, %rsi
  11558. callq initialize
  11559. movq rootstack_begin(%rip), %r15
  11560. movq $0, 0(%r15)
  11561. addq $8, %r15
  11562. jmp start
  11563. conclusion:
  11564. subq $8, %r15
  11565. addq $0, %rsp
  11566. popq %r14
  11567. popq %rbx
  11568. popq %r12
  11569. popq %r13
  11570. popq %rbp
  11571. retq
  11572. \end{lstlisting}
  11573. \end{minipage}
  11574. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11575. \label{fig:print-x86-output-gc}
  11576. \end{figure}
  11577. \begin{figure}[tbp]
  11578. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11579. \node (Lvec) at (0,2) {\large \LangVec{}};
  11580. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11581. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11582. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11583. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11584. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11585. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11586. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11587. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11588. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11589. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11590. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11591. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11592. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11593. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11594. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11595. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11596. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11597. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11598. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11599. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11600. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11601. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11602. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11603. \end{tikzpicture}
  11604. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11605. \label{fig:Lvec-passes}
  11606. \end{figure}
  11607. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11608. for the compilation of \LangVec{}.
  11609. \clearpage
  11610. {\if\edition\racketEd
  11611. \section{Challenge: Simple Structures}
  11612. \label{sec:simple-structures}
  11613. \index{subject}{struct}
  11614. \index{subject}{structure}
  11615. The language \LangStruct{} extends \LangVec{} with support for simple
  11616. structures. Its concrete syntax is defined in
  11617. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11618. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11619. Racket is a user-defined data type that contains named fields and that
  11620. is heap allocated, similar to a vector. The following is an example of
  11621. a structure definition, in this case the definition of a \code{point}
  11622. type.
  11623. \begin{lstlisting}
  11624. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11625. \end{lstlisting}
  11626. \newcommand{\LstructGrammarRacket}{
  11627. \begin{array}{lcl}
  11628. \Type &::=& \Var \\
  11629. \Exp &::=& (\Var\;\Exp \ldots)\\
  11630. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11631. \end{array}
  11632. }
  11633. \newcommand{\LstructASTRacket}{
  11634. \begin{array}{lcl}
  11635. \Type &::=& \VAR{\Var} \\
  11636. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11637. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11638. \end{array}
  11639. }
  11640. \begin{figure}[tbp]
  11641. \centering
  11642. \fbox{
  11643. \begin{minipage}{0.96\textwidth}
  11644. \[
  11645. \begin{array}{l}
  11646. \gray{\LintGrammarRacket{}} \\ \hline
  11647. \gray{\LvarGrammarRacket{}} \\ \hline
  11648. \gray{\LifGrammarRacket{}} \\ \hline
  11649. \gray{\LwhileGrammarRacket} \\ \hline
  11650. \gray{\LtupGrammarRacket} \\ \hline
  11651. \LstructGrammarRacket \\
  11652. \begin{array}{lcl}
  11653. \LangStruct{} &::=& \Def \ldots \; \Exp
  11654. \end{array}
  11655. \end{array}
  11656. \]
  11657. \end{minipage}
  11658. }
  11659. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11660. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11661. \label{fig:Lstruct-concrete-syntax}
  11662. \end{figure}
  11663. \begin{figure}[tbp]
  11664. \centering
  11665. \fbox{
  11666. \begin{minipage}{0.96\textwidth}
  11667. \[
  11668. \begin{array}{l}
  11669. \gray{\LintASTRacket{}} \\ \hline
  11670. \gray{\LvarASTRacket{}} \\ \hline
  11671. \gray{\LifASTRacket{}} \\ \hline
  11672. \gray{\LwhileASTRacket} \\ \hline
  11673. \gray{\LtupASTRacket} \\ \hline
  11674. \LstructASTRacket \\
  11675. \begin{array}{lcl}
  11676. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11677. \end{array}
  11678. \end{array}
  11679. \]
  11680. \end{minipage}
  11681. }
  11682. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11683. (Figure~\ref{fig:Lvec-syntax}).}
  11684. \label{fig:Lstruct-syntax}
  11685. \end{figure}
  11686. An instance of a structure is created using function call syntax, with
  11687. the name of the structure in the function position:
  11688. \begin{lstlisting}
  11689. (point 7 12)
  11690. \end{lstlisting}
  11691. Function-call syntax is also used to read the value in a field of a
  11692. structure. The function name is formed by the structure name, a dash,
  11693. and the field name. The following example uses \code{point-x} and
  11694. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11695. instances.
  11696. \begin{center}
  11697. \begin{lstlisting}
  11698. (let ([pt1 (point 7 12)])
  11699. (let ([pt2 (point 4 3)])
  11700. (+ (- (point-x pt1) (point-x pt2))
  11701. (- (point-y pt1) (point-y pt2)))))
  11702. \end{lstlisting}
  11703. \end{center}
  11704. Similarly, to write to a field of a structure, use its set function,
  11705. whose name starts with \code{set-}, followed by the structure name,
  11706. then a dash, then the field name, and concluded with an exclamation
  11707. mark. The following example uses \code{set-point-x!} to change the
  11708. \code{x} field from \code{7} to \code{42}.
  11709. \begin{center}
  11710. \begin{lstlisting}
  11711. (let ([pt (point 7 12)])
  11712. (let ([_ (set-point-x! pt 42)])
  11713. (point-x pt)))
  11714. \end{lstlisting}
  11715. \end{center}
  11716. \begin{exercise}\normalfont\normalsize
  11717. Create a type checker for \LangStruct{} by extending the type
  11718. checker for \LangVec{}. Extend your compiler with support for simple
  11719. structures, compiling \LangStruct{} to x86 assembly code. Create
  11720. five new test cases that use structures and test your compiler.
  11721. \end{exercise}
  11722. % TODO: create an interpreter for L_struct
  11723. \clearpage
  11724. \section{Challenge: Arrays}
  11725. \label{sec:arrays}
  11726. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11727. elements whose length is determined at compile-time and where each
  11728. element of a tuple may have a different type (they are
  11729. heterogeous). This challenge is also about sequences, but this time
  11730. the length is determined at run-time and all the elements have the same
  11731. type (they are homogeneous). We use the term ``array'' for this later
  11732. kind of sequence.
  11733. The Racket language does not distinguish between tuples and arrays,
  11734. they are both represented by vectors. However, Typed Racket
  11735. distinguishes between tuples and arrays: the \code{Vector} type is for
  11736. tuples and the \code{Vectorof} type is for arrays.
  11737. %
  11738. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11739. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11740. and the \code{make-vector} primitive operator for creating an array,
  11741. whose arguments are the length of the array and an initial value for
  11742. all the elements in the array. The \code{vector-length},
  11743. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11744. for tuples become overloaded for use with arrays.
  11745. %
  11746. We also include integer multiplication in \LangArray{}, as it is
  11747. useful in many examples involving arrays such as computing the
  11748. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11749. \begin{figure}[tp]
  11750. \centering
  11751. \fbox{
  11752. \begin{minipage}{0.96\textwidth}
  11753. \small
  11754. {\if\edition\racketEd
  11755. \[
  11756. \begin{array}{lcl}
  11757. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11758. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11759. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11760. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11761. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11762. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11763. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11764. \MID \LP\key{not}\;\Exp\RP } \\
  11765. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11766. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11767. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11768. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11769. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11770. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11771. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11772. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11773. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11774. \MID \CWHILE{\Exp}{\Exp} } \\
  11775. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11776. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11777. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11778. \end{array}
  11779. \]
  11780. \fi}
  11781. {\if\edition\pythonEd
  11782. UNDER CONSTRUCTION
  11783. \fi}
  11784. \end{minipage}
  11785. }
  11786. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11787. \label{fig:Lvecof-concrete-syntax}
  11788. \end{figure}
  11789. \begin{figure}[tp]
  11790. \begin{lstlisting}
  11791. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11792. [n : Integer]) : Integer
  11793. (let ([i 0])
  11794. (let ([prod 0])
  11795. (begin
  11796. (while (< i n)
  11797. (begin
  11798. (set! prod (+ prod (* (vector-ref A i)
  11799. (vector-ref B i))))
  11800. (set! i (+ i 1))
  11801. ))
  11802. prod))))
  11803. (let ([A (make-vector 2 2)])
  11804. (let ([B (make-vector 2 3)])
  11805. (+ (inner-product A B 2)
  11806. 30)))
  11807. \end{lstlisting}
  11808. \caption{Example program that computes the inner-product.}
  11809. \label{fig:inner-product}
  11810. \end{figure}
  11811. The type checker for \LangArray{} is define in
  11812. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11813. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11814. of the intializing expression. The length expression is required to
  11815. have type \code{Integer}. The type checking of the operators
  11816. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11817. updated to handle the situation where the vector has type
  11818. \code{Vectorof}. In these cases we translate the operators to their
  11819. \code{vectorof} form so that later passes can easily distinguish
  11820. between operations on tuples versus arrays. We override the
  11821. \code{operator-types} method to provide the type signature for
  11822. multiplication: it takes two integers and returns an integer. To
  11823. support injection and projection of arrays to the \code{Any} type
  11824. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11825. predicate.
  11826. \begin{figure}[tbp]
  11827. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11828. (define type-check-Lvecof-class
  11829. (class type-check-Lwhile-class
  11830. (super-new)
  11831. (inherit check-type-equal?)
  11832. (define/override (flat-ty? ty)
  11833. (match ty
  11834. ['(Vectorof Any) #t]
  11835. [else (super flat-ty? ty)]))
  11836. (define/override (operator-types)
  11837. (append '((* . ((Integer Integer) . Integer)))
  11838. (super operator-types)))
  11839. (define/override (type-check-exp env)
  11840. (lambda (e)
  11841. (define recur (type-check-exp env))
  11842. (match e
  11843. [(Prim 'make-vector (list e1 e2))
  11844. (define-values (e1^ t1) (recur e1))
  11845. (define-values (e2^ elt-type) (recur e2))
  11846. (define vec-type `(Vectorof ,elt-type))
  11847. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11848. vec-type)]
  11849. [(Prim 'vector-ref (list e1 e2))
  11850. (define-values (e1^ t1) (recur e1))
  11851. (define-values (e2^ t2) (recur e2))
  11852. (match* (t1 t2)
  11853. [(`(Vectorof ,elt-type) 'Integer)
  11854. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11855. [(other wise) ((super type-check-exp env) e)])]
  11856. [(Prim 'vector-set! (list e1 e2 e3) )
  11857. (define-values (e-vec t-vec) (recur e1))
  11858. (define-values (e2^ t2) (recur e2))
  11859. (define-values (e-arg^ t-arg) (recur e3))
  11860. (match t-vec
  11861. [`(Vectorof ,elt-type)
  11862. (check-type-equal? elt-type t-arg e)
  11863. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11864. [else ((super type-check-exp env) e)])]
  11865. [(Prim 'vector-length (list e1))
  11866. (define-values (e1^ t1) (recur e1))
  11867. (match t1
  11868. [`(Vectorof ,t)
  11869. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11870. [else ((super type-check-exp env) e)])]
  11871. [else ((super type-check-exp env) e)])))
  11872. ))
  11873. (define (type-check-Lvecof p)
  11874. (send (new type-check-Lvecof-class) type-check-program p))
  11875. \end{lstlisting}
  11876. \caption{Type checker for the \LangArray{} language.}
  11877. \label{fig:type-check-Lvecof}
  11878. \end{figure}
  11879. The interpreter for \LangArray{} is defined in
  11880. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11881. implemented with Racket's \code{make-vector} function and
  11882. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11883. integers.
  11884. \begin{figure}[tbp]
  11885. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11886. (define interp-Lvecof-class
  11887. (class interp-Lwhile-class
  11888. (super-new)
  11889. (define/override (interp-op op)
  11890. (verbose "Lvecof/interp-op" op)
  11891. (match op
  11892. ['make-vector make-vector]
  11893. ['* fx*]
  11894. [else (super interp-op op)]))
  11895. ))
  11896. (define (interp-Lvecof p)
  11897. (send (new interp-Lvecof-class) interp-program p))
  11898. \end{lstlisting}
  11899. \caption{Interpreter for \LangArray{}.}
  11900. \label{fig:interp-Lvecof}
  11901. \end{figure}
  11902. \subsection{Data Representation}
  11903. \label{sec:array-rep}
  11904. Just like tuples, we store arrays on the heap which means that the
  11905. garbage collector will need to inspect arrays. An immediate thought is
  11906. to use the same representation for arrays that we use for tuples.
  11907. However, we limit tuples to a length of $50$ so that their length and
  11908. pointer mask can fit into the 64-bit tag at the beginning of each
  11909. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11910. millions of elements, so we need more bits to store the length.
  11911. However, because arrays are homogeneous, we only need $1$ bit for the
  11912. pointer mask instead of one bit per array elements. Finally, the
  11913. garbage collector will need to be able to distinguish between tuples
  11914. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11915. arrive at the following layout for the 64-bit tag at the beginning of
  11916. an array:
  11917. \begin{itemize}
  11918. \item The right-most bit is the forwarding bit, just like in a tuple.
  11919. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11920. it is not.
  11921. \item The next bit to the left is the pointer mask. A $0$ indicates
  11922. that none of the elements are pointers to the heap and a $1$
  11923. indicates that all of the elements are pointers.
  11924. \item The next $61$ bits store the length of the array.
  11925. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11926. array ($1$).
  11927. \end{itemize}
  11928. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11929. differentiate the kinds of values that have been injected into the
  11930. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11931. to indicate that the value is an array.
  11932. In the following subsections we provide hints regarding how to update
  11933. the passes to handle arrays.
  11934. \subsection{Reveal Casts}
  11935. The array-access operators \code{vectorof-ref} and
  11936. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11937. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11938. that the type checker cannot tell whether the index will be in bounds,
  11939. so the bounds check must be performed at run time. Recall that the
  11940. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11941. an \code{If} arround a vector reference for update to check whether
  11942. the index is less than the length. You should do the same for
  11943. \code{vectorof-ref} and \code{vectorof-set!} .
  11944. In addition, the handling of the \code{any-vector} operators in
  11945. \code{reveal-casts} needs to be updated to account for arrays that are
  11946. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11947. generated code should test whether the tag is for tuples (\code{010})
  11948. or arrays (\code{110}) and then dispatch to either
  11949. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11950. we add a case in \code{select\_instructions} to generate the
  11951. appropriate instructions for accessing the array length from the
  11952. header of an array.
  11953. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11954. the generated code needs to check that the index is less than the
  11955. vector length, so like the code for \code{any-vector-length}, check
  11956. the tag to determine whether to use \code{any-vector-length} or
  11957. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11958. is complete, the generated code can use \code{any-vector-ref} and
  11959. \code{any-vector-set!} for both tuples and arrays because the
  11960. instructions used for those operators do not look at the tag at the
  11961. front of the tuple or array.
  11962. \subsection{Expose Allocation}
  11963. This pass should translate the \code{make-vector} operator into
  11964. lower-level operations. In particular, the new AST node
  11965. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11966. length specified by the $\Exp$, but does not initialize the elements
  11967. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11968. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11969. element type for the array. Regarding the initialization of the array,
  11970. we recommend generated a \code{while} loop that uses
  11971. \code{vector-set!} to put the initializing value into every element of
  11972. the array.
  11973. \subsection{Remove Complex Operands}
  11974. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11975. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11976. complex and its subexpression must be atomic.
  11977. \subsection{Explicate Control}
  11978. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11979. \code{explicate\_assign}.
  11980. \subsection{Select Instructions}
  11981. Generate instructions for \code{AllocateArray} similar to those for
  11982. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11983. that the tag at the front of the array should instead use the
  11984. representation discussed in Section~\ref{sec:array-rep}.
  11985. Regarding \code{vectorof-length}, extract the length from the tag
  11986. according to the representation discussed in
  11987. Section~\ref{sec:array-rep}.
  11988. The instructions generated for \code{vectorof-ref} differ from those
  11989. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11990. that the index is not a constant so the offset must be computed at
  11991. runtime, similar to the instructions generated for
  11992. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11993. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11994. appear in an assignment and as a stand-alone statement, so make sure
  11995. to handle both situations in this pass.
  11996. Finally, the instructions for \code{any-vectorof-length} should be
  11997. similar to those for \code{vectorof-length}, except that one must
  11998. first project the array by writing zeroes into the $3$-bit tag
  11999. \begin{exercise}\normalfont\normalsize
  12000. Implement a compiler for the \LangArray{} language by extending your
  12001. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12002. programs, including the one in Figure~\ref{fig:inner-product} and also
  12003. a program that multiplies two matrices. Note that matrices are
  12004. 2-dimensional arrays, but those can be encoded into 1-dimensional
  12005. arrays by laying out each row in the array, one after the next.
  12006. \end{exercise}
  12007. \section{Challenge: Generational Collection}
  12008. The copying collector described in Section~\ref{sec:GC} can incur
  12009. significant runtime overhead because the call to \code{collect} takes
  12010. time proportional to all of the live data. One way to reduce this
  12011. overhead is to reduce how much data is inspected in each call to
  12012. \code{collect}. In particular, researchers have observed that recently
  12013. allocated data is more likely to become garbage then data that has
  12014. survived one or more previous calls to \code{collect}. This insight
  12015. motivated the creation of \emph{generational garbage collectors}
  12016. \index{subject}{generational garbage collector} that
  12017. 1) segregates data according to its age into two or more generations,
  12018. 2) allocates less space for younger generations, so collecting them is
  12019. faster, and more space for the older generations, and 3) performs
  12020. collection on the younger generations more frequently then for older
  12021. generations~\citep{Wilson:1992fk}.
  12022. For this challenge assignment, the goal is to adapt the copying
  12023. collector implemented in \code{runtime.c} to use two generations, one
  12024. for young data and one for old data. Each generation consists of a
  12025. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12026. \code{collect} function to use the two generations.
  12027. \begin{enumerate}
  12028. \item Copy the young generation's FromSpace to its ToSpace then switch
  12029. the role of the ToSpace and FromSpace
  12030. \item If there is enough space for the requested number of bytes in
  12031. the young FromSpace, then return from \code{collect}.
  12032. \item If there is not enough space in the young FromSpace for the
  12033. requested bytes, then move the data from the young generation to the
  12034. old one with the following steps:
  12035. \begin{enumerate}
  12036. \item If there is enough room in the old FromSpace, copy the young
  12037. FromSpace to the old FromSpace and then return.
  12038. \item If there is not enough room in the old FromSpace, then collect
  12039. the old generation by copying the old FromSpace to the old ToSpace
  12040. and swap the roles of the old FromSpace and ToSpace.
  12041. \item If there is enough room now, copy the young FromSpace to the
  12042. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12043. and ToSpace for the old generation. Copy the young FromSpace and
  12044. the old FromSpace into the larger FromSpace for the old
  12045. generation and then return.
  12046. \end{enumerate}
  12047. \end{enumerate}
  12048. We recommend that you generalize the \code{cheney} function so that it
  12049. can be used for all the copies mentioned above: between the young
  12050. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12051. between the young FromSpace and old FromSpace. This can be
  12052. accomplished by adding parameters to \code{cheney} that replace its
  12053. use of the global variables \code{fromspace\_begin},
  12054. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12055. Note that the collection of the young generation does not traverse the
  12056. old generation. This introduces a potential problem: there may be
  12057. young data that is only reachable through pointers in the old
  12058. generation. If these pointers are not taken into account, the
  12059. collector could throw away young data that is live! One solution,
  12060. called \emph{pointer recording}, is to maintain a set of all the
  12061. pointers from the old generation into the new generation and consider
  12062. this set as part of the root set. To maintain this set, the compiler
  12063. must insert extra instructions around every \code{vector-set!}. If the
  12064. vector being modified is in the old generation, and if the value being
  12065. written is a pointer into the new generation, than that pointer must
  12066. be added to the set. Also, if the value being overwritten was a
  12067. pointer into the new generation, then that pointer should be removed
  12068. from the set.
  12069. \begin{exercise}\normalfont\normalsize
  12070. Adapt the \code{collect} function in \code{runtime.c} to implement
  12071. generational garbage collection, as outlined in this section.
  12072. Update the code generation for \code{vector-set!} to implement
  12073. pointer recording. Make sure that your new compiler and runtime
  12074. passes your test suite.
  12075. \end{exercise}
  12076. \fi}
  12077. \section{Further Reading}
  12078. \citet{Appel90} describes many data representation approaches,
  12079. including the ones used in the compilation of Standard ML.
  12080. There are many alternatives to copying collectors (and their bigger
  12081. siblings, the generational collectors) when its comes to garbage
  12082. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12083. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12084. collectors are that allocation is fast (just a comparison and pointer
  12085. increment), there is no fragmentation, cyclic garbage is collected,
  12086. and the time complexity of collection only depends on the amount of
  12087. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12088. main disadvantages of a two-space copying collector is that it uses a
  12089. lot of extra space and takes a long time to perform the copy, though
  12090. these problems are ameliorated in generational collectors.
  12091. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12092. small objects and generate a lot of garbage, so copying and
  12093. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12094. Garbage collection is an active research topic, especially concurrent
  12095. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12096. developing new techniques and revisiting old
  12097. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12098. meet every year at the International Symposium on Memory Management to
  12099. present these findings.
  12100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12101. \chapter{Functions}
  12102. \label{ch:Lfun}
  12103. \index{subject}{function}
  12104. This chapter studies the compilation of a subset of \racket{Typed
  12105. Racket}\python{Python} in which only top-level function definitions
  12106. are allowed..
  12107. This kind of function is a realistic example as the C language imposes
  12108. similar restrictions. It is also an important stepping stone to
  12109. implementing lexically-scoped functions in the form of \key{lambda}
  12110. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  12111. \section{The \LangFun{} Language}
  12112. The concrete and abstract syntax for function definitions and function
  12113. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12114. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language. Programs in
  12115. \LangFun{} begin with zero or more function definitions. The function
  12116. names from these definitions are in-scope for the entire program,
  12117. including all other function definitions (so the ordering of function
  12118. definitions does not matter).
  12119. %
  12120. \python{The abstract syntax for function parameters in
  12121. Figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12122. consists of a parameter name and its type. This design differs from
  12123. Python's \code{ast} module, which has a more complex structure for
  12124. function parameters to handle keyword parameters,
  12125. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12126. complex Python abstract syntax into the simpler syntax of
  12127. Figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12128. \code{FunctionDef} constructor are for decorators and a type
  12129. comment, neither of which are used by our compiler. We recommend
  12130. replacing them with \code{None} in the \code{shrink} pass.
  12131. }
  12132. %
  12133. The concrete syntax for function application\index{subject}{function
  12134. application} is
  12135. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12136. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12137. where the first expression
  12138. must evaluate to a function and the remaining expressions are the arguments. The
  12139. abstract syntax for function application is
  12140. $\APPLY{\Exp}{\Exp^*}$.
  12141. %% The syntax for function application does not include an explicit
  12142. %% keyword, which is error prone when using \code{match}. To alleviate
  12143. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12144. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12145. Functions are first-class in the sense that a function pointer
  12146. \index{subject}{function pointer} is data and can be stored in memory or passed
  12147. as a parameter to another function. Thus, there is a function
  12148. type, written
  12149. {\if\edition\racketEd
  12150. \begin{lstlisting}
  12151. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12152. \end{lstlisting}
  12153. \fi}
  12154. {\if\edition\pythonEd
  12155. \begin{lstlisting}
  12156. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12157. \end{lstlisting}
  12158. \fi}
  12159. %
  12160. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12161. through $\Type_n$ and whose return type is $\Type_R$. The main
  12162. limitation of these functions (with respect to
  12163. \racket{Racket}\python{Python} functions) is that they are not
  12164. lexically scoped. That is, the only external entities that can be
  12165. referenced from inside a function body are other globally-defined
  12166. functions. The syntax of \LangFun{} prevents function definitions from being
  12167. nested inside each other.
  12168. \newcommand{\LfunGrammarRacket}{
  12169. \begin{array}{lcl}
  12170. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12171. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12172. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12173. \end{array}
  12174. }
  12175. \newcommand{\LfunASTRacket}{
  12176. \begin{array}{lcl}
  12177. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12178. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12179. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12180. \end{array}
  12181. }
  12182. \newcommand{\LfunGrammarPython}{
  12183. \begin{array}{lcl}
  12184. \Type &::=& \key{int}
  12185. \MID \key{bool}
  12186. \MID \key{tuple}\LS \Type^+ \RS
  12187. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12188. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12189. \Stmt &::=& \CRETURN{\Exp} \\
  12190. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12191. \end{array}
  12192. }
  12193. \newcommand{\LfunASTPython}{
  12194. \begin{array}{lcl}
  12195. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12196. \MID \key{TupleType}\LS\Type^+\RS\\
  12197. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12198. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12199. \Stmt &::=& \RETURN{\Exp} \\
  12200. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12201. \\
  12202. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12203. \end{array}
  12204. }
  12205. \begin{figure}[tp]
  12206. \centering
  12207. \fbox{
  12208. \begin{minipage}{0.96\textwidth}
  12209. \small
  12210. {\if\edition\racketEd
  12211. \[
  12212. \begin{array}{l}
  12213. \gray{\LintGrammarRacket{}} \\ \hline
  12214. \gray{\LvarGrammarRacket{}} \\ \hline
  12215. \gray{\LifGrammarRacket{}} \\ \hline
  12216. \gray{\LwhileGrammarRacket} \\ \hline
  12217. \gray{\LtupGrammarRacket} \\ \hline
  12218. \LfunGrammarRacket \\
  12219. \begin{array}{lcl}
  12220. \LangFunM{} &::=& \Def \ldots \; \Exp
  12221. \end{array}
  12222. \end{array}
  12223. \]
  12224. \fi}
  12225. {\if\edition\pythonEd
  12226. \[
  12227. \begin{array}{l}
  12228. \gray{\LintGrammarPython{}} \\ \hline
  12229. \gray{\LvarGrammarPython{}} \\ \hline
  12230. \gray{\LifGrammarPython{}} \\ \hline
  12231. \gray{\LwhileGrammarPython} \\ \hline
  12232. \gray{\LtupGrammarPython} \\ \hline
  12233. \LfunGrammarPython \\
  12234. \begin{array}{rcl}
  12235. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12236. \end{array}
  12237. \end{array}
  12238. \]
  12239. \fi}
  12240. \end{minipage}
  12241. }
  12242. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12243. \label{fig:Lfun-concrete-syntax}
  12244. \end{figure}
  12245. \begin{figure}[tp]
  12246. \centering
  12247. \fbox{
  12248. \begin{minipage}{0.96\textwidth}
  12249. \small
  12250. {\if\edition\racketEd
  12251. \[
  12252. \begin{array}{l}
  12253. \gray{\LintOpAST} \\ \hline
  12254. \gray{\LvarASTRacket{}} \\ \hline
  12255. \gray{\LifASTRacket{}} \\ \hline
  12256. \gray{\LwhileASTRacket{}} \\ \hline
  12257. \gray{\LtupASTRacket{}} \\ \hline
  12258. \LfunASTRacket \\
  12259. \begin{array}{lcl}
  12260. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12261. \end{array}
  12262. \end{array}
  12263. \]
  12264. \fi}
  12265. {\if\edition\pythonEd
  12266. \[
  12267. \begin{array}{l}
  12268. \gray{\LintASTPython{}} \\ \hline
  12269. \gray{\LvarASTPython{}} \\ \hline
  12270. \gray{\LifASTPython{}} \\ \hline
  12271. \gray{\LwhileASTPython} \\ \hline
  12272. \gray{\LtupASTPython} \\ \hline
  12273. \LfunASTPython \\
  12274. \begin{array}{rcl}
  12275. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12276. \end{array}
  12277. \end{array}
  12278. \]
  12279. \fi}
  12280. \end{minipage}
  12281. }
  12282. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12283. \label{fig:Lfun-syntax}
  12284. \end{figure}
  12285. The program in Figure~\ref{fig:Lfun-function-example} is a
  12286. representative example of defining and using functions in \LangFun{}.
  12287. We define a function \code{map} that applies some other function
  12288. \code{f} to both elements of a tuple and returns a new tuple
  12289. containing the results. We also define a function \code{inc}. The
  12290. program applies \code{map} to \code{inc} and
  12291. %
  12292. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12293. %
  12294. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12295. %
  12296. from which we return the \code{42}.
  12297. \begin{figure}[tbp]
  12298. {\if\edition\racketEd
  12299. \begin{lstlisting}
  12300. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12301. : (Vector Integer Integer)
  12302. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12303. (define (inc [x : Integer]) : Integer
  12304. (+ x 1))
  12305. (vector-ref (map inc (vector 0 41)) 1)
  12306. \end{lstlisting}
  12307. \fi}
  12308. {\if\edition\pythonEd
  12309. \begin{lstlisting}
  12310. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12311. return f(v[0]), f(v[1])
  12312. def inc(x : int) -> int:
  12313. return x + 1
  12314. print( map(inc, (0, 41))[1] )
  12315. \end{lstlisting}
  12316. \fi}
  12317. \caption{Example of using functions in \LangFun{}.}
  12318. \label{fig:Lfun-function-example}
  12319. \end{figure}
  12320. The definitional interpreter for \LangFun{} is in
  12321. Figure~\ref{fig:interp-Lfun}. The case for the
  12322. %
  12323. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12324. %
  12325. AST is responsible for setting up the mutual recursion between the
  12326. top-level function definitions.
  12327. %
  12328. \racket{We use the classic back-patching
  12329. \index{subject}{back-patching} approach that uses mutable variables
  12330. and makes two passes over the function
  12331. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12332. top-level environment using a mutable cons cell for each function
  12333. definition. Note that the \code{lambda} value for each function is
  12334. incomplete; it does not yet include the environment. Once the
  12335. top-level environment is constructed, we then iterate over it and
  12336. update the \code{lambda} values to use the top-level environment.}
  12337. %
  12338. \python{We create a dictionary named \code{env} and fill it in
  12339. by mapping each function name to a new \code{Function} value,
  12340. each of which stores a reference to the \code{env}.
  12341. (We define the class \code{Function} for this purpose.)}
  12342. %
  12343. To interpret a function \racket{application}\python{call}, we match
  12344. the result of the function expression to obtain a function value. We
  12345. then extend the function's environment with mapping of parameters to
  12346. argument values. Finally, we interpret the body of the function in
  12347. this extended environment.
  12348. \begin{figure}[tp]
  12349. {\if\edition\racketEd
  12350. \begin{lstlisting}
  12351. (define interp-Lfun-class
  12352. (class interp-Lvec-class
  12353. (super-new)
  12354. (define/override ((interp-exp env) e)
  12355. (define recur (interp-exp env))
  12356. (match e
  12357. [(Var x) (unbox (dict-ref env x))]
  12358. [(Let x e body)
  12359. (define new-env (dict-set env x (box (recur e))))
  12360. ((interp-exp new-env) body)]
  12361. [(Apply fun args)
  12362. (define fun-val (recur fun))
  12363. (define arg-vals (for/list ([e args]) (recur e)))
  12364. (match fun-val
  12365. [`(function (,xs ...) ,body ,fun-env)
  12366. (define params-args (for/list ([x xs] [arg arg-vals])
  12367. (cons x (box arg))))
  12368. (define new-env (append params-args fun-env))
  12369. ((interp-exp new-env) body)]
  12370. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12371. [else ((super interp-exp env) e)]
  12372. ))
  12373. (define/public (interp-def d)
  12374. (match d
  12375. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12376. (cons f (box `(function ,xs ,body ())))]))
  12377. (define/override (interp-program p)
  12378. (match p
  12379. [(ProgramDefsExp info ds body)
  12380. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12381. (for/list ([f (in-dict-values top-level)])
  12382. (set-box! f (match (unbox f)
  12383. [`(function ,xs ,body ())
  12384. `(function ,xs ,body ,top-level)])))
  12385. ((interp-exp top-level) body))]))
  12386. ))
  12387. (define (interp-Lfun p)
  12388. (send (new interp-Lfun-class) interp-program p))
  12389. \end{lstlisting}
  12390. \fi}
  12391. {\if\edition\pythonEd
  12392. \begin{lstlisting}
  12393. class InterpLfun(InterpLtup):
  12394. def apply_fun(self, fun, args, e):
  12395. match fun:
  12396. case Function(name, xs, body, env):
  12397. new_env = env.copy().update(zip(xs, args))
  12398. return self.interp_stmts(body, new_env)
  12399. case _:
  12400. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12401. def interp_exp(self, e, env):
  12402. match e:
  12403. case Call(Name('input_int'), []):
  12404. return super().interp_exp(e, env)
  12405. case Call(func, args):
  12406. f = self.interp_exp(func, env)
  12407. vs = [self.interp_exp(arg, env) for arg in args]
  12408. return self.apply_fun(f, vs, e)
  12409. case _:
  12410. return super().interp_exp(e, env)
  12411. def interp_stmts(self, ss, env):
  12412. if len(ss) == 0:
  12413. return
  12414. match ss[0]:
  12415. case Return(value):
  12416. return self.interp_exp(value, env)
  12417. case FunctionDef(name, params, bod, dl, returns, comment):
  12418. ps = [x for (x,t) in params]
  12419. env[name] = Function(name, ps, bod, env)
  12420. return self.interp_stmts(ss[1:], env)
  12421. case _:
  12422. return super().interp_stmts(ss, env)
  12423. def interp(self, p):
  12424. match p:
  12425. case Module(ss):
  12426. env = {}
  12427. self.interp_stmts(ss, env)
  12428. if 'main' in env.keys():
  12429. self.apply_fun(env['main'], [], None)
  12430. case _:
  12431. raise Exception('interp: unexpected ' + repr(p))
  12432. \end{lstlisting}
  12433. \fi}
  12434. \caption{Interpreter for the \LangFun{} language.}
  12435. \label{fig:interp-Lfun}
  12436. \end{figure}
  12437. %\margincomment{TODO: explain type checker}
  12438. The type checker for \LangFun{} is in
  12439. Figure~\ref{fig:type-check-Lfun}. (We omit the code that parses
  12440. function parameters into the simpler abstract syntax.) Similar to the
  12441. interpreter, the case for the
  12442. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12443. %
  12444. AST is responsible for setting up the mutual recursion between the
  12445. top-level function definitions. We begin by create a mapping
  12446. \code{env} from every function name to its type. We then type check
  12447. the program using this mapping.
  12448. %
  12449. In the case for function \racket{application}\python{call}, we match
  12450. the type of the function expression to a function type and check that
  12451. the types of the argument expressions are equal to the function's
  12452. parameter types. The type of the \racket{application}\python{call} as
  12453. a whole is the return type from the function type.
  12454. \begin{figure}[tp]
  12455. {\if\edition\racketEd
  12456. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12457. (define type-check-Lfun-class
  12458. (class type-check-Lvec-class
  12459. (super-new)
  12460. (inherit check-type-equal?)
  12461. (define/public (type-check-apply env e es)
  12462. (define-values (e^ ty) ((type-check-exp env) e))
  12463. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12464. ((type-check-exp env) e)))
  12465. (match ty
  12466. [`(,ty^* ... -> ,rt)
  12467. (for ([arg-ty ty*] [param-ty ty^*])
  12468. (check-type-equal? arg-ty param-ty (Apply e es)))
  12469. (values e^ e* rt)]))
  12470. (define/override (type-check-exp env)
  12471. (lambda (e)
  12472. (match e
  12473. [(FunRef f n)
  12474. (values (FunRef f n) (dict-ref env f))]
  12475. [(Apply e es)
  12476. (define-values (e^ es^ rt) (type-check-apply env e es))
  12477. (values (Apply e^ es^) rt)]
  12478. [(Call e es)
  12479. (define-values (e^ es^ rt) (type-check-apply env e es))
  12480. (values (Call e^ es^) rt)]
  12481. [else ((super type-check-exp env) e)])))
  12482. (define/public (type-check-def env)
  12483. (lambda (e)
  12484. (match e
  12485. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12486. (define new-env (append (map cons xs ps) env))
  12487. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12488. (check-type-equal? ty^ rt body)
  12489. (Def f p:t* rt info body^)])))
  12490. (define/public (fun-def-type d)
  12491. (match d
  12492. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12493. (define/override (type-check-program e)
  12494. (match e
  12495. [(ProgramDefsExp info ds body)
  12496. (define env (for/list ([d ds])
  12497. (cons (Def-name d) (fun-def-type d))))
  12498. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12499. (define-values (body^ ty) ((type-check-exp env) body))
  12500. (check-type-equal? ty 'Integer body)
  12501. (ProgramDefsExp info ds^ body^)]))))
  12502. (define (type-check-Lfun p)
  12503. (send (new type-check-Lfun-class) type-check-program p))
  12504. \end{lstlisting}
  12505. \fi}
  12506. {\if\edition\pythonEd
  12507. \begin{lstlisting}
  12508. class TypeCheckLfun(TypeCheckLtup):
  12509. def type_check_exp(self, e, env):
  12510. match e:
  12511. case Call(Name('input_int'), []):
  12512. return super().type_check_exp(e, env)
  12513. case Call(func, args):
  12514. func_t = self.type_check_exp(func, env)
  12515. args_t = [self.type_check_exp(arg, env) for arg in args]
  12516. match func_t:
  12517. case FunctionType(params_t, return_t):
  12518. for (arg_t, param_t) in zip(args_t, params_t):
  12519. check_type_equal(param_t, arg_t, e)
  12520. return return_t
  12521. case _:
  12522. raise Exception('type_check_exp: in call, unexpected ' +
  12523. repr(func_t))
  12524. case _:
  12525. return super().type_check_exp(e, env)
  12526. def type_check_stmts(self, ss, env):
  12527. if len(ss) == 0:
  12528. return
  12529. match ss[0]:
  12530. case FunctionDef(name, params, body, dl, returns, comment):
  12531. new_env = env.copy().update(params)
  12532. rt = self.type_check_stmts(body, new_env)
  12533. check_type_equal(returns, rt, ss[0])
  12534. return self.type_check_stmts(ss[1:], env)
  12535. case Return(value):
  12536. return self.type_check_exp(value, env)
  12537. case _:
  12538. return super().type_check_stmts(ss, env)
  12539. def type_check(self, p):
  12540. match p:
  12541. case Module(body):
  12542. env = {}
  12543. for s in body:
  12544. match s:
  12545. case FunctionDef(name, params, bod, dl, returns, comment):
  12546. if name in env:
  12547. raise Exception('type_check: function ' +
  12548. repr(name) + ' defined twice')
  12549. params_t = [t for (x,t) in params]
  12550. env[name] = FunctionType(params_t, returns)
  12551. self.type_check_stmts(body, env)
  12552. case _:
  12553. raise Exception('type_check: unexpected ' + repr(p))
  12554. \end{lstlisting}
  12555. \fi}
  12556. \caption{Type checker for the \LangFun{} language.}
  12557. \label{fig:type-check-Lfun}
  12558. \end{figure}
  12559. \clearpage
  12560. \section{Functions in x86}
  12561. \label{sec:fun-x86}
  12562. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12563. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12564. %% \margincomment{\tiny Talk about the return address on the
  12565. %% stack and what callq and retq does.\\ --Jeremy }
  12566. The x86 architecture provides a few features to support the
  12567. implementation of functions. We have already seen that there are
  12568. labels in x86 so that one can refer to the location of an instruction,
  12569. as is needed for jump instructions. Labels can also be used to mark
  12570. the beginning of the instructions for a function. Going further, we
  12571. can obtain the address of a label by using the \key{leaq} instruction
  12572. and instruction-pointer relative addressing. For example, the
  12573. following puts the address of the \code{inc} label into the \code{rbx}
  12574. register.
  12575. \begin{lstlisting}
  12576. leaq inc(%rip), %rbx
  12577. \end{lstlisting}
  12578. Recall from Section~\ref{sec:select-instructions-gc} that
  12579. \verb!inc(%rip)! is an example of instruction-pointer relative
  12580. addressing. It computes the address of \code{inc}.
  12581. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12582. to functions whose locations were given by a label, such as
  12583. \code{read\_int}. To support function calls in this chapter we instead
  12584. will be jumping to functions whose location are given by an address in
  12585. a register, that is, we need to make an \emph{indirect function
  12586. call}. The x86 syntax for this is a \code{callq} instruction but with
  12587. an asterisk before the register name.\index{subject}{indirect function
  12588. call}
  12589. \begin{lstlisting}
  12590. callq *%rbx
  12591. \end{lstlisting}
  12592. \subsection{Calling Conventions}
  12593. \index{subject}{calling conventions}
  12594. The \code{callq} instruction provides partial support for implementing
  12595. functions: it pushes the return address on the stack and it jumps to
  12596. the target. However, \code{callq} does not handle
  12597. \begin{enumerate}
  12598. \item parameter passing,
  12599. \item pushing frames on the procedure call stack and popping them off,
  12600. or
  12601. \item determining how registers are shared by different functions.
  12602. \end{enumerate}
  12603. Regarding (1) parameter passing, recall that the x86-64 calling convention
  12604. for Unix-based system uses the following six
  12605. registers to pass arguments to a function, in this order.
  12606. \begin{lstlisting}
  12607. rdi rsi rdx rcx r8 r9
  12608. \end{lstlisting}
  12609. If there are
  12610. more than six arguments, then the calling convention mandates to use space on the
  12611. frame of the caller for the rest of the arguments. However, to ease
  12612. the implementation of efficient tail calls
  12613. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12614. arguments.
  12615. %
  12616. Also recall that the register \code{rax} is for the return value of
  12617. the function.
  12618. \index{subject}{prelude}\index{subject}{conclusion}
  12619. Regarding (2) frames \index{subject}{frame} and the procedure call
  12620. stack, \index{subject}{procedure call stack} recall from
  12621. Section~\ref{sec:x86} that the stack grows down and each function call
  12622. uses a chunk of space on the stack called a frame. The caller sets the
  12623. stack pointer, register \code{rsp}, to the last data item in its
  12624. frame. The callee must not change anything in the caller's frame, that
  12625. is, anything that is at or above the stack pointer. The callee is free
  12626. to use locations that are below the stack pointer.
  12627. Recall that we are storing variables of tuple type on the root stack.
  12628. So the prelude needs to move the root stack pointer \code{r15} up
  12629. according to the number of variables of tuple type and
  12630. the conclusion needs to move the root stack pointer back down. Also,
  12631. the prelude must initialize to \code{0} this frame's slots in the root
  12632. stack to signal to the garbage collector that those slots do not yet
  12633. contain a pointer to a vector. Otherwise the garbage collector will
  12634. interpret the garbage bits in those slots as memory addresses and try
  12635. to traverse them, causing serious mayhem!
  12636. Regarding (3) the sharing of registers between different functions,
  12637. recall from Section~\ref{sec:calling-conventions} that the registers
  12638. are divided into two groups, the caller-saved registers and the
  12639. callee-saved registers. The caller should assume that all the
  12640. caller-saved registers get overwritten with arbitrary values by the
  12641. callee. For that reason we recommend in
  12642. Section~\ref{sec:calling-conventions} that variables that are live
  12643. during a function call should not be assigned to caller-saved
  12644. registers.
  12645. On the flip side, if the callee wants to use a callee-saved register,
  12646. the callee must save the contents of those registers on their stack
  12647. frame and then put them back prior to returning to the caller. For
  12648. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12649. the register allocator assigns a variable to a callee-saved register,
  12650. then the prelude of the \code{main} function must save that register
  12651. to the stack and the conclusion of \code{main} must restore it. This
  12652. recommendation now generalizes to all functions.
  12653. Recall that the base pointer, register \code{rbp}, is used as a
  12654. point-of-reference within a frame, so that each local variable can be
  12655. accessed at a fixed offset from the base pointer
  12656. (Section~\ref{sec:x86}).
  12657. %
  12658. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12659. and callee frames.
  12660. \begin{figure}[tbp]
  12661. \centering
  12662. \begin{tabular}{r|r|l|l} \hline
  12663. Caller View & Callee View & Contents & Frame \\ \hline
  12664. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12665. 0(\key{\%rbp}) & & old \key{rbp} \\
  12666. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12667. \ldots & & \ldots \\
  12668. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12669. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12670. \ldots & & \ldots \\
  12671. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12672. %% & & \\
  12673. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12674. %% & \ldots & \ldots \\
  12675. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12676. \hline
  12677. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12678. & 0(\key{\%rbp}) & old \key{rbp} \\
  12679. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12680. & \ldots & \ldots \\
  12681. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12682. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12683. & \ldots & \ldots \\
  12684. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12685. \end{tabular}
  12686. \caption{Memory layout of caller and callee frames.}
  12687. \label{fig:call-frames}
  12688. \end{figure}
  12689. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12690. %% local variables and for storing the values of callee-saved registers
  12691. %% (we shall refer to all of these collectively as ``locals''), and that
  12692. %% at the beginning of a function we move the stack pointer \code{rsp}
  12693. %% down to make room for them.
  12694. %% We recommend storing the local variables
  12695. %% first and then the callee-saved registers, so that the local variables
  12696. %% can be accessed using \code{rbp} the same as before the addition of
  12697. %% functions.
  12698. %% To make additional room for passing arguments, we shall
  12699. %% move the stack pointer even further down. We count how many stack
  12700. %% arguments are needed for each function call that occurs inside the
  12701. %% body of the function and find their maximum. Adding this number to the
  12702. %% number of locals gives us how much the \code{rsp} should be moved at
  12703. %% the beginning of the function. In preparation for a function call, we
  12704. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12705. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12706. %% so on.
  12707. %% Upon calling the function, the stack arguments are retrieved by the
  12708. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12709. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12710. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12711. %% the layout of the caller and callee frames. Notice how important it is
  12712. %% that we correctly compute the maximum number of arguments needed for
  12713. %% function calls; if that number is too small then the arguments and
  12714. %% local variables will smash into each other!
  12715. \subsection{Efficient Tail Calls}
  12716. \label{sec:tail-call}
  12717. In general, the amount of stack space used by a program is determined
  12718. by the longest chain of nested function calls. That is, if function
  12719. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12720. of stack space is linear in $n$. The depth $n$ can grow quite large
  12721. if functions are (mutually) recursive. However, in
  12722. some cases we can arrange to use only a constant amount of space for a
  12723. long chain of nested function calls.
  12724. A \emph{tail call}\index{subject}{tail call} is a function call that
  12725. happens as the last action in a function body.
  12726. For example, in the following
  12727. program, the recursive call to \code{tail\_sum} is a tail call.
  12728. \begin{center}
  12729. {\if\edition\racketEd
  12730. \begin{lstlisting}
  12731. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12732. (if (eq? n 0)
  12733. r
  12734. (tail_sum (- n 1) (+ n r))))
  12735. (+ (tail_sum 3 0) 36)
  12736. \end{lstlisting}
  12737. \fi}
  12738. {\if\edition\pythonEd
  12739. \begin{lstlisting}
  12740. def tail_sum(n : int, r : int) -> int:
  12741. if n == 0:
  12742. return r
  12743. else:
  12744. return tail_sum(n - 1, n + r)
  12745. print( tail_sum(3, 0) + 36)
  12746. \end{lstlisting}
  12747. \fi}
  12748. \end{center}
  12749. At a tail call, the frame of the caller is no longer needed, so we can
  12750. pop the caller's frame before making the tail call. With this
  12751. approach, a recursive function that only makes tail calls ends up
  12752. using a constant amount of stack space. Functional languages like
  12753. Racket rely heavily on recursive functions, so the definition of
  12754. Racket \emph{requires} that all tail calls be optimized in this way.
  12755. \index{subject}{frame}
  12756. Some care is needed with regards to argument passing in tail calls.
  12757. As mentioned above, for arguments beyond the sixth, the convention is
  12758. to use space in the caller's frame for passing arguments. But for a
  12759. tail call we pop the caller's frame and can no longer use it. An
  12760. alternative is to use space in the callee's frame for passing
  12761. arguments. However, this option is also problematic because the caller
  12762. and callee's frames overlap in memory. As we begin to copy the
  12763. arguments from their sources in the caller's frame, the target
  12764. locations in the callee's frame might collide with the sources for
  12765. later arguments! We solve this problem by using the heap instead of
  12766. the stack for passing more than six arguments, which we describe in
  12767. the Section~\ref{sec:limit-functions-r4}.
  12768. As mentioned above, for a tail call we pop the caller's frame prior to
  12769. making the tail call. The instructions for popping a frame are the
  12770. instructions that we usually place in the conclusion of a
  12771. function. Thus, we also need to place such code immediately before
  12772. each tail call. These instructions include restoring the callee-saved
  12773. registers, so it is fortunate that the argument passing registers are
  12774. all caller-saved registers!
  12775. One last note regarding which instruction to use to make the tail
  12776. call. When the callee is finished, it should not return to the current
  12777. function, but it should return to the function that called the current
  12778. one. Thus, the return address that is already on the stack is the
  12779. right one, and we should not use \key{callq} to make the tail call, as
  12780. that would unnecessarily overwrite the return address. Instead we can
  12781. simply use the \key{jmp} instruction. Like the indirect function call,
  12782. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12783. register prefixed with an asterisk. We recommend using \code{rax} to
  12784. hold the jump target because the preceding conclusion can overwrite
  12785. just about everything else.
  12786. \begin{lstlisting}
  12787. jmp *%rax
  12788. \end{lstlisting}
  12789. \section{Shrink \LangFun{}}
  12790. \label{sec:shrink-r4}
  12791. The \code{shrink} pass performs a minor modification to ease the
  12792. later passes. This pass introduces an explicit \code{main} function
  12793. that gobbles up all the top-level statements of the module.
  12794. %
  12795. \racket{It also changes the top \code{ProgramDefsExp} form to
  12796. \code{ProgramDefs}.}
  12797. {\if\edition\racketEd
  12798. \begin{lstlisting}
  12799. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12800. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12801. \end{lstlisting}
  12802. where $\itm{mainDef}$ is
  12803. \begin{lstlisting}
  12804. (Def 'main '() 'Integer '() |$\Exp'$|)
  12805. \end{lstlisting}
  12806. \fi}
  12807. {\if\edition\pythonEd
  12808. \begin{lstlisting}
  12809. Module(|$\Def\ldots\Stmt\ldots$|)
  12810. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12811. \end{lstlisting}
  12812. where $\itm{mainDef}$ is
  12813. \begin{lstlisting}
  12814. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12815. \end{lstlisting}
  12816. \fi}
  12817. \section{Reveal Functions and the \LangFunRef{} language}
  12818. \label{sec:reveal-functions-r4}
  12819. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12820. in that it conflates the use of function names and local
  12821. variables. This is a problem because we need to compile the use of a
  12822. function name differently than the use of a local variable; we need to
  12823. use \code{leaq} to convert the function name (a label in x86) to an
  12824. address in a register. Thus, we create a new pass that changes
  12825. function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where $n$ is the
  12826. arity of the function.\python{\footnote{The arity is not needed in this
  12827. chapter but is used in Chapter~\ref{ch:Ldyn}.}} This pass is
  12828. named \code{reveal\_functions} and the output language, \LangFunRef{},
  12829. is defined in Figure~\ref{fig:f1-syntax}.
  12830. %% The concrete syntax for a
  12831. %% function reference is $\CFUNREF{f}$.
  12832. \begin{figure}[tp]
  12833. \centering
  12834. \fbox{
  12835. \begin{minipage}{0.96\textwidth}
  12836. {\if\edition\racketEd
  12837. \[
  12838. \begin{array}{lcl}
  12839. \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12840. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12841. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12842. \end{array}
  12843. \]
  12844. \fi}
  12845. {\if\edition\pythonEd
  12846. \[
  12847. \begin{array}{lcl}
  12848. \Exp &::=& \FUNREF{\Var}{\Int}\\
  12849. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12850. \end{array}
  12851. \]
  12852. \fi}
  12853. \end{minipage}
  12854. }
  12855. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12856. (Figure~\ref{fig:Lfun-syntax}).}
  12857. \label{fig:f1-syntax}
  12858. \end{figure}
  12859. %% Distinguishing between calls in tail position and non-tail position
  12860. %% requires the pass to have some notion of context. We recommend using
  12861. %% two mutually recursive functions, one for processing expressions in
  12862. %% tail position and another for the rest.
  12863. \racket{Placing this pass after \code{uniquify} will make sure that
  12864. there are no local variables and functions that share the same
  12865. name.}
  12866. %
  12867. The \code{reveal\_functions} pass should come before the
  12868. \code{remove\_complex\_operands} pass because function references
  12869. should be categorized as complex expressions.
  12870. \section{Limit Functions}
  12871. \label{sec:limit-functions-r4}
  12872. Recall that we wish to limit the number of function parameters to six
  12873. so that we do not need to use the stack for argument passing, which
  12874. makes it easier to implement efficient tail calls. However, because
  12875. the input language \LangFun{} supports arbitrary numbers of function
  12876. arguments, we have some work to do!
  12877. This pass transforms functions and function calls that involve more
  12878. than six arguments to pass the first five arguments as usual, but it
  12879. packs the rest of the arguments into a vector and passes it as the
  12880. sixth argument.
  12881. Each function definition with seven or more parameters is transformed as
  12882. follows.
  12883. {\if\edition\racketEd
  12884. \begin{lstlisting}
  12885. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12886. |$\Rightarrow$|
  12887. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12888. \end{lstlisting}
  12889. \fi}
  12890. {\if\edition\pythonEd
  12891. \begin{lstlisting}
  12892. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12893. |$\Rightarrow$|
  12894. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12895. |$T_r$|, None, |$\itm{body}'$|, None)
  12896. \end{lstlisting}
  12897. \fi}
  12898. %
  12899. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12900. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12901. the $k$th element of the tuple, where $k = i - 6$.
  12902. %
  12903. {\if\edition\racketEd
  12904. \begin{lstlisting}
  12905. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12906. \end{lstlisting}
  12907. \fi}
  12908. {\if\edition\pythonEd
  12909. \begin{lstlisting}
  12910. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12911. \end{lstlisting}
  12912. \fi}
  12913. For function calls with too many arguments, the \code{limit\_functions}
  12914. pass transforms them in the following way.
  12915. \begin{tabular}{lll}
  12916. \begin{minipage}{0.3\textwidth}
  12917. {\if\edition\racketEd
  12918. \begin{lstlisting}
  12919. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12920. \end{lstlisting}
  12921. \fi}
  12922. {\if\edition\pythonEd
  12923. \begin{lstlisting}
  12924. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12925. \end{lstlisting}
  12926. \fi}
  12927. \end{minipage}
  12928. &
  12929. $\Rightarrow$
  12930. &
  12931. \begin{minipage}{0.5\textwidth}
  12932. {\if\edition\racketEd
  12933. \begin{lstlisting}
  12934. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12935. \end{lstlisting}
  12936. \fi}
  12937. {\if\edition\pythonEd
  12938. \begin{lstlisting}
  12939. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12940. \end{lstlisting}
  12941. \fi}
  12942. \end{minipage}
  12943. \end{tabular}
  12944. \section{Remove Complex Operands}
  12945. \label{sec:rco-r4}
  12946. The primary decisions to make for this pass is whether to classify
  12947. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12948. atomic or complex expressions. Recall that a simple expression will
  12949. eventually end up as just an immediate argument of an x86
  12950. instruction. Function application will be translated to a sequence of
  12951. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12952. classified as complex expression. On the other hand, the arguments of
  12953. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12954. %
  12955. Regarding \code{FunRef}, as discussed above, the function label needs
  12956. to be converted to an address using the \code{leaq} instruction. Thus,
  12957. even though \code{FunRef} seems rather simple, it needs to be
  12958. classified as a complex expression so that we generate an assignment
  12959. statement with a left-hand side that can serve as the target of the
  12960. \code{leaq}.
  12961. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12962. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12963. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12964. %
  12965. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12966. % TODO: Return?
  12967. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  12968. %% \LangFunANF{} of this pass.
  12969. %% \begin{figure}[tp]
  12970. %% \centering
  12971. %% \fbox{
  12972. %% \begin{minipage}{0.96\textwidth}
  12973. %% \small
  12974. %% \[
  12975. %% \begin{array}{rcl}
  12976. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12977. %% \MID \VOID{} } \\
  12978. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12979. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12980. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12981. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12982. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12983. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12984. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12985. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12986. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12987. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12988. %% \end{array}
  12989. %% \]
  12990. %% \end{minipage}
  12991. %% }
  12992. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12993. %% \label{fig:Lfun-anf-syntax}
  12994. %% \end{figure}
  12995. \section{Explicate Control and the \LangCFun{} language}
  12996. \label{sec:explicate-control-r4}
  12997. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12998. output of \code{explicate\_control}.
  12999. %
  13000. \racket{(The concrete syntax is given in
  13001. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13002. %
  13003. The auxiliary functions for assignment\racket{and tail contexts} should
  13004. be updated with cases for
  13005. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13006. function for predicate context should be updated for
  13007. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13008. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13009. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13010. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13011. auxiliary function for processing function definitions. This code is
  13012. similar to the case for \code{Program} in \LangVec{}. The top-level
  13013. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13014. form of \LangFun{} can then apply this new function to all the
  13015. function definitions.
  13016. {\if\edition\pythonEd
  13017. The translation of \code{Return} statements requires a new auxiliary
  13018. function to handle expressions in tail context, called
  13019. \code{explicate\_tail}. The function should take an expression and the
  13020. dictionary of basic blocks and produce a list of statements in the
  13021. \LangCFun{} language. The \code{explicate\_tail} function should
  13022. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13023. and a default case for other kinds of expressions. The default case
  13024. should produce a \code{Return} statement. The case for \code{Call}
  13025. should change it into \code{TailCall}. The other cases should
  13026. recursively process their subexpressions and statements, choosing the
  13027. appropriate explicate functions for the various contexts.
  13028. \fi}
  13029. \newcommand{\CfunASTRacket}{
  13030. \begin{array}{lcl}
  13031. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13032. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13033. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13034. \end{array}
  13035. }
  13036. \newcommand{\CfunASTPython}{
  13037. \begin{array}{lcl}
  13038. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13039. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13040. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13041. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13042. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13043. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13044. \end{array}
  13045. }
  13046. \begin{figure}[tp]
  13047. \fbox{
  13048. \begin{minipage}{0.96\textwidth}
  13049. \small
  13050. {\if\edition\racketEd
  13051. \[
  13052. \begin{array}{l}
  13053. \gray{\CvarASTRacket} \\ \hline
  13054. \gray{\CifASTRacket} \\ \hline
  13055. \gray{\CloopASTRacket} \\ \hline
  13056. \gray{\CtupASTRacket} \\ \hline
  13057. \CfunASTRacket \\
  13058. \begin{array}{lcl}
  13059. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13060. \end{array}
  13061. \end{array}
  13062. \]
  13063. \fi}
  13064. {\if\edition\pythonEd
  13065. \[
  13066. \begin{array}{l}
  13067. \gray{\CifASTPython} \\ \hline
  13068. \gray{\CtupASTPython} \\ \hline
  13069. \CfunASTPython \\
  13070. \begin{array}{lcl}
  13071. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13072. \end{array}
  13073. \end{array}
  13074. \]
  13075. \fi}
  13076. \end{minipage}
  13077. }
  13078. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13079. \label{fig:c3-syntax}
  13080. \end{figure}
  13081. \section{Select Instructions and the \LangXIndCall{} Language}
  13082. \label{sec:select-r4}
  13083. \index{subject}{instruction selection}
  13084. The output of select instructions is a program in the \LangXIndCall{}
  13085. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  13086. \index{subject}{x86}
  13087. \begin{figure}[tp]
  13088. \fbox{
  13089. \begin{minipage}{0.96\textwidth}
  13090. \small
  13091. \[
  13092. \begin{array}{lcl}
  13093. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  13094. \itm{cc} & ::= & \gray{ \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  13095. \Instr &::=& \ldots
  13096. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13097. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13098. \Block &::= & \Instr^{+} \\
  13099. \Def &::= & \key{.globl}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*} \\
  13100. \LangXIndCallM{} &::= & \Def\ldots
  13101. \end{array}
  13102. \]
  13103. \end{minipage}
  13104. }
  13105. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13106. \label{fig:x86-3-concrete}
  13107. \end{figure}
  13108. \begin{figure}[tp]
  13109. \fbox{
  13110. \begin{minipage}{0.96\textwidth}
  13111. \small
  13112. {\if\edition\racketEd
  13113. \[
  13114. \begin{array}{lcl}
  13115. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13116. \MID \BYTEREG{\Reg} } \\
  13117. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13118. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13119. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13120. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13121. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13122. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  13123. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13124. \end{array}
  13125. \]
  13126. \fi}
  13127. {\if\edition\pythonEd
  13128. \[
  13129. \begin{array}{lcl}
  13130. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13131. \MID \BYTEREG{\Reg} } \\
  13132. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13133. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13134. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13135. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13136. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13137. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13138. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13139. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13140. \end{array}
  13141. \]
  13142. \fi}
  13143. \end{minipage}
  13144. }
  13145. \caption{The abstract syntax of \LangXIndCall{} (extends
  13146. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13147. \label{fig:x86-3}
  13148. \end{figure}
  13149. An assignment of a function reference to a variable becomes a
  13150. load-effective-address instruction as follows, where $\itm{lhs}'$
  13151. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  13152. to \Arg{} in \LangXIndCallVar{}. \\
  13153. \begin{tabular}{lcl}
  13154. \begin{minipage}{0.35\textwidth}
  13155. {\if\edition\racketEd
  13156. \begin{lstlisting}
  13157. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13158. \end{lstlisting}
  13159. \fi}
  13160. {\if\edition\pythonEd
  13161. \begin{lstlisting}
  13162. |$\itm{lhs}$| = FunRef(|$f$|, |$n$|);
  13163. \end{lstlisting}
  13164. \fi}
  13165. \end{minipage}
  13166. &
  13167. $\Rightarrow$\qquad\qquad
  13168. &
  13169. \begin{minipage}{0.3\textwidth}
  13170. {\if\edition\racketEd
  13171. \begin{lstlisting}
  13172. leaq (fun-ref |$f$| |$n$|), |$\itm{lhs}'$|
  13173. \end{lstlisting}
  13174. \fi}
  13175. {\if\edition\pythonEd
  13176. \begin{lstlisting}
  13177. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13178. \end{lstlisting}
  13179. \fi}
  13180. \end{minipage}
  13181. \end{tabular} \\
  13182. Regarding function definitions, we need to remove the parameters and
  13183. instead perform parameter passing using the conventions discussed in
  13184. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13185. registers. We recommend turning the parameters into local variables
  13186. and generating instructions at the beginning of the function to move
  13187. from the argument passing registers to these local variables.
  13188. {\if\edition\racketEd
  13189. \begin{lstlisting}
  13190. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13191. |$\Rightarrow$|
  13192. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13193. \end{lstlisting}
  13194. \fi}
  13195. {\if\edition\pythonEd
  13196. \begin{lstlisting}
  13197. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13198. |$\Rightarrow$|
  13199. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13200. \end{lstlisting}
  13201. \fi}
  13202. The basic blocks $B'$ are the same as $B$ except that the
  13203. \code{start} block is modified to add the instructions for moving from
  13204. the argument registers to the parameter variables. So the \code{start}
  13205. block of $B$ shown on the left is changed to the code on the right.
  13206. \begin{center}
  13207. \begin{minipage}{0.3\textwidth}
  13208. \begin{lstlisting}
  13209. start:
  13210. |$\itm{instr}_1$|
  13211. |$\cdots$|
  13212. |$\itm{instr}_n$|
  13213. \end{lstlisting}
  13214. \end{minipage}
  13215. $\Rightarrow$
  13216. \begin{minipage}{0.3\textwidth}
  13217. \begin{lstlisting}
  13218. start:
  13219. movq %rdi, |$x_1$|
  13220. |$\cdots$|
  13221. |$\itm{instr}_1$|
  13222. |$\cdots$|
  13223. |$\itm{instr}_n$|
  13224. \end{lstlisting}
  13225. \end{minipage}
  13226. \end{center}
  13227. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13228. parameters the function expects, but the parameters are no longer in
  13229. the syntax of function definitions. Instead, add an entry to
  13230. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13231. to construct $\itm{info}'$.}
  13232. By changing the parameters to local variables, we are giving the
  13233. register allocator control over which registers or stack locations to
  13234. use for them. If you implemented the move-biasing challenge
  13235. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13236. assign the parameter variables to the corresponding argument register,
  13237. in which case the \code{patch\_instructions} pass will remove the
  13238. \code{movq} instruction. This happens in the example translation in
  13239. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13240. the \code{add} function.
  13241. %
  13242. Also, note that the register allocator will perform liveness analysis
  13243. on this sequence of move instructions and build the interference
  13244. graph. So, for example, $x_1$ will be marked as interfering with
  13245. \code{rsi} and that will prevent the assignment of $x_1$ to
  13246. \code{rsi}, which is good, because that would overwrite the argument
  13247. that needs to move into $x_2$.
  13248. Next, consider the compilation of function calls. In the mirror image
  13249. of handling the parameters of function definitions, the arguments need
  13250. to be moved to the argument passing registers. The function call
  13251. itself is performed with an indirect function call. The return value
  13252. from the function is stored in \code{rax}, so it needs to be moved
  13253. into the \itm{lhs}.
  13254. \begin{lstlisting}
  13255. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13256. |$\Rightarrow$|
  13257. movq |$\itm{arg}_1$|, %rdi
  13258. movq |$\itm{arg}_2$|, %rsi
  13259. |$\vdots$|
  13260. callq *|\itm{fun}|
  13261. movq %rax, |\itm{lhs}|
  13262. \end{lstlisting}
  13263. The \code{IndirectCallq} AST node includes an integer for the arity of
  13264. the function, i.e., the number of parameters. That information is
  13265. useful in the \code{uncover\_live} pass for determining which
  13266. argument-passing registers are potentially read during the call.
  13267. For tail calls, the parameter passing is the same as non-tail calls:
  13268. generate instructions to move the arguments into the argument
  13269. passing registers. After that we need to pop the frame from the
  13270. procedure call stack. However, we do not yet know how big the frame
  13271. is; that gets determined during register allocation. So instead of
  13272. generating those instructions here, we invent a new instruction that
  13273. means ``pop the frame and then do an indirect jump'', which we name
  13274. \code{TailJmp}. The abstract syntax for this instruction includes an
  13275. argument that specifies where to jump and an integer that represents
  13276. the arity of the function being called.
  13277. Recall that we use the label \code{start} for the initial block of a
  13278. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13279. the conclusion of the program with \code{conclusion}, so that
  13280. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13281. by a jump to \code{conclusion}. With the addition of function
  13282. definitions, there is a start block and conclusion for each function,
  13283. but their labels need to be unique. We recommend prepending the
  13284. function's name to \code{start} and \code{conclusion}, respectively,
  13285. to obtain unique labels.
  13286. \section{Register Allocation}
  13287. \label{sec:register-allocation-r4}
  13288. \subsection{Liveness Analysis}
  13289. \label{sec:liveness-analysis-r4}
  13290. \index{subject}{liveness analysis}
  13291. %% The rest of the passes need only minor modifications to handle the new
  13292. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13293. %% \code{leaq}.
  13294. The \code{IndirectCallq} instruction should be treated like
  13295. \code{Callq} regarding its written locations $W$, in that they should
  13296. include all the caller-saved registers. Recall that the reason for
  13297. that is to force variables that are live across a function call to be assigned to callee-saved
  13298. registers or to be spilled to the stack.
  13299. Regarding the set of read locations $R$, the arity field of
  13300. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13301. argument-passing registers should be considered as read by those
  13302. instructions. Also, the target field of \code{TailJmp} and
  13303. \code{IndirectCallq} should be included in the set of read locations
  13304. $R$.
  13305. \subsection{Build Interference Graph}
  13306. \label{sec:build-interference-r4}
  13307. With the addition of function definitions, we compute a separate interference
  13308. graph for each function (not just one for the whole program).
  13309. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13310. spill vector-typed variables that are live during a call to
  13311. \code{collect}, the garbage collector. With the addition of functions to our language, we
  13312. need to revisit this issue. Functions that perform allocation contain
  13313. calls to the collector. Thus, we should
  13314. not only spill a vector-typed variable when it is live during a call
  13315. to \code{collect}, but we should spill the variable if it is live
  13316. during call to a user-defined function. Thus, in the \code{build\_interference} pass,
  13317. we recommend adding interference edges between call-live vector-typed
  13318. variables and the callee-saved registers (in addition to the usual
  13319. addition of edges between call-live variables and the caller-saved
  13320. registers).
  13321. \subsection{Allocate Registers}
  13322. The primary change to the \code{allocate\_registers} pass is adding an
  13323. auxiliary function for handling definitions (the \Def{} non-terminal
  13324. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13325. logic is the same as described in
  13326. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13327. allocation is performed many times, once for each function definition,
  13328. instead of just once for the whole program.
  13329. \section{Patch Instructions}
  13330. In \code{patch\_instructions}, you should deal with the x86
  13331. idiosyncrasy that the destination argument of \code{leaq} must be a
  13332. register. Additionally, you should ensure that the argument of
  13333. \code{TailJmp} is \itm{rax}, our reserved register---mostly to make
  13334. code generation more convenient, because we trample many registers
  13335. before the tail call (as explained in the next section).
  13336. \section{Prelude and Conclusion}
  13337. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13338. %% \code{IndirectCallq} are straightforward: output their concrete
  13339. %% syntax.
  13340. %% \begin{lstlisting}
  13341. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13342. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13343. %% \end{lstlisting}
  13344. Now that register allocation is complete, we can translate the
  13345. \code{TailJmp} into a sequence of instructions. A straightforward
  13346. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13347. However, before the jump we need to pop the current frame. This
  13348. sequence of instructions is the same as the code for the conclusion of
  13349. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13350. Regarding function definitions, you need to generate a prelude
  13351. and conclusion for each one. This code is similar to the prelude and
  13352. conclusion generated for the \code{main} function in
  13353. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13354. should carry out the following steps.
  13355. % TODO: .align the functions!
  13356. \begin{enumerate}
  13357. %% \item Start with \code{.global} and \code{.align} directives followed
  13358. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13359. %% example.)
  13360. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13361. pointer.
  13362. \item Push to the stack all of the callee-saved registers that were
  13363. used for register allocation.
  13364. \item Move the stack pointer \code{rsp} down by the size of the stack
  13365. frame for this function, which depends on the number of regular
  13366. spills. (Aligned to 16 bytes.)
  13367. \item Move the root stack pointer \code{r15} up by the size of the
  13368. root-stack frame for this function, which depends on the number of
  13369. spilled vectors. \label{root-stack-init}
  13370. \item Initialize to zero all new entries in the root-stack frame.
  13371. \item Jump to the start block.
  13372. \end{enumerate}
  13373. The prelude of the \code{main} function has one additional task: call
  13374. the \code{initialize} function to set up the garbage collector and
  13375. move the value of the global \code{rootstack\_begin} in
  13376. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13377. above, which depends on \code{r15}.
  13378. The conclusion of every function should do the following.
  13379. \begin{enumerate}
  13380. \item Move the stack pointer back up by the size of the stack frame
  13381. for this function.
  13382. \item Restore the callee-saved registers by popping them from the
  13383. stack.
  13384. \item Move the root stack pointer back down by the size of the
  13385. root-stack frame for this function.
  13386. \item Restore \code{rbp} by popping it from the stack.
  13387. \item Return to the caller with the \code{retq} instruction.
  13388. \end{enumerate}
  13389. \begin{exercise}\normalfont\normalsize
  13390. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13391. Create 5 new programs that use functions, including examples that pass
  13392. functions and return functions from other functions, recursive
  13393. functions, functions that create vectors, and functions that make tail
  13394. calls. Test your compiler on these new programs and all of your
  13395. previously created test programs.
  13396. \end{exercise}
  13397. \begin{figure}[tbp]
  13398. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13399. \node (Lfun) at (0,2) {\large \LangFun{}};
  13400. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13401. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13402. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13403. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13404. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13405. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13406. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13407. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13408. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13409. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13410. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13411. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13412. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13413. \path[->,bend left=15] (Lfun) edge [above] node
  13414. {\ttfamily\footnotesize shrink} (Lfun-1);
  13415. \path[->,bend left=15] (Lfun-1) edge [above] node
  13416. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13417. \path[->,bend left=15] (Lfun-2) edge [above] node
  13418. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13419. \path[->,bend left=15] (F1-1) edge [right] node
  13420. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13421. \path[->,bend right=15] (F1-2) edge [above] node
  13422. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13423. \path[->,bend right=15] (F1-3) edge [above] node
  13424. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13425. \path[->,bend left=15] (F1-4) edge [right] node
  13426. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13427. \path[->,bend right=15] (C3-2) edge [left] node
  13428. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13429. \path[->,bend left=15] (x86-2) edge [left] node
  13430. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13431. \path[->,bend right=15] (x86-2-1) edge [below] node
  13432. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13433. \path[->,bend right=15] (x86-2-2) edge [left] node
  13434. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13435. \path[->,bend left=15] (x86-3) edge [above] node
  13436. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13437. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13438. \end{tikzpicture}
  13439. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13440. \label{fig:Lfun-passes}
  13441. \end{figure}
  13442. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13443. compiling \LangFun{} to x86.
  13444. \section{An Example Translation}
  13445. \label{sec:functions-example}
  13446. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13447. function in \LangFun{} to x86. The figure also includes the results of the
  13448. \code{explicate\_control} and \code{select\_instructions} passes.
  13449. \begin{figure}[htbp]
  13450. \begin{tabular}{ll}
  13451. \begin{minipage}{0.4\textwidth}
  13452. % s3_2.rkt
  13453. {\if\edition\racketEd
  13454. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13455. (define (add [x : Integer] [y : Integer])
  13456. : Integer
  13457. (+ x y))
  13458. (add 40 2)
  13459. \end{lstlisting}
  13460. \fi}
  13461. {\if\edition\pythonEd
  13462. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13463. def add(x:int, y:int) -> int:
  13464. return x + y
  13465. print(add(40, 2))
  13466. \end{lstlisting}
  13467. \fi}
  13468. $\Downarrow$
  13469. {\if\edition\racketEd
  13470. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13471. (define (add86 [x87 : Integer]
  13472. [y88 : Integer]) : Integer
  13473. add86start:
  13474. return (+ x87 y88);
  13475. )
  13476. (define (main) : Integer ()
  13477. mainstart:
  13478. tmp89 = (fun-ref add86 2);
  13479. (tail-call tmp89 40 2)
  13480. )
  13481. \end{lstlisting}
  13482. \fi}
  13483. {\if\edition\pythonEd
  13484. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13485. def add(x:int, y:int) -> int:
  13486. addstart:
  13487. return x + y
  13488. def main() -> int:
  13489. mainstart:
  13490. fun.0 = add
  13491. tmp.1 = fun.0(40, 2)
  13492. print(tmp.1)
  13493. return 0
  13494. \end{lstlisting}
  13495. \fi}
  13496. \end{minipage}
  13497. &
  13498. $\Rightarrow$
  13499. \begin{minipage}{0.5\textwidth}
  13500. {\if\edition\racketEd
  13501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13502. (define (add86) : Integer
  13503. add86start:
  13504. movq %rdi, x87
  13505. movq %rsi, y88
  13506. movq x87, %rax
  13507. addq y88, %rax
  13508. jmp inc1389conclusion
  13509. )
  13510. (define (main) : Integer
  13511. mainstart:
  13512. leaq (fun-ref add86 2), tmp89
  13513. movq $40, %rdi
  13514. movq $2, %rsi
  13515. tail-jmp tmp89
  13516. )
  13517. \end{lstlisting}
  13518. \fi}
  13519. {\if\edition\pythonEd
  13520. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13521. def add() -> int:
  13522. addstart:
  13523. movq %rdi, x
  13524. movq %rsi, y
  13525. movq x, %rax
  13526. addq y, %rax
  13527. jmp addconclusion
  13528. def main() -> int:
  13529. mainstart:
  13530. leaq add, fun.0
  13531. movq $40, %rdi
  13532. movq $2, %rsi
  13533. callq *fun.0
  13534. movq %rax, tmp.1
  13535. movq tmp.1, %rdi
  13536. callq print_int
  13537. movq $0, %rax
  13538. jmp mainconclusion
  13539. \end{lstlisting}
  13540. \fi}
  13541. $\Downarrow$
  13542. \end{minipage}
  13543. \end{tabular}
  13544. \begin{tabular}{ll}
  13545. \begin{minipage}{0.3\textwidth}
  13546. {\if\edition\racketEd
  13547. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13548. .globl add86
  13549. .align 16
  13550. add86:
  13551. pushq %rbp
  13552. movq %rsp, %rbp
  13553. jmp add86start
  13554. add86start:
  13555. movq %rdi, %rax
  13556. addq %rsi, %rax
  13557. jmp add86conclusion
  13558. add86conclusion:
  13559. popq %rbp
  13560. retq
  13561. \end{lstlisting}
  13562. \fi}
  13563. {\if\edition\pythonEd
  13564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13565. .align 16
  13566. add:
  13567. pushq %rbp
  13568. movq %rsp, %rbp
  13569. subq $0, %rsp
  13570. jmp addstart
  13571. addstart:
  13572. movq %rdi, %rdx
  13573. movq %rsi, %rcx
  13574. movq %rdx, %rax
  13575. addq %rcx, %rax
  13576. jmp addconclusion
  13577. addconclusion:
  13578. subq $0, %r15
  13579. addq $0, %rsp
  13580. popq %rbp
  13581. retq
  13582. \end{lstlisting}
  13583. \fi}
  13584. \end{minipage}
  13585. &
  13586. \begin{minipage}{0.5\textwidth}
  13587. {\if\edition\racketEd
  13588. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13589. .globl main
  13590. .align 16
  13591. main:
  13592. pushq %rbp
  13593. movq %rsp, %rbp
  13594. movq $16384, %rdi
  13595. movq $16384, %rsi
  13596. callq initialize
  13597. movq rootstack_begin(%rip), %r15
  13598. jmp mainstart
  13599. mainstart:
  13600. leaq add86(%rip), %rcx
  13601. movq $40, %rdi
  13602. movq $2, %rsi
  13603. movq %rcx, %rax
  13604. popq %rbp
  13605. jmp *%rax
  13606. mainconclusion:
  13607. popq %rbp
  13608. retq
  13609. \end{lstlisting}
  13610. \fi}
  13611. {\if\edition\pythonEd
  13612. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13613. .globl main
  13614. .align 16
  13615. main:
  13616. pushq %rbp
  13617. movq %rsp, %rbp
  13618. subq $0, %rsp
  13619. movq $65536, %rdi
  13620. movq $65536, %rsi
  13621. callq initialize
  13622. movq rootstack_begin(%rip), %r15
  13623. jmp mainstart
  13624. mainstart:
  13625. leaq add(%rip), %rcx
  13626. movq $40, %rdi
  13627. movq $2, %rsi
  13628. callq *%rcx
  13629. movq %rax, %rcx
  13630. movq %rcx, %rdi
  13631. callq print_int
  13632. movq $0, %rax
  13633. jmp mainconclusion
  13634. mainconclusion:
  13635. subq $0, %r15
  13636. addq $0, %rsp
  13637. popq %rbp
  13638. retq
  13639. \end{lstlisting}
  13640. \fi}
  13641. \end{minipage}
  13642. \end{tabular}
  13643. \caption{Example compilation of a simple function to x86.}
  13644. \label{fig:add-fun}
  13645. \end{figure}
  13646. % Challenge idea: inlining! (simple version)
  13647. % Further Reading
  13648. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13649. \chapter{Lexically Scoped Functions}
  13650. \label{ch:Llambda}
  13651. \index{subject}{lambda}
  13652. \index{subject}{lexical scoping}
  13653. This chapter studies lexically scoped functions. Lexical scoping means
  13654. that a function's body may refer to variables whose binding site is
  13655. outside of the function, in an enclosing scope.
  13656. %
  13657. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13658. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13659. using the \key{lambda} form. The body of the \key{lambda} refers to
  13660. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13661. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13662. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13663. variable of function \code{f}} and \code{x} is a parameter of
  13664. function \code{f}. The \key{lambda} is returned from the function
  13665. \code{f}. The main expression of the program includes two calls to
  13666. \code{f} with different arguments for \code{x}, first \code{5} then
  13667. \code{3}. The functions returned from \code{f} are bound to variables
  13668. \code{g} and \code{h}. Even though these two functions were created by
  13669. the same \code{lambda}, they are really different functions because
  13670. they use different values for \code{x}. Applying \code{g} to \code{11}
  13671. produces \code{20} whereas applying \code{h} to \code{15} produces
  13672. \code{22}. The result of this program is \code{42}.
  13673. \begin{figure}[btp]
  13674. {\if\edition\racketEd
  13675. % lambda_test_21.rkt
  13676. \begin{lstlisting}
  13677. (define (f [x : Integer]) : (Integer -> Integer)
  13678. (let ([y 4])
  13679. (lambda: ([z : Integer]) : Integer
  13680. (+ x (+ y z)))))
  13681. (let ([g (f 5)])
  13682. (let ([h (f 3)])
  13683. (+ (g 11) (h 15))))
  13684. \end{lstlisting}
  13685. \fi}
  13686. {\if\edition\pythonEd
  13687. \begin{lstlisting}
  13688. def f(x : int) -> Callable[[int], int]:
  13689. y = 4
  13690. return lambda z: x + y + z
  13691. g = f(5)
  13692. h = f(3)
  13693. print( g(11) + h(15) )
  13694. \end{lstlisting}
  13695. \fi}
  13696. \caption{Example of a lexically scoped function.}
  13697. \label{fig:lexical-scoping}
  13698. \end{figure}
  13699. The approach that we take for implementing lexically scoped functions
  13700. is to compile them into top-level function definitions, translating
  13701. from \LangLam{} into \LangFun{}. However, the compiler must give
  13702. special treatment to variable occurrences such as \code{x} and
  13703. \code{y} in the body of the \code{lambda} of
  13704. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13705. may not refer to variables defined outside of it. To identify such
  13706. variable occurrences, we review the standard notion of free variable.
  13707. \begin{definition}
  13708. A variable is \textbf{free in expression} $e$ if the variable occurs
  13709. inside $e$ but does not have an enclosing definition that is also in
  13710. $e$.\index{subject}{free variable}
  13711. \end{definition}
  13712. For example, in the expression
  13713. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13714. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13715. only \code{x} and \code{y} are free in the following expression
  13716. because \code{z} is defined by the \code{lambda}.
  13717. {\if\edition\racketEd
  13718. \begin{lstlisting}
  13719. (lambda: ([z : Integer]) : Integer
  13720. (+ x (+ y z)))
  13721. \end{lstlisting}
  13722. \fi}
  13723. {\if\edition\pythonEd
  13724. \begin{lstlisting}
  13725. lambda z: x + y + z
  13726. \end{lstlisting}
  13727. \fi}
  13728. %
  13729. So the free variables of a \code{lambda} are the ones that need
  13730. special treatment. We need to transport, at runtime, the values of
  13731. those variables from the point where the \code{lambda} was created to
  13732. the point where the \code{lambda} is applied. An efficient solution to
  13733. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13734. of the free variables together with a function pointer into a tuple,
  13735. an arrangement called a \emph{flat closure} (which we shorten to just
  13736. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  13737. %
  13738. Fortunately, we have all the ingredients to make closures:
  13739. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13740. function pointers. The function pointer resides at index $0$ and the
  13741. values for the free variables fill in the rest of the tuple.
  13742. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13743. how closures work. It's a three-step dance. The program calls function
  13744. \code{f}, which creates a closure for the \code{lambda}. The closure
  13745. is a tuple whose first element is a pointer to the top-level function
  13746. that we will generate for the \code{lambda}, the second element is the
  13747. value of \code{x}, which is \code{5}, and the third element is
  13748. \code{4}, the value of \code{y}. The closure does not contain an
  13749. element for \code{z} because \code{z} is not a free variable of the
  13750. \code{lambda}. Creating the closure is step 1 of the dance. The
  13751. closure is returned from \code{f} and bound to \code{g}, as shown in
  13752. Figure~\ref{fig:closures}.
  13753. %
  13754. The second call to \code{f} creates another closure, this time with
  13755. \code{3} in the second slot (for \code{x}). This closure is also
  13756. returned from \code{f} but bound to \code{h}, which is also shown in
  13757. Figure~\ref{fig:closures}.
  13758. \begin{figure}[tbp]
  13759. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13760. \caption{Flat closure representations for the two functions
  13761. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13762. \label{fig:closures}
  13763. \end{figure}
  13764. Continuing with the example, consider the application of \code{g} to
  13765. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13766. obtain the function pointer in the first element of the closure and
  13767. call it, passing in the closure itself and then the regular arguments,
  13768. in this case \code{11}. This technique for applying a closure is step
  13769. 2 of the dance.
  13770. %
  13771. But doesn't this \code{lambda} only take 1 argument, for parameter
  13772. \code{z}? The third and final step of the dance is generating a
  13773. top-level function for a \code{lambda}. We add an additional
  13774. parameter for the closure and we insert an initialization at the beginning
  13775. of the function for each free variable, to bind those variables to the
  13776. appropriate elements from the closure parameter.
  13777. %
  13778. This three-step dance is known as \emph{closure conversion}. We
  13779. discuss the details of closure conversion in
  13780. Section~\ref{sec:closure-conversion} and the code generated from the
  13781. example in Section~\ref{sec:example-lambda}. But first we define the
  13782. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13783. \section{The \LangLam{} Language}
  13784. \label{sec:r5}
  13785. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13786. functions and lexical scoping, is defined in
  13787. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13788. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13789. syntax for function application.
  13790. %
  13791. \python{The syntax also includes an assignment statement that includes
  13792. a type annotation for the variable on the left-hand side, which
  13793. facilitates the type checking of \code{lambda} expressions that we
  13794. discuss later in this section.}
  13795. %
  13796. \python{The \code{arity} operation returns the number of parameters of
  13797. a given function, an operation that we need for the translation
  13798. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13799. The \code{arity} operation is not in Python, but the same functionality
  13800. is available in a more complex form. We include \code{arity} in the
  13801. \LangLam{} source language to enable testing.}
  13802. \newcommand{\LlambdaGrammarRacket}{
  13803. \begin{array}{lcl}
  13804. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13805. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13806. \end{array}
  13807. }
  13808. \newcommand{\LlambdaASTRacket}{
  13809. \begin{array}{lcl}
  13810. \itm{op} &::=& \code{procedure-arity} \\
  13811. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13812. \end{array}
  13813. }
  13814. \newcommand{\LlambdaGrammarPython}{
  13815. \begin{array}{lcl}
  13816. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13817. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13818. \end{array}
  13819. }
  13820. \newcommand{\LlambdaASTPython}{
  13821. \begin{array}{lcl}
  13822. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13823. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13824. \end{array}
  13825. }
  13826. % include AnnAssign in ASTPython
  13827. \begin{figure}[tp]
  13828. \centering
  13829. \fbox{
  13830. \begin{minipage}{0.96\textwidth}
  13831. \small
  13832. {\if\edition\racketEd
  13833. \[
  13834. \begin{array}{l}
  13835. \gray{\LintGrammarRacket{}} \\ \hline
  13836. \gray{\LvarGrammarRacket{}} \\ \hline
  13837. \gray{\LifGrammarRacket{}} \\ \hline
  13838. \gray{\LwhileGrammarRacket} \\ \hline
  13839. \gray{\LtupGrammarRacket} \\ \hline
  13840. \gray{\LfunGrammarRacket} \\ \hline
  13841. \LlambdaGrammarRacket \\
  13842. \begin{array}{lcl}
  13843. \LangLamM{} &::=& \Def\ldots \; \Exp
  13844. \end{array}
  13845. \end{array}
  13846. \]
  13847. \fi}
  13848. {\if\edition\pythonEd
  13849. \[
  13850. \begin{array}{l}
  13851. \gray{\LintGrammarPython{}} \\ \hline
  13852. \gray{\LvarGrammarPython{}} \\ \hline
  13853. \gray{\LifGrammarPython{}} \\ \hline
  13854. \gray{\LwhileGrammarPython} \\ \hline
  13855. \gray{\LtupGrammarPython} \\ \hline
  13856. \gray{\LfunGrammarPython} \\ \hline
  13857. \LlambdaGrammarPython \\
  13858. \begin{array}{lcl}
  13859. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13860. \end{array}
  13861. \end{array}
  13862. \]
  13863. \fi}
  13864. \end{minipage}
  13865. }
  13866. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-concrete-syntax})
  13867. with \key{lambda}.}
  13868. \label{fig:Rlam-concrete-syntax}
  13869. \end{figure}
  13870. \begin{figure}[tp]
  13871. \centering
  13872. \fbox{
  13873. \begin{minipage}{0.96\textwidth}
  13874. \small
  13875. {\if\edition\racketEd
  13876. \[
  13877. \begin{array}{l}
  13878. \gray{\LintOpAST} \\ \hline
  13879. \gray{\LvarASTRacket{}} \\ \hline
  13880. \gray{\LifASTRacket{}} \\ \hline
  13881. \gray{\LwhileASTRacket{}} \\ \hline
  13882. \gray{\LtupASTRacket{}} \\ \hline
  13883. \gray{\LfunASTRacket} \\ \hline
  13884. \LlambdaASTRacket \\
  13885. \begin{array}{lcl}
  13886. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13887. \end{array}
  13888. \end{array}
  13889. \]
  13890. \fi}
  13891. {\if\edition\pythonEd
  13892. \[
  13893. \begin{array}{l}
  13894. \gray{\LintASTPython} \\ \hline
  13895. \gray{\LvarASTPython{}} \\ \hline
  13896. \gray{\LifASTPython{}} \\ \hline
  13897. \gray{\LwhileASTPython{}} \\ \hline
  13898. \gray{\LtupASTPython{}} \\ \hline
  13899. \gray{\LfunASTPython} \\ \hline
  13900. \LlambdaASTPython \\
  13901. \begin{array}{lcl}
  13902. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13903. \end{array}
  13904. \end{array}
  13905. \]
  13906. \fi}
  13907. \end{minipage}
  13908. }
  13909. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-syntax}).}
  13910. \label{fig:Rlam-syntax}
  13911. \end{figure}
  13912. \index{subject}{interpreter}
  13913. \label{sec:interp-Rlambda}
  13914. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13915. \LangLam{}. The case for \key{Lambda} saves the current environment
  13916. inside the returned function value. Recall that during function
  13917. application, the environment stored in the function value, extended
  13918. with the mapping of parameters to argument values, is used to
  13919. interpret the body of the function.
  13920. \begin{figure}[tbp]
  13921. {\if\edition\racketEd
  13922. \begin{lstlisting}
  13923. (define interp-Llambda-class
  13924. (class interp-Lfun-class
  13925. (super-new)
  13926. (define/override (interp-op op)
  13927. (match op
  13928. ['procedure-arity
  13929. (lambda (v)
  13930. (match v
  13931. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13932. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13933. [else (super interp-op op)]))
  13934. (define/override ((interp-exp env) e)
  13935. (define recur (interp-exp env))
  13936. (match e
  13937. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13938. `(function ,xs ,body ,env)]
  13939. [else ((super interp-exp env) e)]))
  13940. ))
  13941. (define (interp-Rlambda p)
  13942. (send (new interp-Llambda-class) interp-program p))
  13943. \end{lstlisting}
  13944. \fi}
  13945. {\if\edition\pythonEd
  13946. \begin{lstlisting}
  13947. class InterpLlambda(InterpLfun):
  13948. def arity(self, v):
  13949. match v:
  13950. case Function(name, params, body, env):
  13951. return len(params)
  13952. case _:
  13953. raise Exception('Llambda arity unexpected ' + repr(v))
  13954. def interp_exp(self, e, env):
  13955. match e:
  13956. case Call(Name('arity'), [fun]):
  13957. f = self.interp_exp(fun, env)
  13958. return self.arity(f)
  13959. case Lambda(params, body):
  13960. return Function('lambda', params, [Return(body)], env)
  13961. case _:
  13962. return super().interp_exp(e, env)
  13963. def interp_stmts(self, ss, env):
  13964. if len(ss) == 0:
  13965. return
  13966. match ss[0]:
  13967. case AnnAssign(lhs, typ, value, simple):
  13968. env[lhs.id] = self.interp_exp(value, env)
  13969. return self.interp_stmts(ss[1:], env)
  13970. case _:
  13971. return super().interp_stmts(ss, env)
  13972. \end{lstlisting}
  13973. \fi}
  13974. \caption{Interpreter for \LangLam{}.}
  13975. \label{fig:interp-Rlambda}
  13976. \end{figure}
  13977. \label{sec:type-check-r5}
  13978. \index{subject}{type checking}
  13979. {\if\edition\racketEd
  13980. %
  13981. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13982. \key{lambda} form. The body of the \key{lambda} is checked in an
  13983. environment that includes the current environment (because it is
  13984. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13985. require the body's type to match the declared return type.
  13986. %
  13987. \fi}
  13988. {\if\edition\pythonEd
  13989. %
  13990. Figures~\ref{fig:type-check-Llambda} and
  13991. \ref{fig:type-check-Llambda-part2} define the type checker for
  13992. \LangLam{}, which is more complex than one might expect. The reason
  13993. for the added complexity is that the syntax of \key{lambda} does not
  13994. include type annotations for the parameters or return type. Instead
  13995. they must be inferred. There are many approaches of type inference to
  13996. choose from of varying degrees of complexity. We choose one of the
  13997. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13998. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13999. this book is compilation, not type inference.
  14000. The main idea of bidirectional type inference is to add an auxilliary
  14001. function, here named \code{check\_exp}, that takes an expected type
  14002. and checks whether the given expression is of that type. Thus, in
  14003. \code{check\_exp}, type information flows in a top-down manner with
  14004. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14005. function, where type information flows in a primarily bottom-up
  14006. manner.
  14007. %
  14008. The idea then is to use \code{check\_exp} in all the places where we
  14009. already know what the type of an expression should be, such as in the
  14010. \code{return} statement of a top-level function definition, or on the
  14011. right-hand side of an annotated assignment statement.
  14012. Getting back to \code{lambda}, it is straightforward to check a
  14013. \code{lambda} inside \code{check\_exp} because the expected type
  14014. provides the parameter types and the return type. On the other hand,
  14015. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14016. that we do not allow \code{lambda} in contexts where we don't already
  14017. know its type. This restriction does not incur a loss of
  14018. expressiveness for \LangLam{} because it is straightforward to modify
  14019. a program to sidestep the restriction, for example, by using an
  14020. annotated assignment statement to assign the \code{lambda} to a
  14021. temporary variable.
  14022. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14023. checker records their type in a \code{has\_type} field. This type
  14024. information is used later in this chapter.
  14025. %
  14026. \fi}
  14027. \begin{figure}[tbp]
  14028. {\if\edition\racketEd
  14029. \begin{lstlisting}
  14030. (define (type-check-Rlambda env)
  14031. (lambda (e)
  14032. (match e
  14033. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14034. (define-values (new-body bodyT)
  14035. ((type-check-exp (append (map cons xs Ts) env)) body))
  14036. (define ty `(,@Ts -> ,rT))
  14037. (cond
  14038. [(equal? rT bodyT)
  14039. (values (HasType (Lambda params rT new-body) ty) ty)]
  14040. [else
  14041. (error "mismatch in return type" bodyT rT)])]
  14042. ...
  14043. )))
  14044. \end{lstlisting}
  14045. \fi}
  14046. {\if\edition\pythonEd
  14047. \begin{lstlisting}
  14048. class TypeCheckLlambda(TypeCheckLfun):
  14049. def type_check_exp(self, e, env):
  14050. match e:
  14051. case Name(id):
  14052. e.has_type = env[id]
  14053. return env[id]
  14054. case Lambda(params, body):
  14055. raise Exception('cannot synthesize a type for a lambda')
  14056. case Call(Name('arity'), [func]):
  14057. func_t = self.type_check_exp(func, env)
  14058. match func_t:
  14059. case FunctionType(params_t, return_t):
  14060. return IntType()
  14061. case _:
  14062. raise Exception('in arity, unexpected ' + repr(func_t))
  14063. case _:
  14064. return super().type_check_exp(e, env)
  14065. def check_exp(self, e, ty, env):
  14066. match e:
  14067. case Lambda(params, body):
  14068. e.has_type = ty
  14069. match ty:
  14070. case FunctionType(params_t, return_t):
  14071. new_env = env.copy().update(zip(params, params_t))
  14072. self.check_exp(body, return_t, new_env)
  14073. case _:
  14074. raise Exception('lambda does not have type ' + str(ty))
  14075. case Call(func, args):
  14076. func_t = self.type_check_exp(func, env)
  14077. match func_t:
  14078. case FunctionType(params_t, return_t):
  14079. for (arg, param_t) in zip(args, params_t):
  14080. self.check_exp(arg, param_t, env)
  14081. self.check_type_equal(return_t, ty, e)
  14082. case _:
  14083. raise Exception('type_check_exp: in call, unexpected ' + \
  14084. repr(func_t))
  14085. case _:
  14086. t = self.type_check_exp(e, env)
  14087. self.check_type_equal(t, ty, e)
  14088. \end{lstlisting}
  14089. \fi}
  14090. \caption{Type checking \LangLam{}\python{, part 1}.}
  14091. \label{fig:type-check-Llambda}
  14092. \end{figure}
  14093. {\if\edition\pythonEd
  14094. \begin{figure}[tbp]
  14095. \begin{lstlisting}
  14096. def check_stmts(self, ss, return_ty, env):
  14097. if len(ss) == 0:
  14098. return
  14099. match ss[0]:
  14100. case FunctionDef(name, params, body, dl, returns, comment):
  14101. new_env = env.copy().update(params)
  14102. rt = self.check_stmts(body, returns, new_env)
  14103. self.check_stmts(ss[1:], return_ty, env)
  14104. case Return(value):
  14105. self.check_exp(value, return_ty, env)
  14106. case Assign([Name(id)], value):
  14107. if id in env:
  14108. self.check_exp(value, env[id], env)
  14109. else:
  14110. env[id] = self.type_check_exp(value, env)
  14111. self.check_stmts(ss[1:], return_ty, env)
  14112. case Assign([Subscript(tup, Constant(index), Store())], value):
  14113. tup_t = self.type_check_exp(tup, env)
  14114. match tup_t:
  14115. case TupleType(ts):
  14116. self.check_exp(value, ts[index], env)
  14117. case _:
  14118. raise Exception('expected a tuple, not ' + repr(tup_t))
  14119. self.check_stmts(ss[1:], return_ty, env)
  14120. case AnnAssign(Name(id), ty_annot, value, simple):
  14121. ss[0].annotation = ty_annot
  14122. if id in env:
  14123. self.check_type_equal(env[id], ty_annot)
  14124. else:
  14125. env[id] = ty_annot
  14126. self.check_exp(value, ty_annot, env)
  14127. self.check_stmts(ss[1:], return_ty, env)
  14128. case _:
  14129. self.type_check_stmts(ss, env)
  14130. def type_check(self, p):
  14131. match p:
  14132. case Module(body):
  14133. env = {}
  14134. for s in body:
  14135. match s:
  14136. case FunctionDef(name, params, bod, dl, returns, comment):
  14137. params_t = [t for (x,t) in params]
  14138. env[name] = FunctionType(params_t, returns)
  14139. self.check_stmts(body, int, env)
  14140. \end{lstlisting}
  14141. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14142. \label{fig:type-check-Llambda-part2}
  14143. \end{figure}
  14144. \fi}
  14145. \clearpage
  14146. \section{Assignment and Lexically Scoped Functions}
  14147. \label{sec:assignment-scoping}
  14148. The combination of lexically-scoped functions and assignment to
  14149. variables raises a challenge with our approach to implementing
  14150. lexically-scoped functions. Consider the following example in which
  14151. function \code{f} has a free variable \code{x} that is changed after
  14152. \code{f} is created but before the call to \code{f}.
  14153. % loop_test_11.rkt
  14154. {\if\edition\racketEd
  14155. \begin{lstlisting}
  14156. (let ([x 0])
  14157. (let ([y 0])
  14158. (let ([z 20])
  14159. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14160. (begin
  14161. (set! x 10)
  14162. (set! y 12)
  14163. (f y))))))
  14164. \end{lstlisting}
  14165. \fi}
  14166. {\if\edition\pythonEd
  14167. % box_free_assign.py
  14168. \begin{lstlisting}
  14169. def g(z : int) -> int:
  14170. x = 0
  14171. y = 0
  14172. f : Callable[[int],int] = lambda a: a + x + z
  14173. x = 10
  14174. y = 12
  14175. return f(y)
  14176. print( g(20) )
  14177. \end{lstlisting}
  14178. \fi}
  14179. The correct output for this example is \code{42} because the call to
  14180. \code{f} is required to use the current value of \code{x} (which is
  14181. \code{10}). Unfortunately, the closure conversion pass
  14182. (Section~\ref{sec:closure-conversion}) generates code for the
  14183. \code{lambda} that copies the old value of \code{x} into a
  14184. closure. Thus, if we naively add support for assignment to our current
  14185. compiler, the output of this program would be \code{32}.
  14186. A first attempt at solving this problem would be to save a pointer to
  14187. \code{x} in the closure and change the occurrences of \code{x} inside
  14188. the lambda to dereference the pointer. Of course, this would require
  14189. assigning \code{x} to the stack and not to a register. However, the
  14190. problem goes a bit deeper.
  14191. %% Consider the following example in which we
  14192. %% create a counter abstraction by creating a pair of functions that
  14193. %% share the free variable \code{x}.
  14194. Consider the following example that returns a function that refers to
  14195. a local variable of the enclosing function.
  14196. \begin{center}
  14197. \begin{minipage}{\textwidth}
  14198. {\if\edition\racketEd
  14199. % similar to loop_test_10.rkt
  14200. %% \begin{lstlisting}
  14201. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  14202. %% (vector
  14203. %% (lambda: () : Integer x)
  14204. %% (lambda: () : Void (set! x (+ 1 x)))))
  14205. %% (let ([counter (f 0)])
  14206. %% (let ([get (vector-ref counter 0)])
  14207. %% (let ([inc (vector-ref counter 1)])
  14208. %% (begin
  14209. %% (inc)
  14210. %% (get)))))
  14211. %% \end{lstlisting}
  14212. \begin{lstlisting}
  14213. (define (f []) : Integer
  14214. (let ([x 0])
  14215. (let ([g (lambda: () : Integer x)])
  14216. (begin
  14217. (set! x 42)
  14218. g))))
  14219. ((f))
  14220. \end{lstlisting}
  14221. \fi}
  14222. {\if\edition\pythonEd
  14223. % counter.py
  14224. \begin{lstlisting}
  14225. def f():
  14226. x = 0
  14227. g = lambda: x
  14228. x = 42
  14229. return g
  14230. print( f()() )
  14231. \end{lstlisting}
  14232. \fi}
  14233. \end{minipage}
  14234. \end{center}
  14235. In this example, the lifetime of \code{x} extends beyond the lifetime
  14236. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14237. stack frame for the call to \code{f}, it would be gone by the time we
  14238. call \code{g}, leaving us with dangling pointers for
  14239. \code{x}. This example demonstrates that when a variable occurs free
  14240. inside a function, its lifetime becomes indefinite. Thus, the value of
  14241. the variable needs to live on the heap. The verb
  14242. \emph{box}\index{subject}{box} is often used for allocating a single
  14243. value on the heap, producing a pointer, and
  14244. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14245. %% {\if\edition\racketEd
  14246. %% We recommend solving these problems by boxing the local variables that
  14247. %% are in the intersection of 1) variables that appear on the
  14248. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14249. %% inside a \code{lambda}.
  14250. %% \fi}
  14251. %% {\if\edition\pythonEd
  14252. %% We recommend solving these problems by boxing the local variables that
  14253. %% are in the intersection of 1) variables whose values may change and 2)
  14254. %% variables that occur free inside a \code{lambda}.
  14255. %% \fi}
  14256. We shall introduce a new pass named
  14257. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14258. to address this challenge.
  14259. %
  14260. \racket{But before diving into the compiler passes, we have one more
  14261. problem to discuss.}
  14262. \if\edition\pythonEd
  14263. \section{Uniquify Variables}
  14264. \label{sec:uniquify-lambda}
  14265. With the addition of \code{lambda} we have a complication to deal
  14266. with: name shadowing. Consider the following program with a function
  14267. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14268. \code{lambda} expressions. The first \code{lambda} has a parameter
  14269. that is also named \code{x}.
  14270. \begin{lstlisting}
  14271. def f(x:int, y:int) -> Callable[[int], int]:
  14272. g : Callable[[int],int] = (lambda x: x + y)
  14273. h : Callable[[int],int] = (lambda y: x + y)
  14274. x = input_int()
  14275. return g
  14276. print(f(0, 10)(32))
  14277. \end{lstlisting}
  14278. Many of our compiler passes rely on being able to connect variable
  14279. uses with their definitions using just the name of the variable,
  14280. including new passes in this chapter. However, in the above example
  14281. the name of the variable does not uniquely determine its
  14282. definition. To solve this problem we recommend implementing a pass
  14283. named \code{uniquify} that renames every variable in the program to
  14284. make sure they are all unique.
  14285. The following shows the result of \code{uniquify} for the above
  14286. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14287. and the \code{x} parameter of the \code{lambda} is renamed to
  14288. \code{x\_4}.
  14289. \begin{lstlisting}
  14290. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14291. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14292. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14293. x_0 = input_int()
  14294. return g_2
  14295. def main() -> int :
  14296. print(f(0, 10)(32))
  14297. return 0
  14298. \end{lstlisting}
  14299. \fi
  14300. %% \section{Reveal Functions}
  14301. %% \label{sec:reveal-functions-r5}
  14302. %% \racket{To support the \code{procedure-arity} operator we need to
  14303. %% communicate the arity of a function to the point of closure
  14304. %% creation.}
  14305. %% %
  14306. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14307. %% function at runtime. Thus, we need to communicate the arity of a
  14308. %% function to the point of closure creation.}
  14309. %% %
  14310. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14311. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14312. %% \[
  14313. %% \begin{array}{lcl}
  14314. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14315. %% \end{array}
  14316. %% \]
  14317. \section{Assignment Conversion}
  14318. \label{sec:convert-assignments}
  14319. The purpose of the \code{convert\_assignments} pass is to address the
  14320. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14321. interaction between variable assignments and closure conversion.
  14322. First we identify which variables need to be boxed, then we transform
  14323. the program to box those variables. In general, boxing introduces
  14324. runtime overhead that we would like to avoid, so we should box as few
  14325. variables as possible. We recommend boxing the variables in the
  14326. intersection of the following two sets of variables:
  14327. \begin{enumerate}
  14328. \item The variables that are free in a \code{lambda}.
  14329. \item The variables that appear on the left-hand side of an
  14330. assignment.
  14331. \end{enumerate}
  14332. The first condition is a must, but the second condition is quite conservative and it is possible to
  14333. develop a more liberal condition.
  14334. Consider again the first example from
  14335. Section~\ref{sec:assignment-scoping}:
  14336. %
  14337. {\if\edition\racketEd
  14338. \begin{lstlisting}
  14339. (let ([x 0])
  14340. (let ([y 0])
  14341. (let ([z 20])
  14342. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14343. (begin
  14344. (set! x 10)
  14345. (set! y 12)
  14346. (f y))))))
  14347. \end{lstlisting}
  14348. \fi}
  14349. {\if\edition\pythonEd
  14350. \begin{lstlisting}
  14351. def g(z : int) -> int:
  14352. x = 0
  14353. y = 0
  14354. f : Callable[[int],int] = lambda a: a + x + z
  14355. x = 10
  14356. y = 12
  14357. return f(y)
  14358. print( g(20) )
  14359. \end{lstlisting}
  14360. \fi}
  14361. %
  14362. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14363. variables \code{x} and \code{z} occur free inside the
  14364. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14365. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14366. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14367. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14368. with a tuple write. The output of \code{convert\_assignments} for
  14369. this example is as follows.
  14370. %
  14371. {\if\edition\racketEd
  14372. \begin{lstlisting}
  14373. (define (main) : Integer
  14374. (let ([x0 (vector 0)])
  14375. (let ([y1 0])
  14376. (let ([z2 20])
  14377. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14378. (+ a3 (+ (vector-ref x0 0) z2)))])
  14379. (begin
  14380. (vector-set! x0 0 10)
  14381. (set! y1 12)
  14382. (f4 y1)))))))
  14383. \end{lstlisting}
  14384. \fi}
  14385. %
  14386. {\if\edition\pythonEd
  14387. \begin{lstlisting}
  14388. def g(z : int)-> int:
  14389. x = (uninitialized(int),)
  14390. x[0] = 0
  14391. y = 0
  14392. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14393. x[0] = 10
  14394. y = 12
  14395. return f(y)
  14396. def main() -> int:
  14397. print(g(20))
  14398. return 0
  14399. \end{lstlisting}
  14400. \fi}
  14401. To compute the free variables of all the \code{lambda} expressions, we
  14402. recommend defining two auxiliary functions:
  14403. \begin{enumerate}
  14404. \item \code{free\_variables} computes the free variables of an expression, and
  14405. \item \code{free\_in\_lambda} collects all of the variables that are
  14406. free in any of the \code{lambda} expressions, using
  14407. \code{free\_variables} in the case for each \code{lambda}.
  14408. \end{enumerate}
  14409. {\if\edition\racketEd
  14410. %
  14411. To compute the variables that are assigned-to, we recommend using the
  14412. \code{collect-set!} function that we introduced in
  14413. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14414. forms such as \code{Lambda}.
  14415. %
  14416. \fi}
  14417. {\if\edition\pythonEd
  14418. %
  14419. To compute the variables that are assigned-to, we recommend defining
  14420. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14421. the set of variables that occur in the left-hand side of an assignment
  14422. statement, and otherwise returns the empty set.
  14423. %
  14424. \fi}
  14425. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14426. free in a \code{lambda} and that are assigned-to in the enclosing
  14427. function definition.
  14428. Next we discuss the \code{convert\_assignments} pass. In the case for
  14429. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14430. $\VAR{x}$ to a tuple read.
  14431. %
  14432. {\if\edition\racketEd
  14433. \begin{lstlisting}
  14434. (Var |$x$|)
  14435. |$\Rightarrow$|
  14436. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14437. \end{lstlisting}
  14438. \fi}
  14439. %
  14440. {\if\edition\pythonEd
  14441. \begin{lstlisting}
  14442. Name(|$x$|)
  14443. |$\Rightarrow$|
  14444. Subscript(Name(|$x$|), Constant(0), Load())
  14445. \end{lstlisting}
  14446. \fi}
  14447. %
  14448. %
  14449. In the case for assignment, recursively process the right-hand side
  14450. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14451. the assignment into a tuple-write as follows.
  14452. %
  14453. {\if\edition\racketEd
  14454. \begin{lstlisting}
  14455. (SetBang |$x$| |$\itm{rhs}$|)
  14456. |$\Rightarrow$|
  14457. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14458. \end{lstlisting}
  14459. \fi}
  14460. {\if\edition\pythonEd
  14461. \begin{lstlisting}
  14462. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14463. |$\Rightarrow$|
  14464. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14465. \end{lstlisting}
  14466. \fi}
  14467. %
  14468. {\if\edition\racketEd
  14469. The case for \code{Lambda} is non-trivial, but it is similar to the
  14470. case for function definitions, which we discuss next.
  14471. \fi}
  14472. To translate a function definition, we first compute $\mathit{AF}$,
  14473. the intersection of the variables that are free in a \code{lambda} and
  14474. that are assigned-to. We then apply assignment conversion to the body
  14475. of the function definition. Finally, we box the parameters of this
  14476. function definition that are in $\mathit{AF}$. For example,
  14477. the parameter \code{x} of the following function \code{g}
  14478. needs to be boxed.
  14479. {\if\edition\racketEd
  14480. \begin{lstlisting}
  14481. (define (g [x : Integer]) : Integer
  14482. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14483. (begin
  14484. (set! x 10)
  14485. (f 32))))
  14486. \end{lstlisting}
  14487. \fi}
  14488. %
  14489. {\if\edition\pythonEd
  14490. \begin{lstlisting}
  14491. def g(x : int) -> int:
  14492. f : Callable[[int],int] = lambda a: a + x
  14493. x = 10
  14494. return f(32)
  14495. \end{lstlisting}
  14496. \fi}
  14497. %
  14498. \noindent We box parameter \code{x} by creating a local variable named
  14499. \code{x} that is initialized to a tuple whose contents is the value of
  14500. the parameter, which we has been renamed.
  14501. %
  14502. {\if\edition\racketEd
  14503. \begin{lstlisting}
  14504. (define (g [x_0 : Integer]) : Integer
  14505. (let ([x (vector x_0)])
  14506. (let ([f (lambda: ([a : Integer]) : Integer
  14507. (+ a (vector-ref x 0)))])
  14508. (begin
  14509. (vector-set! x 0 10)
  14510. (f 32)))))
  14511. \end{lstlisting}
  14512. \fi}
  14513. %
  14514. {\if\edition\pythonEd
  14515. \begin{lstlisting}
  14516. def g(x_0 : int)-> int:
  14517. x = (x_0,)
  14518. f : Callable[[int], int] = (lambda a: a + x[0])
  14519. x[0] = 10
  14520. return f(32)
  14521. \end{lstlisting}
  14522. \fi}
  14523. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14524. %% involving a counter abstraction. The following is the output of
  14525. %% assignment version for function \code{f}.
  14526. %% \begin{lstlisting}
  14527. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14528. %% (vector
  14529. %% (lambda: () : Integer x1)
  14530. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14531. %% |$\Rightarrow$|
  14532. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14533. %% (let ([x1 (vector param_x1)])
  14534. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14535. %% (lambda: () : Void
  14536. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14537. %% \end{lstlisting}
  14538. \section{Closure Conversion}
  14539. \label{sec:closure-conversion}
  14540. \index{subject}{closure conversion}
  14541. The compiling of lexically-scoped functions into top-level function
  14542. definitions is accomplished in the pass \code{convert\_to\_closures}
  14543. that comes after \code{reveal\_functions} and before
  14544. \code{limit\_functions}.
  14545. As usual, we implement the pass as a recursive function over the
  14546. AST. The interesting cases are the ones for \key{lambda} and function
  14547. application. We transform a \key{lambda} expression into an expression
  14548. that creates a closure, that is, a tuple whose first element is a
  14549. function pointer and the rest of the elements are the values of the
  14550. free variables of the \key{lambda}.
  14551. %
  14552. However, we use the \code{Closure} AST node instead of using a tuple
  14553. so that we can record the arity.
  14554. %
  14555. In the generated code below, \itm{fvs} is the free variables of the
  14556. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14557. %
  14558. \racket{The \itm{arity} is the number of parameters (the length of
  14559. \itm{ps}).}
  14560. %
  14561. {\if\edition\racketEd
  14562. \begin{lstlisting}
  14563. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14564. |$\Rightarrow$|
  14565. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14566. \end{lstlisting}
  14567. \fi}
  14568. %
  14569. {\if\edition\pythonEd
  14570. \begin{lstlisting}
  14571. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14572. |$\Rightarrow$|
  14573. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14574. \end{lstlisting}
  14575. \fi}
  14576. %
  14577. In addition to transforming each \key{Lambda} AST node into a
  14578. tuple, we create a top-level function definition for each
  14579. \key{Lambda}, as shown below.\\
  14580. \begin{minipage}{0.8\textwidth}
  14581. {\if\edition\racketEd
  14582. \begin{lstlisting}
  14583. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14584. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14585. ...
  14586. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14587. |\itm{body'}|)...))
  14588. \end{lstlisting}
  14589. \fi}
  14590. {\if\edition\pythonEd
  14591. \begin{lstlisting}
  14592. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14593. |$\itm{fvs}_1$| = clos[1]
  14594. |$\ldots$|
  14595. |$\itm{fvs}_n$| = clos[|$n$|]
  14596. |\itm{body'}|
  14597. \end{lstlisting}
  14598. \fi}
  14599. \end{minipage}\\
  14600. The \code{clos} parameter refers to the closure. Translate the type
  14601. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14602. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14603. \itm{closTy} is a tuple type whose first element type is
  14604. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14605. the element types are the types of the free variables in the
  14606. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14607. is non-trivial to give a type to the function in the closure's type.%
  14608. %
  14609. \footnote{To give an accurate type to a closure, we would need to add
  14610. existential types to the type checker~\citep{Minamide:1996ys}.}
  14611. %
  14612. %% The dummy type is considered to be equal to any other type during type
  14613. %% checking.
  14614. The free variables become local variables that are initialized with
  14615. their values in the closure.
  14616. Closure conversion turns every function into a tuple, so the type
  14617. annotations in the program must also be translated. We recommend
  14618. defining an auxiliary recursive function for this purpose. Function
  14619. types should be translated as follows.
  14620. %
  14621. {\if\edition\racketEd
  14622. \begin{lstlisting}
  14623. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14624. |$\Rightarrow$|
  14625. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14626. \end{lstlisting}
  14627. \fi}
  14628. {\if\edition\pythonEd
  14629. \begin{lstlisting}
  14630. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14631. |$\Rightarrow$|
  14632. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14633. \end{lstlisting}
  14634. \fi}
  14635. %
  14636. The above type says that the first thing in the tuple is a
  14637. function. The first parameter of the function is a tuple (a closure)
  14638. and the rest of the parameters are the ones from the original
  14639. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14640. omits the types of the free variables because 1) those types are not
  14641. available in this context and 2) we do not need them in the code that
  14642. is generated for function application. So this type only describes the
  14643. first component of the closure tuple. At runtime the tuple may have
  14644. more components, but we ignore them at this point.
  14645. We transform function application into code that retrieves the
  14646. function from the closure and then calls the function, passing the
  14647. closure as the first argument. We place $e'$ in a temporary variable
  14648. to avoid code duplication.
  14649. \begin{center}
  14650. \begin{minipage}{\textwidth}
  14651. {\if\edition\racketEd
  14652. \begin{lstlisting}
  14653. (Apply |$e$| |$\itm{es}$|)
  14654. |$\Rightarrow$|
  14655. (Let |$\itm{tmp}$| |$e'$|
  14656. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14657. \end{lstlisting}
  14658. \fi}
  14659. %
  14660. {\if\edition\pythonEd
  14661. \begin{lstlisting}
  14662. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14663. |$\Rightarrow$|
  14664. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14665. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14666. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14667. \end{lstlisting}
  14668. \fi}
  14669. \end{minipage}
  14670. \end{center}
  14671. There is also the question of what to do with references to top-level
  14672. function definitions. To maintain a uniform translation of function
  14673. application, we turn function references into closures.
  14674. \begin{tabular}{lll}
  14675. \begin{minipage}{0.3\textwidth}
  14676. {\if\edition\racketEd
  14677. \begin{lstlisting}
  14678. (FunRef |$f$| |$n$|)
  14679. \end{lstlisting}
  14680. \fi}
  14681. {\if\edition\pythonEd
  14682. \begin{lstlisting}
  14683. FunRef(|$f$|, |$n$|)
  14684. \end{lstlisting}
  14685. \fi}
  14686. \end{minipage}
  14687. &
  14688. $\Rightarrow$
  14689. &
  14690. \begin{minipage}{0.5\textwidth}
  14691. {\if\edition\racketEd
  14692. \begin{lstlisting}
  14693. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14694. \end{lstlisting}
  14695. \fi}
  14696. {\if\edition\pythonEd
  14697. \begin{lstlisting}
  14698. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14699. \end{lstlisting}
  14700. \fi}
  14701. \end{minipage}
  14702. \end{tabular} \\
  14703. We no longer need the annotated assignment statement \code{AnnAssign}
  14704. to support the type checking of \code{lambda} expressions, so we
  14705. translate it to a regular \code{Assign} statement.
  14706. The top-level function definitions need to be updated to take an extra
  14707. closure parameter.
  14708. \section{An Example Translation}
  14709. \label{sec:example-lambda}
  14710. Figure~\ref{fig:lexical-functions-example} shows the result of
  14711. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14712. program demonstrating lexical scoping that we discussed at the
  14713. beginning of this chapter.
  14714. \begin{figure}[tbp]
  14715. \begin{minipage}{0.8\textwidth}
  14716. {\if\edition\racketEd
  14717. % tests/lambda_test_6.rkt
  14718. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14719. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14720. (let ([y8 4])
  14721. (lambda: ([z9 : Integer]) : Integer
  14722. (+ x7 (+ y8 z9)))))
  14723. (define (main) : Integer
  14724. (let ([g0 ((fun-ref f6 1) 5)])
  14725. (let ([h1 ((fun-ref f6 1) 3)])
  14726. (+ (g0 11) (h1 15)))))
  14727. \end{lstlisting}
  14728. $\Rightarrow$
  14729. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14730. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14731. (let ([y8 4])
  14732. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14733. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14734. (let ([x7 (vector-ref fvs3 1)])
  14735. (let ([y8 (vector-ref fvs3 2)])
  14736. (+ x7 (+ y8 z9)))))
  14737. (define (main) : Integer
  14738. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14739. ((vector-ref clos5 0) clos5 5))])
  14740. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14741. ((vector-ref clos6 0) clos6 3))])
  14742. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14743. \end{lstlisting}
  14744. \fi}
  14745. %
  14746. {\if\edition\pythonEd
  14747. % free_var.py
  14748. \begin{lstlisting}
  14749. def f(x : int) -> Callable[[int], int]:
  14750. y = 4
  14751. return lambda z: x + y + z
  14752. g = f(5)
  14753. h = f(3)
  14754. print( g(11) + h(15) )
  14755. \end{lstlisting}
  14756. $\Rightarrow$
  14757. \begin{lstlisting}
  14758. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14759. x = fvs_1[1]
  14760. y = fvs_1[2]
  14761. return x + y[0] + z
  14762. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14763. y = (777,)
  14764. y[0] = 4
  14765. return (lambda_0, x, y)
  14766. def main() -> int:
  14767. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14768. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14769. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14770. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14771. return 0
  14772. \end{lstlisting}
  14773. \fi}
  14774. \end{minipage}
  14775. \caption{Example of closure conversion.}
  14776. \label{fig:lexical-functions-example}
  14777. \end{figure}
  14778. \begin{exercise}\normalfont\normalsize
  14779. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14780. Create 5 new programs that use \key{lambda} functions and make use of
  14781. lexical scoping. Test your compiler on these new programs and all of
  14782. your previously created test programs.
  14783. \end{exercise}
  14784. \section{Expose Allocation}
  14785. \label{sec:expose-allocation-r5}
  14786. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14787. that allocates and initializes a tuple, similar to the translation of
  14788. the tuple creation in Section~\ref{sec:expose-allocation}.
  14789. The only difference is replacing the use of
  14790. \ALLOC{\itm{len}}{\itm{type}} with
  14791. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14792. \section{Explicate Control and \LangCLam{}}
  14793. \label{sec:explicate-r5}
  14794. The output language of \code{explicate\_control} is \LangCLam{} whose
  14795. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14796. %
  14797. \racket{The only difference with respect to \LangCFun{} is the
  14798. addition of the \code{AllocateClosure} form to the grammar for
  14799. $\Exp$. The handling of \code{AllocateClosure} in the
  14800. \code{explicate\_control} pass is similar to the handling of other
  14801. expressions such as primitive operators.}
  14802. %
  14803. \python{The differences with respect to \LangCFun{} are the
  14804. additions of \code{Uninitialized}, \code{AllocateClosure},
  14805. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14806. \code{explicate\_control} pass is similar to the handling of other
  14807. expressions such as primitive operators.}
  14808. \newcommand{\ClambdaASTPython}{
  14809. \begin{array}{lcl}
  14810. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14811. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14812. &\MID& \ARITY{\Atm}
  14813. \end{array}
  14814. }
  14815. \begin{figure}[tp]
  14816. \fbox{
  14817. \begin{minipage}{0.96\textwidth}
  14818. \small
  14819. {\if\edition\racketEd
  14820. \[
  14821. \begin{array}{lcl}
  14822. \Exp &::= & \ldots
  14823. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14824. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14825. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14826. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14827. \MID \GOTO{\itm{label}} } \\
  14828. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14829. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14830. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14831. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14832. \end{array}
  14833. \]
  14834. \fi}
  14835. {\if\edition\pythonEd
  14836. \[
  14837. \begin{array}{l}
  14838. \gray{\CifASTPython} \\ \hline
  14839. \gray{\CtupASTPython} \\ \hline
  14840. \gray{\CfunASTPython} \\ \hline
  14841. \ClambdaASTPython \\
  14842. \begin{array}{lcl}
  14843. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14844. \end{array}
  14845. \end{array}
  14846. \]
  14847. \fi}
  14848. \end{minipage}
  14849. }
  14850. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14851. \label{fig:Clam-syntax}
  14852. \end{figure}
  14853. \section{Select Instructions}
  14854. \label{sec:select-instructions-Rlambda}
  14855. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14856. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14857. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14858. that you should place the \itm{arity} in the tag that is stored at
  14859. position $0$ of the vector. Recall that in
  14860. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14861. was not used. We store the arity in the $5$ bits starting at position
  14862. $58$.
  14863. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14864. instructions that access the tag from position $0$ of the vector and
  14865. extract the $5$-bits starting at position $58$ from the tag.}
  14866. %
  14867. \python{Compile a call to the \code{arity} operator to a sequence of
  14868. instructions that access the tag from position $0$ of the tuple
  14869. (representing a closure) and extract the $5$-bits starting at position
  14870. $58$ from the tag.}
  14871. \begin{figure}[p]
  14872. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14873. \node (Lfun) at (0,2) {\large \LangLam{}};
  14874. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  14875. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  14876. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14877. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14878. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14879. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14880. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14881. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14882. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14883. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14884. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14885. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14886. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14887. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14888. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14889. \path[->,bend left=15] (Lfun) edge [above] node
  14890. {\ttfamily\footnotesize shrink} (Lfun-2);
  14891. \path[->,bend left=15] (Lfun-2) edge [above] node
  14892. {\ttfamily\footnotesize uniquify} (Lfun-3);
  14893. \path[->,bend left=15] (Lfun-3) edge [above] node
  14894. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14895. \path[->,bend left=15] (F1-0) edge [right] node
  14896. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14897. \path[->,bend left=15] (F1-1) edge [below] node
  14898. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14899. \path[->,bend right=15] (F1-2) edge [above] node
  14900. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14901. \path[->,bend right=15] (F1-3) edge [above] node
  14902. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14903. \path[->,bend right=15] (F1-4) edge [above] node
  14904. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14905. \path[->,bend right=15] (F1-5) edge [right] node
  14906. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14907. \path[->,bend left=15] (C3-2) edge [left] node
  14908. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14909. \path[->,bend right=15] (x86-2) edge [left] node
  14910. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14911. \path[->,bend right=15] (x86-2-1) edge [below] node
  14912. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14913. \path[->,bend right=15] (x86-2-2) edge [left] node
  14914. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14915. \path[->,bend left=15] (x86-3) edge [above] node
  14916. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14917. \path[->,bend left=15] (x86-4) edge [right] node
  14918. {\ttfamily\footnotesize print\_x86} (x86-5);
  14919. \end{tikzpicture}
  14920. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14921. functions.}
  14922. \label{fig:Rlambda-passes}
  14923. \end{figure}
  14924. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14925. for the compilation of \LangLam{}.
  14926. \clearpage
  14927. \section{Challenge: Optimize Closures}
  14928. \label{sec:optimize-closures}
  14929. In this chapter we compiled lexically-scoped functions into a
  14930. relatively efficient representation: flat closures. However, even this
  14931. representation comes with some overhead. For example, consider the
  14932. following program with a function \code{tail\_sum} that does not have
  14933. any free variables and where all the uses of \code{tail\_sum} are in
  14934. applications where we know that only \code{tail\_sum} is being applied
  14935. (and not any other functions).
  14936. \begin{center}
  14937. \begin{minipage}{0.95\textwidth}
  14938. {\if\edition\racketEd
  14939. \begin{lstlisting}
  14940. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14941. (if (eq? n 0)
  14942. s
  14943. (tail_sum (- n 1) (+ n s))))
  14944. (+ (tail_sum 3 0) 36)
  14945. \end{lstlisting}
  14946. \fi}
  14947. {\if\edition\pythonEd
  14948. \begin{lstlisting}
  14949. def tail_sum(n : int, s : int) -> int:
  14950. if n == 0:
  14951. return s
  14952. else:
  14953. return tail_sum(n - 1, n + s)
  14954. print( tail_sum(3, 0) + 36)
  14955. \end{lstlisting}
  14956. \fi}
  14957. \end{minipage}
  14958. \end{center}
  14959. As described in this chapter, we uniformly apply closure conversion to
  14960. all functions, obtaining the following output for this program.
  14961. \begin{center}
  14962. \begin{minipage}{0.95\textwidth}
  14963. {\if\edition\racketEd
  14964. \begin{lstlisting}
  14965. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14966. (if (eq? n2 0)
  14967. s3
  14968. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  14969. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14970. (define (main) : Integer
  14971. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  14972. ((vector-ref clos6 0) clos6 3 0)) 27))
  14973. \end{lstlisting}
  14974. \fi}
  14975. {\if\edition\pythonEd
  14976. \begin{lstlisting}
  14977. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14978. if n_0 == 0:
  14979. return s_1
  14980. else:
  14981. return (let clos_2 = (tail_sum,)
  14982. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14983. def main() -> int :
  14984. print((let clos_4 = (tail_sum,)
  14985. in clos_4[0](clos_4, 3, 0)) + 36)
  14986. return 0
  14987. \end{lstlisting}
  14988. \fi}
  14989. \end{minipage}
  14990. \end{center}
  14991. In the previous chapter, there would be no allocation in the program
  14992. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14993. the above program allocates memory for each closure and the calls to
  14994. \code{tail\_sum} are indirect. These two differences incur
  14995. considerable overhead in a program such as this one, where the
  14996. allocations and indirect calls occur inside a tight loop.
  14997. One might think that this problem is trivial to solve: can't we just
  14998. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  14999. and compile them to direct calls instead of treating it like a call to
  15000. a closure? We would also drop the new \code{fvs} parameter of
  15001. \code{tail\_sum}.
  15002. %
  15003. However, this problem is not so trivial because a global function may
  15004. ``escape'' and become involved in applications that also involve
  15005. closures. Consider the following example in which the application
  15006. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15007. application, because the \code{lambda} may flow into \code{f}, but the
  15008. \code{inc} function might also flow into \code{f}.
  15009. \begin{center}
  15010. \begin{minipage}{\textwidth}
  15011. % lambda_test_30.rkt
  15012. {\if\edition\racketEd
  15013. \begin{lstlisting}
  15014. (define (inc [x : Integer]) : Integer
  15015. (+ x 1))
  15016. (let ([y (read)])
  15017. (let ([f (if (eq? (read) 0)
  15018. inc
  15019. (lambda: ([x : Integer]) : Integer (- x y)))])
  15020. (f 41)))
  15021. \end{lstlisting}
  15022. \fi}
  15023. {\if\edition\pythonEd
  15024. \begin{lstlisting}
  15025. def add1(x : int) -> int:
  15026. return x + 1
  15027. y = input_int()
  15028. g : Callable[[int], int] = lambda x: x - y
  15029. f = add1 if input_int() == 0 else g
  15030. print( f(41) )
  15031. \end{lstlisting}
  15032. \fi}
  15033. \end{minipage}
  15034. \end{center}
  15035. If a global function name is used in any way other than as the
  15036. operator in a direct call, then we say that the function
  15037. \emph{escapes}. If a global function does not escape, then we do not
  15038. need to perform closure conversion on the function.
  15039. \begin{exercise}\normalfont\normalsize
  15040. Implement an auxiliary function for detecting which global
  15041. functions escape. Using that function, implement an improved version
  15042. of closure conversion that does not apply closure conversion to
  15043. global functions that do not escape but instead compiles them as
  15044. regular functions. Create several new test cases that check whether
  15045. you properly detect whether global functions escape or not.
  15046. \end{exercise}
  15047. So far we have reduced the overhead of calling global functions, but
  15048. it would also be nice to reduce the overhead of calling a
  15049. \code{lambda} when we can determine at compile time which
  15050. \code{lambda} will be called. We refer to such calls as \emph{known
  15051. calls}. Consider the following example in which a \code{lambda} is
  15052. bound to \code{f} and then applied.
  15053. {\if\edition\racketEd
  15054. % lambda_test_9.rkt
  15055. \begin{lstlisting}
  15056. (let ([y (read)])
  15057. (let ([f (lambda: ([x : Integer]) : Integer
  15058. (+ x y))])
  15059. (f 21)))
  15060. \end{lstlisting}
  15061. \fi}
  15062. {\if\edition\pythonEd
  15063. \begin{lstlisting}
  15064. y = input_int()
  15065. f : Callable[[int],int] = lambda x: x + y
  15066. print( f(21) )
  15067. \end{lstlisting}
  15068. \fi}
  15069. %
  15070. \noindent Closure conversion compiles the application
  15071. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15072. %
  15073. {\if\edition\racketEd
  15074. \begin{lstlisting}
  15075. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15076. (let ([y2 (vector-ref fvs6 1)])
  15077. (+ x3 y2)))
  15078. (define (main) : Integer
  15079. (let ([y2 (read)])
  15080. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15081. ((vector-ref f4 0) f4 21))))
  15082. \end{lstlisting}
  15083. \fi}
  15084. {\if\edition\pythonEd
  15085. \begin{lstlisting}
  15086. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15087. y_1 = fvs_4[1]
  15088. return x_2 + y_1[0]
  15089. def main() -> int:
  15090. y_1 = (777,)
  15091. y_1[0] = input_int()
  15092. f_0 = (lambda_3, y_1)
  15093. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15094. return 0
  15095. \end{lstlisting}
  15096. \fi}
  15097. %
  15098. \noindent but we can instead compile the application
  15099. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15100. %
  15101. {\if\edition\racketEd
  15102. \begin{lstlisting}
  15103. (define (main) : Integer
  15104. (let ([y2 (read)])
  15105. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15106. ((fun-ref lambda5 1) f4 21))))
  15107. \end{lstlisting}
  15108. \fi}
  15109. {\if\edition\pythonEd
  15110. \begin{lstlisting}
  15111. def main() -> int:
  15112. y_1 = (777,)
  15113. y_1[0] = input_int()
  15114. f_0 = (lambda_3, y_1)
  15115. print(lambda_3(f_0, 21))
  15116. return 0
  15117. \end{lstlisting}
  15118. \fi}
  15119. The problem of determining which \code{lambda} will be called from a
  15120. particular application is quite challenging in general and the topic
  15121. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15122. following exercise we recommend that you compile an application to a
  15123. direct call when the operator is a variable and \racket{the variable
  15124. is \code{let}-bound to a closure} \python{the previous assignment to
  15125. the variable is a closure}. This can be accomplished by maintaining
  15126. an environment mapping variables to function names. Extend the
  15127. environment whenever you encounter a closure on the right-hand side of
  15128. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15129. name of the global function for the closure. This pass should come
  15130. after closure conversion.
  15131. \begin{exercise}\normalfont\normalsize
  15132. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15133. compiles known calls into direct calls. Verify that your compiler is
  15134. successful in this regard on several example programs.
  15135. \end{exercise}
  15136. These exercises only scratches the surface of optimizing of
  15137. closures. A good next step for the interested reader is to look at the
  15138. work of \citet{Keep:2012ab}.
  15139. \section{Further Reading}
  15140. The notion of lexically scoped functions predates modern computers by
  15141. about a decade. They were invented by \citet{Church:1932aa}, who
  15142. proposed the lambda calculus as a foundation for logic. Anonymous
  15143. functions were included in the LISP~\citep{McCarthy:1960dz}
  15144. programming language but were initially dynamically scoped. The Scheme
  15145. dialect of LISP adopted lexical scoping and
  15146. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15147. Scheme programs. However, environments were represented as linked
  15148. lists, so variable lookup was linear in the size of the
  15149. environment. \citet{Appel91} gives a detailed description of several
  15150. closure representations. In this chapter we represent environments
  15151. using flat closures, which were invented by
  15152. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15153. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15154. closures, variable lookup is constant time but the time to create a
  15155. closure is proportional to the number of its free variables. Flat
  15156. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15157. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15158. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15159. \chapter{Dynamic Typing}
  15160. \label{ch:Ldyn}
  15161. \index{subject}{dynamic typing}
  15162. In this chapter we discuss the compilation of \LangDyn{}, a
  15163. dynamically typed language that is a subset of
  15164. \racket{Racket}\python{Python}. The dynamic typing is in contrast to
  15165. the previous chapters, which have studied the compilation of
  15166. statically typed languages. In dynamically typed languages such as
  15167. \LangDyn{}, a particular expression may produce a value of a different
  15168. type each time it is executed. Consider the following example with a
  15169. conditional \code{if} expression that may return a Boolean or an
  15170. integer depending on the input to the program.
  15171. % part of dynamic_test_25.rkt
  15172. {\if\edition\racketEd
  15173. \begin{lstlisting}
  15174. (not (if (eq? (read) 1) #f 0))
  15175. \end{lstlisting}
  15176. \fi}
  15177. {\if\edition\pythonEd
  15178. \begin{lstlisting}
  15179. not (False if input_int() == 1 else 0)
  15180. \end{lstlisting}
  15181. \fi}
  15182. Languages that allow expressions to produce different kinds of values
  15183. are called \emph{polymorphic}, a word composed of the Greek roots
  15184. ``poly'', meaning ``many'', and ``morphos'', meaning ``form''. There
  15185. are several kinds of polymorphism in programming languages, such as
  15186. subtype polymorphism and parametric
  15187. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15188. study in this chapter does not have a special name but it is the kind
  15189. that arises in dynamically typed languages.
  15190. Another characteristic of dynamically typed languages is that
  15191. primitive operations, such as \code{not}, are often defined to operate
  15192. on many different types of values. In fact, in
  15193. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15194. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15195. given anything else it returns \FALSE{}.
  15196. Furthermore, even when primitive operations restrict their inputs to
  15197. values of a certain type, this restriction is enforced at runtime
  15198. instead of during compilation. For example, the tuple read
  15199. operation
  15200. \racket{\code{(vector-ref \#t 0)}}
  15201. \python{\code{True[0]}}
  15202. results in a run-time error because the first argument must
  15203. be a tuple, not a Boolean.
  15204. \begin{figure}[tp]
  15205. \centering
  15206. \fbox{
  15207. \begin{minipage}{0.97\textwidth}
  15208. {\if\edition\racketEd
  15209. \[
  15210. \begin{array}{rcl}
  15211. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  15212. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15213. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  15214. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  15215. &\MID& \key{\#t} \MID \key{\#f}
  15216. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  15217. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  15218. \MID \CUNIOP{\key{not}}{\Exp} \\
  15219. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15220. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  15221. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  15222. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  15223. &\MID& \LP\Exp \; \Exp\ldots\RP
  15224. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15225. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15226. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15227. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  15228. \LangDynM{} &::=& \Def\ldots\; \Exp
  15229. \end{array}
  15230. \]
  15231. \fi}
  15232. {\if\edition\pythonEd
  15233. \[
  15234. \begin{array}{rcl}
  15235. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15236. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15237. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15238. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15239. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15240. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15241. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15242. \MID \CLEN{\Exp} \\
  15243. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15244. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15245. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15246. \MID \Var\mathop{\key{=}}\Exp \\
  15247. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15248. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15249. &\MID& \CRETURN{\Exp} \\
  15250. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15251. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15252. \end{array}
  15253. \]
  15254. \fi}
  15255. \end{minipage}
  15256. }
  15257. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15258. \label{fig:r7-concrete-syntax}
  15259. \end{figure}
  15260. \begin{figure}[tp]
  15261. \centering
  15262. \fbox{
  15263. \begin{minipage}{0.96\textwidth}
  15264. \small
  15265. {\if\edition\racketEd
  15266. \[
  15267. \begin{array}{lcl}
  15268. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15269. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15270. &\MID& \BOOL{\itm{bool}}
  15271. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15272. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15273. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15274. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15275. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15276. \end{array}
  15277. \]
  15278. \fi}
  15279. {\if\edition\pythonEd
  15280. \[
  15281. \begin{array}{rcl}
  15282. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15283. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15284. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15285. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15286. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15287. &\MID & \code{Is()} \\
  15288. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15289. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15290. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15291. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15292. \MID \VAR{\Var{}} \\
  15293. &\MID& \BOOL{\itm{bool}}
  15294. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15295. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15296. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15297. &\MID& \LEN{\Exp} \\
  15298. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15299. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15300. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15301. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15302. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15303. &\MID& \RETURN{\Exp} \\
  15304. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15305. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15306. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15307. \end{array}
  15308. \]
  15309. \fi}
  15310. \end{minipage}
  15311. }
  15312. \caption{The abstract syntax of \LangDyn{}.}
  15313. \label{fig:r7-syntax}
  15314. \end{figure}
  15315. The concrete and abstract syntax of \LangDyn{} is defined in
  15316. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15317. %
  15318. There is no type checker for \LangDyn{} because dynamically typed
  15319. languages check types at runtime.
  15320. The definitional interpreter for \LangDyn{} is presented in
  15321. \racket{Figure~\ref{fig:interp-Ldyn}}
  15322. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15323. and its auxiliary functions are defined in
  15324. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15325. \INT{n}. Instead of simply returning the integer \code{n} (as
  15326. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15327. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15328. value} that combines an underlying value with a tag that identifies
  15329. what kind of value it is. We define the following \racket{struct}\python{class}
  15330. to represented tagged values.
  15331. %
  15332. {\if\edition\racketEd
  15333. \begin{lstlisting}
  15334. (struct Tagged (value tag) #:transparent)
  15335. \end{lstlisting}
  15336. \fi}
  15337. {\if\edition\pythonEd
  15338. \begin{minipage}{\textwidth}
  15339. \begin{lstlisting}
  15340. @dataclass(eq=True)
  15341. class Tagged(Value):
  15342. value : Value
  15343. tag : str
  15344. def __str__(self):
  15345. return str(self.value)
  15346. \end{lstlisting}
  15347. \end{minipage}
  15348. \fi}
  15349. %
  15350. \racket{The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15351. \code{Vector}, and \code{Procedure}.}
  15352. %
  15353. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15354. \code{'tuple'}, and \code{'function'}.}
  15355. %
  15356. Tags are closely related to types but don't always capture all the
  15357. information that a type does.
  15358. %
  15359. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15360. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15361. Any)} is tagged with \code{Procedure}.}
  15362. %
  15363. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15364. is tagged with \code{'tuple'} and a function of type
  15365. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15366. is tagged with \code{'function'}.}
  15367. Next consider the match case for accessing the element of a tuple.
  15368. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15369. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15370. argument is a tuple and the second is an integer.
  15371. \racket{
  15372. If they are not, a \code{trapped-error} is raised. Recall from
  15373. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15374. raises a \code{trapped-error} error, the compiled code must also
  15375. signal an error by exiting with return code \code{255}. A
  15376. \code{trapped-error} is also raised if the index is not less than the
  15377. length of the vector.
  15378. }
  15379. %
  15380. \python{If they are not, an exception is raised. The compiled code
  15381. must also signal an error by exiting with return code \code{255}. A
  15382. exception is also raised if the index is not less than the length of the
  15383. tuple or if it is negative.}
  15384. \begin{figure}[tbp]
  15385. {\if\edition\racketEd
  15386. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15387. (define ((interp-Rdyn-exp env) ast)
  15388. (define recur (interp-Rdyn-exp env))
  15389. (match ast
  15390. [(Var x) (lookup x env)]
  15391. [(Int n) (Tagged n 'Integer)]
  15392. [(Bool b) (Tagged b 'Boolean)]
  15393. [(Lambda xs rt body)
  15394. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15395. [(Prim 'vector es)
  15396. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15397. [(Prim 'vector-ref (list e1 e2))
  15398. (define vec (recur e1)) (define i (recur e2))
  15399. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15400. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15401. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15402. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15403. [(Prim 'vector-set! (list e1 e2 e3))
  15404. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15405. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15406. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15407. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15408. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15409. (Tagged (void) 'Void)]
  15410. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15411. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15412. [(Prim 'or (list e1 e2))
  15413. (define v1 (recur e1))
  15414. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15415. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15416. [(Prim op (list e1))
  15417. #:when (set-member? type-predicates op)
  15418. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15419. [(Prim op es)
  15420. (define args (map recur es))
  15421. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15422. (unless (for/or ([expected-tags (op-tags op)])
  15423. (equal? expected-tags tags))
  15424. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15425. (tag-value
  15426. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15427. [(If q t f)
  15428. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15429. [(Apply f es)
  15430. (define new-f (recur f)) (define args (map recur es))
  15431. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15432. (match f-val
  15433. [`(function ,xs ,body ,lam-env)
  15434. (unless (eq? (length xs) (length args))
  15435. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15436. (define new-env (append (map cons xs args) lam-env))
  15437. ((interp-Rdyn-exp new-env) body)]
  15438. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15439. \end{lstlisting}
  15440. \fi}
  15441. {\if\edition\pythonEd
  15442. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15443. class InterpLdyn(InterpLlambda):
  15444. def interp_exp(self, e, env):
  15445. match e:
  15446. case Constant(n):
  15447. return self.tag(super().interp_exp(e, env))
  15448. case Tuple(es, Load()):
  15449. return self.tag(super().interp_exp(e, env))
  15450. case Lambda(params, body):
  15451. return self.tag(super().interp_exp(e, env))
  15452. case Call(Name('input_int'), []):
  15453. return self.tag(super().interp_exp(e, env))
  15454. case BinOp(left, Add(), right):
  15455. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15456. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15457. case BinOp(left, Sub(), right):
  15458. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15459. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15460. case UnaryOp(USub(), e1):
  15461. v = self.interp_exp(e1, env)
  15462. return self.tag(- self.untag(v, 'int', e))
  15463. case IfExp(test, body, orelse):
  15464. v = self.interp_exp(test, env)
  15465. if self.untag(v, 'bool', e):
  15466. return self.interp_exp(body, env)
  15467. else:
  15468. return self.interp_exp(orelse, env)
  15469. case UnaryOp(Not(), e1):
  15470. v = self.interp_exp(e1, env)
  15471. return self.tag(not self.untag(v, 'bool', e))
  15472. case BoolOp(And(), values):
  15473. left = values[0]; right = values[1]
  15474. l = self.interp_exp(left, env)
  15475. if self.untag(l, 'bool', e):
  15476. return self.interp_exp(right, env)
  15477. else:
  15478. return self.tag(False)
  15479. case BoolOp(Or(), values):
  15480. left = values[0]; right = values[1]
  15481. l = self.interp_exp(left, env)
  15482. if self.untag(l, 'bool', e):
  15483. return self.tag(True)
  15484. else:
  15485. return self.interp_exp(right, env)
  15486. case Compare(left, [cmp], [right]):
  15487. l = self.interp_exp(left, env)
  15488. r = self.interp_exp(right, env)
  15489. if l.tag == r.tag:
  15490. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15491. else:
  15492. raise Exception('interp Compare unexpected ' \
  15493. + repr(l) + ' ' + repr(r))
  15494. case Subscript(tup, index, Load()):
  15495. t = self.interp_exp(tup, env)
  15496. n = self.interp_exp(index, env)
  15497. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15498. case Call(Name('len'), [tup]):
  15499. t = self.interp_exp(tup, env)
  15500. return self.tag(len(self.untag(t, 'tuple', e)))
  15501. case _:
  15502. return self.tag(super().interp_exp(e, env))
  15503. \end{lstlisting}
  15504. \fi}
  15505. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  15506. \label{fig:interp-Ldyn}
  15507. \end{figure}
  15508. \begin{figure}[tbp]
  15509. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15510. class InterpLdyn(InterpLlambda):
  15511. def interp_stmts(self, ss, env):
  15512. if len(ss) == 0:
  15513. return
  15514. match ss[0]:
  15515. case If(test, body, orelse):
  15516. v = self.interp_exp(test, env)
  15517. if self.untag(v, 'bool', ss[0]):
  15518. return self.interp_stmts(body + ss[1:], env)
  15519. else:
  15520. return self.interp_stmts(orelse + ss[1:], env)
  15521. case While(test, body, []):
  15522. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15523. self.interp_stmts(body, env)
  15524. return self.interp_stmts(ss[1:], env)
  15525. case Assign([Subscript(tup, index)], value):
  15526. tup = self.interp_exp(tup, env)
  15527. index = self.interp_exp(index, env)
  15528. tup_v = self.untag(tup, 'tuple', ss[0])
  15529. index_v = self.untag(index, 'int', ss[0])
  15530. tup_v[index_v] = self.interp_exp(value, env)
  15531. return self.interp_stmts(ss[1:], env)
  15532. case FunctionDef(name, params, bod, dl, returns, comment):
  15533. ps = [x for (x,t) in params]
  15534. env[name] = self.tag(Function(name, ps, bod, env))
  15535. return self.interp_stmts(ss[1:], env)
  15536. case _:
  15537. return super().interp_stmts(ss, env)
  15538. \end{lstlisting}
  15539. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  15540. \label{fig:interp-Ldyn-2}
  15541. \end{figure}
  15542. \begin{figure}[tbp]
  15543. {\if\edition\racketEd
  15544. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15545. (define (interp-op op)
  15546. (match op
  15547. ['+ fx+]
  15548. ['- fx-]
  15549. ['read read-fixnum]
  15550. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15551. ['< (lambda (v1 v2)
  15552. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15553. ['<= (lambda (v1 v2)
  15554. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15555. ['> (lambda (v1 v2)
  15556. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15557. ['>= (lambda (v1 v2)
  15558. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15559. ['boolean? boolean?]
  15560. ['integer? fixnum?]
  15561. ['void? void?]
  15562. ['vector? vector?]
  15563. ['vector-length vector-length]
  15564. ['procedure? (match-lambda
  15565. [`(functions ,xs ,body ,env) #t] [else #f])]
  15566. [else (error 'interp-op "unknown operator" op)]))
  15567. (define (op-tags op)
  15568. (match op
  15569. ['+ '((Integer Integer))]
  15570. ['- '((Integer Integer) (Integer))]
  15571. ['read '(())]
  15572. ['not '((Boolean))]
  15573. ['< '((Integer Integer))]
  15574. ['<= '((Integer Integer))]
  15575. ['> '((Integer Integer))]
  15576. ['>= '((Integer Integer))]
  15577. ['vector-length '((Vector))]))
  15578. (define type-predicates
  15579. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15580. (define (tag-value v)
  15581. (cond [(boolean? v) (Tagged v 'Boolean)]
  15582. [(fixnum? v) (Tagged v 'Integer)]
  15583. [(procedure? v) (Tagged v 'Procedure)]
  15584. [(vector? v) (Tagged v 'Vector)]
  15585. [(void? v) (Tagged v 'Void)]
  15586. [else (error 'tag-value "unidentified value ~a" v)]))
  15587. (define (check-tag val expected ast)
  15588. (define tag (Tagged-tag val))
  15589. (unless (eq? tag expected)
  15590. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15591. \end{lstlisting}
  15592. \fi}
  15593. {\if\edition\pythonEd
  15594. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15595. class InterpLdyn(InterpLlambda):
  15596. def tag(self, v):
  15597. if v is True or v is False:
  15598. return Tagged(v, 'bool')
  15599. elif isinstance(v, int):
  15600. return Tagged(v, 'int')
  15601. elif isinstance(v, Function):
  15602. return Tagged(v, 'function')
  15603. elif isinstance(v, tuple):
  15604. return Tagged(v, 'tuple')
  15605. elif isinstance(v, type(None)):
  15606. return Tagged(v, 'none')
  15607. else:
  15608. raise Exception('tag: unexpected ' + repr(v))
  15609. def untag(self, v, expected_tag, ast):
  15610. match v:
  15611. case Tagged(val, tag) if tag == expected_tag:
  15612. return val
  15613. case _:
  15614. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15615. def apply_fun(self, fun, args, e):
  15616. f = self.untag(fun, 'function', e)
  15617. return super().apply_fun(f, args, e)
  15618. \end{lstlisting}
  15619. \fi}
  15620. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15621. \label{fig:interp-Ldyn-aux}
  15622. \end{figure}
  15623. \clearpage
  15624. \section{Representation of Tagged Values}
  15625. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15626. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15627. values at the bit level. Because almost every operation in \LangDyn{}
  15628. involves manipulating tagged values, the representation must be
  15629. efficient. Recall that all of our values are 64 bits. We shall steal
  15630. the 3 right-most bits to encode the tag. We use $001$ to identify
  15631. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15632. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  15633. function for mapping types to tag codes.
  15634. {\if\edition\racketEd
  15635. \begin{align*}
  15636. \itm{tagof}(\key{Integer}) &= 001 \\
  15637. \itm{tagof}(\key{Boolean}) &= 100 \\
  15638. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15639. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15640. \itm{tagof}(\key{Void}) &= 101
  15641. \end{align*}
  15642. \fi}
  15643. {\if\edition\pythonEd
  15644. \begin{align*}
  15645. \itm{tagof}(\key{IntType()}) &= 001 \\
  15646. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15647. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15648. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15649. \itm{tagof}(\key{type(None)}) &= 101
  15650. \end{align*}
  15651. \fi}
  15652. This stealing of 3 bits comes at some price: integers are now restricted
  15653. to the range from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15654. affect vectors and procedures because those values are addresses, and
  15655. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15656. they are always $000$. Thus, we do not lose information by overwriting
  15657. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15658. to recover the original address.
  15659. To make tagged values into first-class entities, we can give them a
  15660. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define operations
  15661. such as \code{Inject} and \code{Project} for creating and using them,
  15662. yielding the \LangAny{} intermediate language. We describe how to
  15663. compile \LangDyn{} to \LangAny{} in Section~\ref{sec:compile-r7}
  15664. but first we describe the \LangAny{} language in greater detail.
  15665. \section{The \LangAny{} Language}
  15666. \label{sec:Rany-lang}
  15667. \newcommand{\LanyASTRacket}{
  15668. \begin{array}{lcl}
  15669. \Type &::= & \key{Any} \\
  15670. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15671. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15672. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15673. \itm{op} &::= & \code{any-vector-length}
  15674. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15675. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15676. \MID \code{procedure?} \MID \code{void?} \\
  15677. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15678. \end{array}
  15679. }
  15680. \newcommand{\LanyASTPython}{
  15681. \begin{array}{lcl}
  15682. \Type &::= & \key{AnyType()} \\
  15683. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15684. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15685. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15686. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15687. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\INT{n}\RS}\\
  15688. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS}
  15689. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15690. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15691. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15692. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15693. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15694. \end{array}
  15695. }
  15696. \begin{figure}[tp]
  15697. \centering
  15698. \fbox{
  15699. \begin{minipage}{0.96\textwidth}
  15700. \small
  15701. {\if\edition\racketEd
  15702. \[
  15703. \begin{array}{l}
  15704. \gray{\LintOpAST} \\ \hline
  15705. \gray{\LvarASTRacket{}} \\ \hline
  15706. \gray{\LifASTRacket{}} \\ \hline
  15707. \gray{\LwhileASTRacket{}} \\ \hline
  15708. \gray{\LtupASTRacket{}} \\ \hline
  15709. \gray{\LfunASTRacket} \\ \hline
  15710. \gray{\LlambdaASTRacket} \\ \hline
  15711. \LanyASTRacket \\
  15712. \begin{array}{lcl}
  15713. %% \Type &::= & \ldots \MID \key{Any} \\
  15714. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15715. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15716. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15717. %% \MID \code{procedure?} \MID \code{void?} \\
  15718. %% \Exp &::=& \ldots
  15719. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15720. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15721. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15722. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15723. \end{array}
  15724. \end{array}
  15725. \]
  15726. \fi}
  15727. {\if\edition\pythonEd
  15728. \[
  15729. \begin{array}{l}
  15730. \gray{\LintASTPython} \\ \hline
  15731. \gray{\LvarASTPython{}} \\ \hline
  15732. \gray{\LifASTPython{}} \\ \hline
  15733. \gray{\LwhileASTPython{}} \\ \hline
  15734. \gray{\LtupASTPython{}} \\ \hline
  15735. \gray{\LfunASTPython} \\ \hline
  15736. \gray{\LlambdaASTPython} \\ \hline
  15737. \LanyASTPython \\
  15738. \begin{array}{lcl}
  15739. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15740. \end{array}
  15741. \end{array}
  15742. \]
  15743. \fi}
  15744. \end{minipage}
  15745. }
  15746. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15747. \label{fig:Rany-syntax}
  15748. \end{figure}
  15749. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15750. \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15751. Figure~\ref{fig:Rany-concrete-syntax}.)} The $\INJECT{e}{T}$ form
  15752. converts the value produced by expression $e$ of type $T$ into a
  15753. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15754. produced by expression $e$ into a value of type $T$ or halts the
  15755. program if the type tag does not match $T$.
  15756. %
  15757. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15758. restricted to a flat type $\FType$, which simplifies the
  15759. implementation and corresponds with the needs for compiling \LangDyn{}.
  15760. The \racket{\code{any-vector}} operators
  15761. \python{\code{any\_tuple\_load} and \code{any\_len}}
  15762. adapt the tuple operations so that they can be applied to a value of
  15763. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  15764. tuple operations in that the index is not restricted to be a literal
  15765. integer in the grammar but is allowed to be any expression.
  15766. \racket{The type predicates such as
  15767. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15768. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  15769. the predicate and they return {\FALSE} otherwise.}
  15770. The type checker for \LangAny{} is shown in
  15771. Figure~\ref{fig:type-check-Rany}
  15772. %
  15773. \racket{ and uses the auxiliary functions in
  15774. Figure~\ref{fig:type-check-Rany-aux}}.
  15775. %
  15776. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Lany} and
  15777. its auxiliary functions are in Figure~\ref{fig:interp-Lany-aux}.
  15778. \begin{figure}[btp]
  15779. {\if\edition\racketEd
  15780. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15781. (define type-check-Rany-class
  15782. (class type-check-Rlambda-class
  15783. (super-new)
  15784. (inherit check-type-equal?)
  15785. (define/override (type-check-exp env)
  15786. (lambda (e)
  15787. (define recur (type-check-exp env))
  15788. (match e
  15789. [(Inject e1 ty)
  15790. (unless (flat-ty? ty)
  15791. (error 'type-check "may only inject from flat type, not ~a" ty))
  15792. (define-values (new-e1 e-ty) (recur e1))
  15793. (check-type-equal? e-ty ty e)
  15794. (values (Inject new-e1 ty) 'Any)]
  15795. [(Project e1 ty)
  15796. (unless (flat-ty? ty)
  15797. (error 'type-check "may only project to flat type, not ~a" ty))
  15798. (define-values (new-e1 e-ty) (recur e1))
  15799. (check-type-equal? e-ty 'Any e)
  15800. (values (Project new-e1 ty) ty)]
  15801. [(Prim 'any-vector-length (list e1))
  15802. (define-values (e1^ t1) (recur e1))
  15803. (check-type-equal? t1 'Any e)
  15804. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15805. [(Prim 'any-vector-ref (list e1 e2))
  15806. (define-values (e1^ t1) (recur e1))
  15807. (define-values (e2^ t2) (recur e2))
  15808. (check-type-equal? t1 'Any e)
  15809. (check-type-equal? t2 'Integer e)
  15810. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15811. [(Prim 'any-vector-set! (list e1 e2 e3))
  15812. (define-values (e1^ t1) (recur e1))
  15813. (define-values (e2^ t2) (recur e2))
  15814. (define-values (e3^ t3) (recur e3))
  15815. (check-type-equal? t1 'Any e)
  15816. (check-type-equal? t2 'Integer e)
  15817. (check-type-equal? t3 'Any e)
  15818. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15819. [(ValueOf e ty)
  15820. (define-values (new-e e-ty) (recur e))
  15821. (values (ValueOf new-e ty) ty)]
  15822. [(Prim pred (list e1))
  15823. #:when (set-member? (type-predicates) pred)
  15824. (define-values (new-e1 e-ty) (recur e1))
  15825. (check-type-equal? e-ty 'Any e)
  15826. (values (Prim pred (list new-e1)) 'Boolean)]
  15827. [(If cnd thn els)
  15828. (define-values (cnd^ Tc) (recur cnd))
  15829. (define-values (thn^ Tt) (recur thn))
  15830. (define-values (els^ Te) (recur els))
  15831. (check-type-equal? Tc 'Boolean cnd)
  15832. (check-type-equal? Tt Te e)
  15833. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15834. [(Exit) (values (Exit) '_)]
  15835. [(Prim 'eq? (list arg1 arg2))
  15836. (define-values (e1 t1) (recur arg1))
  15837. (define-values (e2 t2) (recur arg2))
  15838. (match* (t1 t2)
  15839. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15840. [(other wise) (check-type-equal? t1 t2 e)])
  15841. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15842. [else ((super type-check-exp env) e)])))
  15843. ))
  15844. \end{lstlisting}
  15845. \fi}
  15846. {\if\edition\pythonEd
  15847. \begin{lstlisting}
  15848. class TypeCheckLany(TypeCheckLlambda):
  15849. def type_check_exp(self, e, env):
  15850. match e:
  15851. case Inject(value, typ):
  15852. self.check_exp(value, typ, env)
  15853. return AnyType()
  15854. case Project(value, typ):
  15855. self.check_exp(value, AnyType(), env)
  15856. return typ
  15857. case Call(Name('any_tuple_load'), [tup, index]):
  15858. self.check_exp(tup, AnyType(), env)
  15859. return AnyType()
  15860. case Call(Name('any_len'), [tup]):
  15861. self.check_exp(tup, AnyType(), env)
  15862. return IntType()
  15863. case Call(Name('arity'), [fun]):
  15864. ty = self.type_check_exp(fun, env)
  15865. match ty:
  15866. case FunctionType(ps, rt):
  15867. return IntType()
  15868. case TupleType([FunctionType(ps,rs)]):
  15869. return IntType()
  15870. case _:
  15871. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15872. case Call(Name('make_any'), [value, tag]):
  15873. self.type_check_exp(value, env)
  15874. self.check_exp(tag, IntType(), env)
  15875. return AnyType()
  15876. case ValueOf(value, typ):
  15877. self.check_exp(value, AnyType(), env)
  15878. return typ
  15879. case TagOf(value):
  15880. self.check_exp(value, AnyType(), env)
  15881. return IntType()
  15882. case Call(Name('exit'), []):
  15883. return Bottom()
  15884. case AnnLambda(params, returns, body):
  15885. new_env = {x:t for (x,t) in env.items()}
  15886. for (x,t) in params:
  15887. new_env[x] = t
  15888. return_t = self.type_check_exp(body, new_env)
  15889. self.check_type_equal(returns, return_t, e)
  15890. return FunctionType([t for (x,t) in params], return_t)
  15891. case _:
  15892. return super().type_check_exp(e, env)
  15893. \end{lstlisting}
  15894. \fi}
  15895. \caption{Type checker for the \LangAny{} language.}
  15896. \label{fig:type-check-Rany}
  15897. \end{figure}
  15898. {\if\edition\racketEd
  15899. \begin{figure}[tbp]
  15900. {\if\edition\racketEd
  15901. \begin{lstlisting}
  15902. (define/override (operator-types)
  15903. (append
  15904. '((integer? . ((Any) . Boolean))
  15905. (vector? . ((Any) . Boolean))
  15906. (procedure? . ((Any) . Boolean))
  15907. (void? . ((Any) . Boolean))
  15908. (tag-of-any . ((Any) . Integer))
  15909. (make-any . ((_ Integer) . Any)))
  15910. (super operator-types)))
  15911. (define/public (type-predicates)
  15912. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15913. (define/public (combine-types t1 t2)
  15914. (match (list t1 t2)
  15915. [(list '_ t2) t2]
  15916. [(list t1 '_) t1]
  15917. [(list `(Vector ,ts1 ...)
  15918. `(Vector ,ts2 ...))
  15919. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15920. (combine-types t1 t2)))]
  15921. [(list `(,ts1 ... -> ,rt1)
  15922. `(,ts2 ... -> ,rt2))
  15923. `(,@(for/list ([t1 ts1] [t2 ts2])
  15924. (combine-types t1 t2))
  15925. -> ,(combine-types rt1 rt2))]
  15926. [else t1]))
  15927. (define/public (flat-ty? ty)
  15928. (match ty
  15929. [(or `Integer `Boolean '_ `Void) #t]
  15930. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15931. [`(,ts ... -> ,rt)
  15932. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15933. [else #f]))
  15934. \end{lstlisting}
  15935. \fi}
  15936. \caption{Auxiliary methods for type checking \LangAny{}.}
  15937. \label{fig:type-check-Rany-aux}
  15938. \end{figure}
  15939. \fi}
  15940. \begin{figure}[btp]
  15941. {\if\edition\racketEd
  15942. \begin{lstlisting}
  15943. (define interp-Lany-class
  15944. (class interp-Llambda-class
  15945. (super-new)
  15946. (define/override (interp-op op)
  15947. (match op
  15948. ['boolean? (match-lambda
  15949. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15950. [else #f])]
  15951. ['integer? (match-lambda
  15952. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15953. [else #f])]
  15954. ['vector? (match-lambda
  15955. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15956. [else #f])]
  15957. ['procedure? (match-lambda
  15958. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15959. [else #f])]
  15960. ['eq? (match-lambda*
  15961. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15962. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15963. [ls (apply (super interp-op op) ls)])]
  15964. ['any-vector-ref (lambda (v i)
  15965. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15966. ['any-vector-set! (lambda (v i a)
  15967. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15968. ['any-vector-length (lambda (v)
  15969. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15970. [else (super interp-op op)]))
  15971. (define/override ((interp-exp env) e)
  15972. (define recur (interp-exp env))
  15973. (match e
  15974. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15975. [(Project e ty2) (apply-project (recur e) ty2)]
  15976. [else ((super interp-exp env) e)]))
  15977. ))
  15978. (define (interp-Lany p)
  15979. (send (new interp-Lany-class) interp-program p))
  15980. \end{lstlisting}
  15981. \fi}
  15982. {\if\edition\pythonEd
  15983. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15984. class InterpLany(InterpLlambda):
  15985. def interp_exp(self, e, env):
  15986. match e:
  15987. case Inject(value, typ):
  15988. v = self.interp_exp(value, env)
  15989. return Tagged(v, self.type_to_tag(typ))
  15990. case Project(value, typ):
  15991. v = self.interp_exp(value, env)
  15992. match v:
  15993. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  15994. return val
  15995. case _:
  15996. raise Exception('interp project to ' + repr(typ) \
  15997. + ' unexpected ' + repr(v))
  15998. case Call(Name('any_tuple_load'), [tup, index]):
  15999. tv = self.interp_exp(tup, env)
  16000. n = self.interp_exp(index, env)
  16001. match tv:
  16002. case Tagged(v, tag):
  16003. return v[n]
  16004. case _:
  16005. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16006. case Call(Name('any_tuple_store'), [tup, index, value]):
  16007. tv = self.interp_exp(tup, env)
  16008. n = self.interp_exp(index, env)
  16009. val = self.interp_exp(value, env)
  16010. match tv:
  16011. case Tagged(v, tag):
  16012. v[n] = val
  16013. return None
  16014. case _:
  16015. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16016. case Call(Name('any_len'), [value]):
  16017. v = self.interp_exp(value, env)
  16018. match v:
  16019. case Tagged(value, tag):
  16020. return len(value)
  16021. case _:
  16022. raise Exception('interp any_len unexpected ' + repr(v))
  16023. case Call(Name('make_any'), [value, tag]):
  16024. v = self.interp_exp(value, env)
  16025. t = self.interp_exp(tag, env)
  16026. return Tagged(v, t)
  16027. case Call(Name('arity'), [fun]):
  16028. f = self.interp_exp(fun, env)
  16029. return self.arity(f)
  16030. case Call(Name('exit'), []):
  16031. trace('exiting!')
  16032. exit(0)
  16033. case TagOf(value):
  16034. v = self.interp_exp(value, env)
  16035. match v:
  16036. case Tagged(val, tag):
  16037. return tag
  16038. case _:
  16039. raise Exception('interp TagOf unexpected ' + repr(v))
  16040. case ValueOf(value, typ):
  16041. v = self.interp_exp(value, env)
  16042. match v:
  16043. case Tagged(val, tag):
  16044. return val
  16045. case _:
  16046. raise Exception('interp ValueOf unexpected ' + repr(v))
  16047. case AnnLambda(params, returns, body):
  16048. return Function('lambda', [x for (x,t) in params], [Return(body)], env)
  16049. case _:
  16050. return super().interp_exp(e, env)
  16051. \end{lstlisting}
  16052. \fi}
  16053. \caption{Interpreter for \LangAny{}.}
  16054. \label{fig:interp-Lany}
  16055. \end{figure}
  16056. \begin{figure}[tbp]
  16057. {\if\edition\racketEd
  16058. \begin{lstlisting}
  16059. (define/public (apply-inject v tg) (Tagged v tg))
  16060. (define/public (apply-project v ty2)
  16061. (define tag2 (any-tag ty2))
  16062. (match v
  16063. [(Tagged v1 tag1)
  16064. (cond
  16065. [(eq? tag1 tag2)
  16066. (match ty2
  16067. [`(Vector ,ts ...)
  16068. (define l1 ((interp-op 'vector-length) v1))
  16069. (cond
  16070. [(eq? l1 (length ts)) v1]
  16071. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16072. l1 (length ts))])]
  16073. [`(,ts ... -> ,rt)
  16074. (match v1
  16075. [`(function ,xs ,body ,env)
  16076. (cond [(eq? (length xs) (length ts)) v1]
  16077. [else
  16078. (error 'apply-project "arity mismatch ~a != ~a"
  16079. (length xs) (length ts))])]
  16080. [else (error 'apply-project "expected function not ~a" v1)])]
  16081. [else v1])]
  16082. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16083. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16084. \end{lstlisting}
  16085. \fi}
  16086. {\if\edition\pythonEd
  16087. \begin{lstlisting}
  16088. class InterpLany(InterpLlambda):
  16089. def type_to_tag(self, typ):
  16090. match typ:
  16091. case FunctionType(params, rt):
  16092. return 'function'
  16093. case TupleType(fields):
  16094. return 'tuple'
  16095. case t if t == int:
  16096. return 'int'
  16097. case t if t == bool:
  16098. return 'bool'
  16099. case IntType():
  16100. return 'int'
  16101. case BoolType():
  16102. return 'int'
  16103. case _:
  16104. raise Exception('type_to_tag unexpected ' + repr(typ))
  16105. def arity(self, v):
  16106. match v:
  16107. case Function(name, params, body, env):
  16108. return len(params)
  16109. case ClosureTuple(args, arity):
  16110. return arity
  16111. case _:
  16112. raise Exception('Lany arity unexpected ' + repr(v))
  16113. \end{lstlisting}
  16114. \fi}
  16115. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16116. \label{fig:interp-Lany-aux}
  16117. \end{figure}
  16118. \clearpage
  16119. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16120. \label{sec:compile-r7}
  16121. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16122. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  16123. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  16124. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  16125. an expression $e'$ in \LangAny{} that has type \ANYTY{}. For example, the
  16126. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  16127. the Boolean \TRUE{}, which must be injected to produce an
  16128. expression of type \ANYTY{}.
  16129. %
  16130. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  16131. addition, is representative of compilation for many primitive
  16132. operations: the arguments have type \ANYTY{} and must be projected to
  16133. \INTTYPE{} before the addition can be performed.
  16134. The compilation of \key{lambda} (third row of
  16135. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  16136. produce type annotations: we simply use \ANYTY{}.
  16137. %
  16138. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16139. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16140. this pass has to account for some differences in behavior between
  16141. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16142. permissive than \LangAny{} regarding what kind of values can be used
  16143. in various places. For example, the condition of an \key{if} does
  16144. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16145. of the same type (in that case the result is \code{\#f}).}
  16146. \begin{figure}[btp]
  16147. \centering
  16148. {\if\edition\racketEd
  16149. \begin{tabular}{|lll|} \hline
  16150. \begin{minipage}{0.27\textwidth}
  16151. \begin{lstlisting}
  16152. #t
  16153. \end{lstlisting}
  16154. \end{minipage}
  16155. &
  16156. $\Rightarrow$
  16157. &
  16158. \begin{minipage}{0.65\textwidth}
  16159. \begin{lstlisting}
  16160. (inject #t Boolean)
  16161. \end{lstlisting}
  16162. \end{minipage}
  16163. \\[2ex]\hline
  16164. \begin{minipage}{0.27\textwidth}
  16165. \begin{lstlisting}
  16166. (+ |$e_1$| |$e_2$|)
  16167. \end{lstlisting}
  16168. \end{minipage}
  16169. &
  16170. $\Rightarrow$
  16171. &
  16172. \begin{minipage}{0.65\textwidth}
  16173. \begin{lstlisting}
  16174. (inject
  16175. (+ (project |$e'_1$| Integer)
  16176. (project |$e'_2$| Integer))
  16177. Integer)
  16178. \end{lstlisting}
  16179. \end{minipage}
  16180. \\[2ex]\hline
  16181. \begin{minipage}{0.27\textwidth}
  16182. \begin{lstlisting}
  16183. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  16184. \end{lstlisting}
  16185. \end{minipage}
  16186. &
  16187. $\Rightarrow$
  16188. &
  16189. \begin{minipage}{0.65\textwidth}
  16190. \begin{lstlisting}
  16191. (inject
  16192. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  16193. (Any|$\ldots$|Any -> Any))
  16194. \end{lstlisting}
  16195. \end{minipage}
  16196. \\[2ex]\hline
  16197. \begin{minipage}{0.27\textwidth}
  16198. \begin{lstlisting}
  16199. (|$e_0$| |$e_1 \ldots e_n$|)
  16200. \end{lstlisting}
  16201. \end{minipage}
  16202. &
  16203. $\Rightarrow$
  16204. &
  16205. \begin{minipage}{0.65\textwidth}
  16206. \begin{lstlisting}
  16207. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16208. \end{lstlisting}
  16209. \end{minipage}
  16210. \\[2ex]\hline
  16211. \begin{minipage}{0.27\textwidth}
  16212. \begin{lstlisting}
  16213. (vector-ref |$e_1$| |$e_2$|)
  16214. \end{lstlisting}
  16215. \end{minipage}
  16216. &
  16217. $\Rightarrow$
  16218. &
  16219. \begin{minipage}{0.65\textwidth}
  16220. \begin{lstlisting}
  16221. (any-vector-ref |$e_1'$| |$e_2'$|)
  16222. \end{lstlisting}
  16223. \end{minipage}
  16224. \\[2ex]\hline
  16225. \begin{minipage}{0.27\textwidth}
  16226. \begin{lstlisting}
  16227. (if |$e_1$| |$e_2$| |$e_3$|)
  16228. \end{lstlisting}
  16229. \end{minipage}
  16230. &
  16231. $\Rightarrow$
  16232. &
  16233. \begin{minipage}{0.65\textwidth}
  16234. \begin{lstlisting}
  16235. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16236. \end{lstlisting}
  16237. \end{minipage}
  16238. \\[2ex]\hline
  16239. \begin{minipage}{0.27\textwidth}
  16240. \begin{lstlisting}
  16241. (eq? |$e_1$| |$e_2$|)
  16242. \end{lstlisting}
  16243. \end{minipage}
  16244. &
  16245. $\Rightarrow$
  16246. &
  16247. \begin{minipage}{0.65\textwidth}
  16248. \begin{lstlisting}
  16249. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16250. \end{lstlisting}
  16251. \end{minipage}
  16252. \\[2ex]\hline
  16253. \begin{minipage}{0.27\textwidth}
  16254. \begin{lstlisting}
  16255. (not |$e_1$|)
  16256. \end{lstlisting}
  16257. \end{minipage}
  16258. &
  16259. $\Rightarrow$
  16260. &
  16261. \begin{minipage}{0.65\textwidth}
  16262. \begin{lstlisting}
  16263. (if (eq? |$e'_1$| (inject #f Boolean))
  16264. (inject #t Boolean) (inject #f Boolean))
  16265. \end{lstlisting}
  16266. \end{minipage}
  16267. \\[2ex]\hline
  16268. \end{tabular}
  16269. \fi}
  16270. {\if\edition\pythonEd
  16271. \begin{tabular}{|lll|} \hline
  16272. \begin{minipage}{0.22\textwidth}
  16273. \begin{lstlisting}
  16274. True
  16275. \end{lstlisting}
  16276. \end{minipage}
  16277. &
  16278. $\Rightarrow$
  16279. &
  16280. \begin{minipage}{0.7\textwidth}
  16281. \begin{lstlisting}
  16282. Inject(True, BoolType())
  16283. \end{lstlisting}
  16284. \end{minipage}
  16285. \\[2ex]\hline
  16286. \begin{minipage}{0.22\textwidth}
  16287. \begin{lstlisting}
  16288. |$e_1$| + |$e_2$|
  16289. \end{lstlisting}
  16290. \end{minipage}
  16291. &
  16292. $\Rightarrow$
  16293. &
  16294. \begin{minipage}{0.7\textwidth}
  16295. \begin{lstlisting}
  16296. Inject(Project(|$e'_1$|, IntType())
  16297. + Project(|$e'_2$|, IntType()),
  16298. IntType())
  16299. \end{lstlisting}
  16300. \end{minipage}
  16301. \\[2ex]\hline
  16302. \begin{minipage}{0.22\textwidth}
  16303. \begin{lstlisting}
  16304. lambda |$x_1 \ldots x_n$|: |$e$|
  16305. \end{lstlisting}
  16306. \end{minipage}
  16307. &
  16308. $\Rightarrow$
  16309. &
  16310. \begin{minipage}{0.7\textwidth}
  16311. \begin{lstlisting}
  16312. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|,(|$x_n$|,AnyType)], |$e'$|)
  16313. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16314. \end{lstlisting}
  16315. \end{minipage}
  16316. \\[2ex]\hline
  16317. \begin{minipage}{0.22\textwidth}
  16318. \begin{lstlisting}
  16319. |$e_0$|(|$e_1 \ldots e_n$|)
  16320. \end{lstlisting}
  16321. \end{minipage}
  16322. &
  16323. $\Rightarrow$
  16324. &
  16325. \begin{minipage}{0.7\textwidth}
  16326. \begin{lstlisting}
  16327. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16328. AnyType())), |$e'_1, \ldots, e'_n$|)
  16329. \end{lstlisting}
  16330. \end{minipage}
  16331. \\[2ex]\hline
  16332. \begin{minipage}{0.22\textwidth}
  16333. \begin{lstlisting}
  16334. |$e_1$|[|$e_2$|]
  16335. \end{lstlisting}
  16336. \end{minipage}
  16337. &
  16338. $\Rightarrow$
  16339. &
  16340. \begin{minipage}{0.7\textwidth}
  16341. \begin{lstlisting}
  16342. Call(Name('any_tuple_load'),[|$e_1'$|, |$e_2'$|])
  16343. \end{lstlisting}
  16344. \end{minipage}
  16345. \\[2ex]\hline
  16346. %% \begin{minipage}{0.22\textwidth}
  16347. %% \begin{lstlisting}
  16348. %% |$e_2$| if |$e_1$| else |$e_3$|
  16349. %% \end{lstlisting}
  16350. %% \end{minipage}
  16351. %% &
  16352. %% $\Rightarrow$
  16353. %% &
  16354. %% \begin{minipage}{0.7\textwidth}
  16355. %% \begin{lstlisting}
  16356. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16357. %% \end{lstlisting}
  16358. %% \end{minipage}
  16359. %% \\[2ex]\hline
  16360. %% \begin{minipage}{0.22\textwidth}
  16361. %% \begin{lstlisting}
  16362. %% (eq? |$e_1$| |$e_2$|)
  16363. %% \end{lstlisting}
  16364. %% \end{minipage}
  16365. %% &
  16366. %% $\Rightarrow$
  16367. %% &
  16368. %% \begin{minipage}{0.7\textwidth}
  16369. %% \begin{lstlisting}
  16370. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16371. %% \end{lstlisting}
  16372. %% \end{minipage}
  16373. %% \\[2ex]\hline
  16374. %% \begin{minipage}{0.22\textwidth}
  16375. %% \begin{lstlisting}
  16376. %% (not |$e_1$|)
  16377. %% \end{lstlisting}
  16378. %% \end{minipage}
  16379. %% &
  16380. %% $\Rightarrow$
  16381. %% &
  16382. %% \begin{minipage}{0.7\textwidth}
  16383. %% \begin{lstlisting}
  16384. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16385. %% (inject #t Boolean) (inject #f Boolean))
  16386. %% \end{lstlisting}
  16387. %% \end{minipage}
  16388. %% \\[2ex]\hline
  16389. \end{tabular}
  16390. \fi}
  16391. \caption{Cast Insertion}
  16392. \label{fig:compile-r7-Rany}
  16393. \end{figure}
  16394. \section{Reveal Casts}
  16395. \label{sec:reveal-casts-Rany}
  16396. % TODO: define R'_6
  16397. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16398. into a conditional expression that checks whether the value's tag
  16399. matches the target type; if it does, the value is converted to a value
  16400. of the target type by removing the tag; if it does not, the program
  16401. exits.
  16402. %
  16403. {\if\edition\racketEd
  16404. %
  16405. To perform these actions we need a new primitive operation,
  16406. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16407. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16408. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16409. underlying value from a tagged value. The \code{ValueOf} form
  16410. includes the type for the underlying value which is used by the type
  16411. checker. Finally, the \code{Exit} form ends the execution of the
  16412. program.
  16413. %
  16414. \fi}
  16415. %
  16416. {\if\edition\pythonEd
  16417. %
  16418. To perform these actions we need the \code{exit} function (from the C
  16419. standard library) and two new AST classes: \code{TagOf} and
  16420. \code{ValueOf}. The \code{exit} function ends the execution of the
  16421. program. The \code{TagOf} operation retrieves the type tag from a
  16422. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16423. the underlying value from a tagged value. The \code{ValueOf}
  16424. operation includes the type for the underlying value which is used by
  16425. the type checker.
  16426. %
  16427. \fi}
  16428. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16429. \code{Project} can be translated as follows.
  16430. \begin{center}
  16431. \begin{minipage}{1.0\textwidth}
  16432. {\if\edition\racketEd
  16433. \begin{lstlisting}
  16434. (Project |$e$| |$\FType$|)
  16435. |$\Rightarrow$|
  16436. (Let |$\itm{tmp}$| |$e'$|
  16437. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16438. (Int |$\itm{tagof}(\FType)$|)))
  16439. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16440. (Exit)))
  16441. \end{lstlisting}
  16442. \fi}
  16443. {\if\edition\pythonEd
  16444. \begin{lstlisting}
  16445. Project(|$e$|, |$\FType$|)
  16446. |$\Rightarrow$|
  16447. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16448. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16449. [Constant(|$\itm{tagof}(\FType)$|)]),
  16450. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16451. Call(Name('exit'), [])))
  16452. \end{lstlisting}
  16453. \fi}
  16454. \end{minipage}
  16455. \end{center}
  16456. If the target type of the projection is a tuple or function type, then
  16457. there is a bit more work to do. For tuples, check that the length of
  16458. the tuple type matches the length of the tuple. For functions, check
  16459. that the number of parameters in the function type matches the
  16460. function's arity.
  16461. Regarding \code{Inject}, we recommend compiling it to a slightly
  16462. lower-level primitive operation named \code{make\_any}. This operation
  16463. takes a tag instead of a type.
  16464. \begin{center}
  16465. \begin{minipage}{1.0\textwidth}
  16466. {\if\edition\racketEd
  16467. \begin{lstlisting}
  16468. (Inject |$e$| |$\FType$|)
  16469. |$\Rightarrow$|
  16470. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16471. \end{lstlisting}
  16472. \fi}
  16473. {\if\edition\pythonEd
  16474. \begin{lstlisting}
  16475. Inject(|$e$|, |$\FType$|)
  16476. |$\Rightarrow$|
  16477. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16478. \end{lstlisting}
  16479. \fi}
  16480. \end{minipage}
  16481. \end{center}
  16482. {\if\edition\pythonEd
  16483. %
  16484. The introduction of \code{make\_any} makes it difficult to use
  16485. bidirectional type checking because we no longer have an expected type
  16486. to use for type checking the expression $e'$. Thus, we run into
  16487. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16488. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16489. annotated lambda) whose parameters have type annotations and that
  16490. records the return type.
  16491. %
  16492. \fi}
  16493. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16494. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16495. translation of \code{Project}.}
  16496. {\if\edition\racketEd
  16497. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16498. combine the projection action with the vector operation. Also, the
  16499. read and write operations allow arbitrary expressions for the index so
  16500. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany})
  16501. cannot guarantee that the index is within bounds. Thus, we insert code
  16502. to perform bounds checking at runtime. The translation for
  16503. \code{any-vector-ref} is as follows and the other two operations are
  16504. translated in a similar way.
  16505. \begin{lstlisting}
  16506. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16507. |$\Rightarrow$|
  16508. (Let |$v$| |$e'_1$|
  16509. (Let |$i$| |$e'_2$|
  16510. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16511. (If (Prim '< (list (Var |$i$|)
  16512. (Prim 'any-vector-length (list (Var |$v$|)))))
  16513. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16514. (Exit))
  16515. (Exit))))
  16516. \end{lstlisting}
  16517. \fi}
  16518. %
  16519. {\if\edition\pythonEd
  16520. %
  16521. The \code{any\_tuple\_load} operation combines the projection action
  16522. with the load operation. Also, the load operation allows arbitrary
  16523. expressions for the index so the type checker for \LangAny{}
  16524. (Figure~\ref{fig:type-check-Rany}) cannot guarantee that the index is
  16525. within bounds. Thus, we insert code to perform bounds checking at
  16526. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16527. \begin{lstlisting}
  16528. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16529. |$\Rightarrow$|
  16530. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16531. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16532. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16533. Call(Name('any_tuple_load'), [|$t$|, |$i$|]),
  16534. Call(Name('exit'), [])),
  16535. Call(Name('exit'), [])))
  16536. \end{lstlisting}
  16537. \fi}
  16538. {\if\edition\pythonEd
  16539. \section{Assignment Conversion}
  16540. \label{sec:convert-assignments-Lany}
  16541. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16542. \code{AnnLambda} AST classes.
  16543. \section{Closure Conversion}
  16544. \label{sec:closure-conversion-Lany}
  16545. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16546. \code{AnnLambda} AST classes.
  16547. \fi}
  16548. \section{Remove Complex Operands}
  16549. \label{sec:rco-Rany}
  16550. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16551. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16552. %
  16553. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16554. complex expressions. Their subexpressions must be atomic.}
  16555. \section{Explicate Control and \LangCAny{}}
  16556. \label{sec:explicate-Rany}
  16557. The output of \code{explicate\_control} is the \LangCAny{} language
  16558. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16559. %
  16560. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16561. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16562. note that the index argument of \code{vector-ref} and
  16563. \code{vector-set!} is an $\Atm$ instead of an integer, as in
  16564. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16565. %
  16566. \python{
  16567. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16568. and \code{explicate\_pred} as appropriately to handle the new expressions
  16569. in \LangCAny{}.
  16570. }
  16571. \newcommand{\CanyASTPython}{
  16572. \begin{array}{lcl}
  16573. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16574. &\MID& \key{TagOf}\LP \Atm \RP
  16575. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  16576. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS \Atm,\Atm \RS}\\
  16577. &\MID& \CALL{\VAR{\key{'any\_tuple\_store'}}}{\LS \Atm,\Atm,\Atm \RS}\\
  16578. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16579. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16580. \end{array}
  16581. }
  16582. \begin{figure}[tp]
  16583. \fbox{
  16584. \begin{minipage}{0.96\textwidth}
  16585. \small
  16586. {\if\edition\racketEd
  16587. \[
  16588. \begin{array}{lcl}
  16589. \Exp &::= & \ldots
  16590. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16591. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16592. &\MID& \VALUEOF{\Exp}{\FType} \\
  16593. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  16594. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  16595. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  16596. \MID \GOTO{\itm{label}} } \\
  16597. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  16598. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  16599. \MID \LP\key{Exit}\RP \\
  16600. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  16601. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  16602. \end{array}
  16603. \]
  16604. \fi}
  16605. {\if\edition\pythonEd
  16606. \[
  16607. \begin{array}{l}
  16608. \gray{\CifASTPython} \\ \hline
  16609. \gray{\CtupASTPython} \\ \hline
  16610. \gray{\CfunASTPython} \\ \hline
  16611. \gray{\ClambdaASTPython} \\ \hline
  16612. \CanyASTPython \\
  16613. \begin{array}{lcl}
  16614. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16615. \end{array}
  16616. \end{array}
  16617. \]
  16618. \fi}
  16619. \end{minipage}
  16620. }
  16621. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16622. \label{fig:c5-syntax}
  16623. \end{figure}
  16624. \section{Select Instructions}
  16625. \label{sec:select-Rany}
  16626. In the \code{select\_instructions} pass we translate the primitive
  16627. operations on the \ANYTY{} type to x86 instructions that manipulate
  16628. the 3 tag bits of the tagged value. In the following descriptions,
  16629. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16630. of translating $e$ into an x86 argument.
  16631. \paragraph{\code{make\_any}}
  16632. We recommend compiling the \code{make\_any} operation as follows if
  16633. the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16634. shifts the destination to the left by the number of bits specified its
  16635. source argument (in this case $3$, the length of the tag) and it
  16636. preserves the sign of the integer. We use the \key{orq} instruction to
  16637. combine the tag and the value to form the tagged value. \\
  16638. %
  16639. {\if\edition\racketEd
  16640. \begin{lstlisting}
  16641. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16642. |$\Rightarrow$|
  16643. movq |$e'$|, |\itm{lhs'}|
  16644. salq $3, |\itm{lhs'}|
  16645. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16646. \end{lstlisting}
  16647. \fi}
  16648. %
  16649. {\if\edition\pythonEd
  16650. \begin{lstlisting}
  16651. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16652. |$\Rightarrow$|
  16653. movq |$e'$|, |\itm{lhs'}|
  16654. salq $3, |\itm{lhs'}|
  16655. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16656. \end{lstlisting}
  16657. \fi}
  16658. %
  16659. The instruction selection for tuples and procedures is different
  16660. because their is no need to shift them to the left. The rightmost 3
  16661. bits are already zeros so we simply combine the value and the tag
  16662. using \key{orq}. \\
  16663. %
  16664. {\if\edition\racketEd
  16665. \begin{lstlisting}
  16666. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16667. |$\Rightarrow$|
  16668. movq |$e'$|, |\itm{lhs'}|
  16669. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16670. \end{lstlisting}
  16671. \fi}
  16672. %
  16673. {\if\edition\pythonEd
  16674. \begin{lstlisting}
  16675. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16676. |$\Rightarrow$|
  16677. movq |$e'$|, |\itm{lhs'}|
  16678. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16679. \end{lstlisting}
  16680. \fi}
  16681. \paragraph{\code{TagOf}}
  16682. Recall that the \code{TagOf} operation extracts the type tag from a
  16683. value of type \ANYTY{}. The type tag is the bottom three bits, so we
  16684. obtain the tag by taking the bitwise-and of the value with $111$ ($7$
  16685. in decimal).
  16686. %
  16687. {\if\edition\racketEd
  16688. \begin{lstlisting}
  16689. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16690. |$\Rightarrow$|
  16691. movq |$e'$|, |\itm{lhs'}|
  16692. andq $7, |\itm{lhs'}|
  16693. \end{lstlisting}
  16694. \fi}
  16695. %
  16696. {\if\edition\pythonEd
  16697. \begin{lstlisting}
  16698. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16699. |$\Rightarrow$|
  16700. movq |$e'$|, |\itm{lhs'}|
  16701. andq $7, |\itm{lhs'}|
  16702. \end{lstlisting}
  16703. \fi}
  16704. \paragraph{\code{ValueOf}}
  16705. Like \code{make\_any}, the instructions for \key{ValueOf} are
  16706. different depending on whether the type $T$ is a pointer (tuple or
  16707. function) or not (integer or Boolean). The following shows the
  16708. instruction selection for integers and Booleans. We produce an
  16709. untagged value by shifting it to the right by 3 bits.
  16710. %
  16711. {\if\edition\racketEd
  16712. \begin{lstlisting}
  16713. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16714. |$\Rightarrow$|
  16715. movq |$e'$|, |\itm{lhs'}|
  16716. sarq $3, |\itm{lhs'}|
  16717. \end{lstlisting}
  16718. \fi}
  16719. %
  16720. {\if\edition\pythonEd
  16721. \begin{lstlisting}
  16722. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16723. |$\Rightarrow$|
  16724. movq |$e'$|, |\itm{lhs'}|
  16725. sarq $3, |\itm{lhs'}|
  16726. \end{lstlisting}
  16727. \fi}
  16728. %
  16729. In the case for tuples and procedures, we just need to zero-out the
  16730. rightmost 3 bits. We accomplish this by creating the bit pattern
  16731. $\ldots 0111$ ($7$ in decimal) and apply bitwise-not to obtain $\ldots
  16732. 11111000$ (-8 in decimal) which we \code{movq} into the destination
  16733. $\itm{lhs'}$. Finally, we apply \code{andq} with the tagged value to
  16734. get the desired result.
  16735. %
  16736. {\if\edition\racketEd
  16737. \begin{lstlisting}
  16738. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16739. |$\Rightarrow$|
  16740. movq $|$-8$|, |\itm{lhs'}|
  16741. andq |$e'$|, |\itm{lhs'}|
  16742. \end{lstlisting}
  16743. \fi}
  16744. %
  16745. {\if\edition\pythonEd
  16746. \begin{lstlisting}
  16747. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16748. |$\Rightarrow$|
  16749. movq $|$-8$|, |\itm{lhs'}|
  16750. andq |$e'$|, |\itm{lhs'}|
  16751. \end{lstlisting}
  16752. \fi}
  16753. %% \paragraph{Type Predicates} We leave it to the reader to
  16754. %% devise a sequence of instructions to implement the type predicates
  16755. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16756. \paragraph{\racket{Any-vector-length}\python{\code{any\_len}}}
  16757. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16758. operation combines the effect of \code{ValueOf} with accessing the
  16759. length of a tuple from the tag stored at the zero index of the tuple.
  16760. {\if\edition\racketEd
  16761. \begin{lstlisting}
  16762. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16763. |$\Longrightarrow$|
  16764. movq $|$-8$|, %r11
  16765. andq |$e_1'$|, %r11
  16766. movq 0(%r11), %r11
  16767. andq $126, %r11
  16768. sarq $1, %r11
  16769. movq %r11, |$\itm{lhs'}$|
  16770. \end{lstlisting}
  16771. \fi}
  16772. {\if\edition\pythonEd
  16773. \begin{lstlisting}
  16774. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16775. |$\Longrightarrow$|
  16776. movq $|$-8$|, %r11
  16777. andq |$e_1'$|, %r11
  16778. movq 0(%r11), %r11
  16779. andq $126, %r11
  16780. sarq $1, %r11
  16781. movq %r11, |$\itm{lhs'}$|
  16782. \end{lstlisting}
  16783. \fi}
  16784. \paragraph{\racket{Any-vector-ref}\python{\code{\code{any\_tuple\_load}}}}
  16785. This operation combines the effect of \code{ValueOf} with reading an
  16786. element of the tuple (see
  16787. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16788. an arbitrary atom so instead of computing the offset at compile time,
  16789. we must generate instructions to compute the offset at runtime as
  16790. follows. Note the use of the new instruction \code{imulq}.
  16791. \begin{center}
  16792. \begin{minipage}{0.96\textwidth}
  16793. {\if\edition\racketEd
  16794. \begin{lstlisting}
  16795. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16796. |$\Longrightarrow$|
  16797. movq |$\neg 111$|, %r11
  16798. andq |$e_1'$|, %r11
  16799. movq |$e_2'$|, %rax
  16800. addq $1, %rax
  16801. imulq $8, %rax
  16802. addq %rax, %r11
  16803. movq 0(%r11) |$\itm{lhs'}$|
  16804. \end{lstlisting}
  16805. \fi}
  16806. %
  16807. {\if\edition\pythonEd
  16808. \begin{lstlisting}
  16809. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|]))
  16810. |$\Longrightarrow$|
  16811. movq $|$-8$|, %r11
  16812. andq |$e_1'$|, %r11
  16813. movq |$e_2'$|, %rax
  16814. addq $1, %rax
  16815. imulq $8, %rax
  16816. addq %rax, %r11
  16817. movq 0(%r11) |$\itm{lhs'}$|
  16818. \end{lstlisting}
  16819. \fi}
  16820. \end{minipage}
  16821. \end{center}
  16822. \paragraph{\racket{Any-vector-set!}\python{\code{any\_tuple\_store}}}
  16823. The code generation for
  16824. \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16825. analogous to the above translation for reading from a tuple.
  16826. \section{Register Allocation for \LangAny{}}
  16827. \label{sec:register-allocation-Rany}
  16828. \index{subject}{register allocation}
  16829. There is an interesting interaction between tagged values and garbage
  16830. collection that has an impact on register allocation. A variable of
  16831. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16832. that needs to be inspected and copied during garbage collection. Thus,
  16833. we need to treat variables of type \ANYTY{} in a similar way to
  16834. variables of tuple type for purposes of register allocation. In
  16835. particular,
  16836. \begin{itemize}
  16837. \item If a variable of type \ANYTY{} is live during a function call,
  16838. then it must be spilled. This can be accomplished by changing
  16839. \code{build\_interference} to mark all variables of type \ANYTY{}
  16840. that are live after a \code{callq} as interfering with all the
  16841. registers.
  16842. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16843. the root stack instead of the normal procedure call stack.
  16844. \end{itemize}
  16845. Another concern regarding the root stack is that the garbage collector
  16846. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16847. tagged value that points to a tuple, and (3) a tagged value that is
  16848. not a tuple. We enable this differentiation by choosing not to use the
  16849. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16850. reserved for identifying plain old pointers to tuples. That way, if
  16851. one of the first three bits is set, then we have a tagged value and
  16852. inspecting the tag can differentiate between tuples ($010$) and the
  16853. other kinds of values.
  16854. %% \begin{exercise}\normalfont
  16855. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16856. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16857. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16858. %% compiler on these new programs and all of your previously created test
  16859. %% programs.
  16860. %% \end{exercise}
  16861. \begin{exercise}\normalfont\normalsize
  16862. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16863. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16864. by removing type annotations. Add 5 more tests programs that
  16865. specifically rely on the language being dynamically typed. That is,
  16866. they should not be legal programs in a statically typed language, but
  16867. nevertheless, they should be valid \LangDyn{} programs that run to
  16868. completion without error.
  16869. \end{exercise}
  16870. \begin{figure}[p]
  16871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16872. \node (Lfun) at (0,4) {\large \LangDyn{}};
  16873. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  16874. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  16875. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  16876. \node (Lfun-5) at (9,2) {\large \LangAnyFunRef{}};
  16877. \node (Lfun-6) at (12,2) {\large \LangAnyFunRef{}};
  16878. \node (Lfun-7) at (12,0) {\large \LangAnyFunRef{}};
  16879. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  16880. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  16881. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  16882. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  16883. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16884. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16885. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16886. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16887. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16888. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16889. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16890. \path[->,bend left=15] (Lfun) edge [above] node
  16891. {\ttfamily\footnotesize shrink} (Lfun-2);
  16892. \path[->,bend left=15] (Lfun-2) edge [above] node
  16893. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16894. \path[->,bend left=15] (Lfun-3) edge [above] node
  16895. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  16896. \path[->,bend right=15] (Lfun-4) edge [left] node
  16897. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  16898. \path[->,bend left=15] (Lfun-5) edge [above] node
  16899. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  16900. \path[->,bend left=15] (Lfun-6) edge [left] node
  16901. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  16902. \path[->,bend left=15] (Lfun-7) edge [below] node
  16903. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16904. \path[->,bend right=15] (F1-2) edge [above] node
  16905. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16906. \path[->,bend right=15] (F1-3) edge [above] node
  16907. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16908. \path[->,bend right=15] (F1-4) edge [above] node
  16909. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16910. \path[->,bend right=15] (F1-5) edge [right] node
  16911. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16912. \path[->,bend left=15] (C3-2) edge [left] node
  16913. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16914. \path[->,bend right=15] (x86-2) edge [left] node
  16915. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16916. \path[->,bend right=15] (x86-2-1) edge [below] node
  16917. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16918. \path[->,bend right=15] (x86-2-2) edge [left] node
  16919. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16920. \path[->,bend left=15] (x86-3) edge [above] node
  16921. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16922. \path[->,bend left=15] (x86-4) edge [right] node
  16923. {\ttfamily\footnotesize print\_x86} (x86-5);
  16924. \end{tikzpicture}
  16925. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16926. \label{fig:Rdyn-passes}
  16927. \end{figure}
  16928. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  16929. for the compilation of \LangDyn{}.
  16930. % Further Reading
  16931. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16932. %% {\if\edition\pythonEd
  16933. %% \chapter{Objects}
  16934. %% \label{ch:Lobject}
  16935. %% \index{subject}{objects}
  16936. %% \index{subject}{classes}
  16937. %% \fi}
  16938. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16939. \chapter{Gradual Typing}
  16940. \label{ch:Lgrad}
  16941. \index{subject}{gradual typing}
  16942. \if\edition\pythonEd
  16943. UNDER CONSTRUCTION
  16944. \fi
  16945. \if\edition\racketEd
  16946. This chapter studies a language, \LangGrad{}, in which the programmer
  16947. can choose between static and dynamic type checking in different parts
  16948. of a program, thereby mixing the statically typed \LangLoop{} language
  16949. with the dynamically typed \LangDyn{}. There are several approaches to
  16950. mixing static and dynamic typing, including multi-language
  16951. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16952. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16953. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16954. programmer controls the amount of static versus dynamic checking by
  16955. adding or removing type annotations on parameters and
  16956. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16957. %
  16958. The concrete syntax of \LangGrad{} is defined in
  16959. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  16960. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  16961. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16962. non-terminals that make type annotations optional. The return types
  16963. are not optional in the abstract syntax; the parser fills in
  16964. \code{Any} when the return type is not specified in the concrete
  16965. syntax.
  16966. \begin{figure}[tp]
  16967. \centering
  16968. \fbox{
  16969. \begin{minipage}{0.96\textwidth}
  16970. \small
  16971. \[
  16972. \begin{array}{lcl}
  16973. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16974. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16975. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  16976. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  16977. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  16978. &\MID& \gray{\key{\#t} \MID \key{\#f}
  16979. \MID (\key{and}\;\Exp\;\Exp)
  16980. \MID (\key{or}\;\Exp\;\Exp)
  16981. \MID (\key{not}\;\Exp) } \\
  16982. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  16983. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  16984. (\key{vector-ref}\;\Exp\;\Int)} \\
  16985. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  16986. \MID (\Exp \; \Exp\ldots) } \\
  16987. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  16988. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16989. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  16990. \MID \CBEGIN{\Exp\ldots}{\Exp}
  16991. \MID \CWHILE{\Exp}{\Exp} } \\
  16992. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  16993. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16994. \end{array}
  16995. \]
  16996. \end{minipage}
  16997. }
  16998. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16999. \label{fig:Rgrad-concrete-syntax}
  17000. \end{figure}
  17001. \begin{figure}[tp]
  17002. \centering
  17003. \fbox{
  17004. \begin{minipage}{0.96\textwidth}
  17005. \small
  17006. \[
  17007. \begin{array}{lcl}
  17008. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17009. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  17010. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  17011. &\MID& \gray{ \BOOL{\itm{bool}}
  17012. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  17013. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  17014. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  17015. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  17016. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  17017. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  17018. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  17019. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17020. \end{array}
  17021. \]
  17022. \end{minipage}
  17023. }
  17024. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  17025. \label{fig:Rgrad-syntax}
  17026. \end{figure}
  17027. Both the type checker and the interpreter for \LangGrad{} require some
  17028. interesting changes to enable gradual typing, which we discuss in the
  17029. next two sections in the context of the \code{map} example from
  17030. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  17031. revised the \code{map} example, omitting the type annotations from
  17032. the \code{inc} function.
  17033. \begin{figure}[btp]
  17034. % gradual_test_9.rkt
  17035. \begin{lstlisting}
  17036. (define (map [f : (Integer -> Integer)]
  17037. [v : (Vector Integer Integer)])
  17038. : (Vector Integer Integer)
  17039. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17040. (define (inc x) (+ x 1))
  17041. (vector-ref (map inc (vector 0 41)) 1)
  17042. \end{lstlisting}
  17043. \caption{A partially-typed version of the \code{map} example.}
  17044. \label{fig:gradual-map}
  17045. \end{figure}
  17046. \section{Type Checking \LangGrad{} and \LangCast{}}
  17047. \label{sec:gradual-type-check}
  17048. The type checker for \LangGrad{} uses the \code{Any} type for missing
  17049. parameter and return types. For example, the \code{x} parameter of
  17050. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  17051. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  17052. consider the \code{+} operator inside \code{inc}. It expects both
  17053. arguments to have type \code{Integer}, but its first argument \code{x}
  17054. has type \code{Any}. In a gradually typed language, such differences
  17055. are allowed so long as the types are \emph{consistent}, that is, they
  17056. are equal except in places where there is an \code{Any} type. The type
  17057. \code{Any} is consistent with every other type.
  17058. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  17059. \begin{figure}[tbp]
  17060. \begin{lstlisting}
  17061. (define/public (consistent? t1 t2)
  17062. (match* (t1 t2)
  17063. [('Integer 'Integer) #t]
  17064. [('Boolean 'Boolean) #t]
  17065. [('Void 'Void) #t]
  17066. [('Any t2) #t]
  17067. [(t1 'Any) #t]
  17068. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17069. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17070. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17071. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17072. (consistent? rt1 rt2))]
  17073. [(other wise) #f]))
  17074. \end{lstlisting}
  17075. \caption{The consistency predicate on types.}
  17076. \label{fig:consistent}
  17077. \end{figure}
  17078. Returning to the \code{map} example of
  17079. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  17080. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  17081. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  17082. because the two types are consistent. In particular, \code{->} is
  17083. equal to \code{->} and because \code{Any} is consistent with
  17084. \code{Integer}.
  17085. Next consider a program with an error, such as applying the
  17086. \code{map} to a function that sometimes returns a Boolean, as
  17087. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  17088. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  17089. consistent with the type of parameter \code{f} of \code{map}, that
  17090. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  17091. Integer)}. One might say that a gradual type checker is optimistic
  17092. in that it accepts programs that might execute without a runtime type
  17093. error.
  17094. %
  17095. Unfortunately, running this program with input \code{1} triggers an
  17096. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  17097. performs checking at runtime to ensure the integrity of the static
  17098. types, such as the \code{(Integer -> Integer)} annotation on parameter
  17099. \code{f} of \code{map}. This runtime checking is carried out by a
  17100. new \code{Cast} form that is inserted by the type checker. Thus, the
  17101. output of the type checker is a program in the \LangCast{} language, which
  17102. adds \code{Cast} to \LangLoop{}, as shown in
  17103. Figure~\ref{fig:Rgrad-prime-syntax}.
  17104. \begin{figure}[tp]
  17105. \centering
  17106. \fbox{
  17107. \begin{minipage}{0.96\textwidth}
  17108. \small
  17109. \[
  17110. \begin{array}{lcl}
  17111. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17112. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17113. \end{array}
  17114. \]
  17115. \end{minipage}
  17116. }
  17117. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  17118. \label{fig:Rgrad-prime-syntax}
  17119. \end{figure}
  17120. \begin{figure}[tbp]
  17121. \begin{lstlisting}
  17122. (define (map [f : (Integer -> Integer)]
  17123. [v : (Vector Integer Integer)])
  17124. : (Vector Integer Integer)
  17125. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17126. (define (inc x) (+ x 1))
  17127. (define (true) #t)
  17128. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  17129. (vector-ref (map maybe-inc (vector 0 41)) 0)
  17130. \end{lstlisting}
  17131. \caption{A variant of the \code{map} example with an error.}
  17132. \label{fig:map-maybe-inc}
  17133. \end{figure}
  17134. Figure~\ref{fig:map-cast} shows the output of the type checker for
  17135. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  17136. inserted every time the type checker sees two types that are
  17137. consistent but not equal. In the \code{inc} function, \code{x} is
  17138. cast to \code{Integer} and the result of the \code{+} is cast to
  17139. \code{Any}. In the call to \code{map}, the \code{inc} argument
  17140. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  17141. \begin{figure}[btp]
  17142. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17143. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17144. : (Vector Integer Integer)
  17145. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17146. (define (inc [x : Any]) : Any
  17147. (cast (+ (cast x Any Integer) 1) Integer Any))
  17148. (define (true) : Any (cast #t Boolean Any))
  17149. (define (maybe-inc [x : Any]) : Any
  17150. (if (eq? 0 (read)) (inc x) (true)))
  17151. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  17152. (vector 0 41)) 0)
  17153. \end{lstlisting}
  17154. \caption{Output of type checking \code{map}
  17155. and \code{maybe-inc}.}
  17156. \label{fig:map-cast}
  17157. \end{figure}
  17158. The type checker for \LangGrad{} is defined in
  17159. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  17160. and \ref{fig:type-check-Rgradual-3}.
  17161. \begin{figure}[tbp]
  17162. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17163. (define type-check-gradual-class
  17164. (class type-check-Lwhile-class
  17165. (super-new)
  17166. (inherit operator-types type-predicates)
  17167. (define/override (type-check-exp env)
  17168. (lambda (e)
  17169. (define recur (type-check-exp env))
  17170. (match e
  17171. [(Prim 'vector-length (list e1))
  17172. (define-values (e1^ t) (recur e1))
  17173. (match t
  17174. [`(Vector ,ts ...)
  17175. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17176. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17177. [(Prim 'vector-ref (list e1 e2))
  17178. (define-values (e1^ t1) (recur e1))
  17179. (define-values (e2^ t2) (recur e2))
  17180. (check-consistent? t2 'Integer e)
  17181. (match t1
  17182. [`(Vector ,ts ...)
  17183. (match e2^
  17184. [(Int i)
  17185. (unless (and (0 . <= . i) (i . < . (length ts)))
  17186. (error 'type-check "invalid index ~a in ~a" i e))
  17187. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17188. [else (define e1^^ (make-cast e1^ t1 'Any))
  17189. (define e2^^ (make-cast e2^ t2 'Integer))
  17190. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17191. ['Any
  17192. (define e2^^ (make-cast e2^ t2 'Integer))
  17193. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17194. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17195. [(Prim 'vector-set! (list e1 e2 e3) )
  17196. (define-values (e1^ t1) (recur e1))
  17197. (define-values (e2^ t2) (recur e2))
  17198. (define-values (e3^ t3) (recur e3))
  17199. (check-consistent? t2 'Integer e)
  17200. (match t1
  17201. [`(Vector ,ts ...)
  17202. (match e2^
  17203. [(Int i)
  17204. (unless (and (0 . <= . i) (i . < . (length ts)))
  17205. (error 'type-check "invalid index ~a in ~a" i e))
  17206. (check-consistent? (list-ref ts i) t3 e)
  17207. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17208. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17209. [else
  17210. (define e1^^ (make-cast e1^ t1 'Any))
  17211. (define e2^^ (make-cast e2^ t2 'Integer))
  17212. (define e3^^ (make-cast e3^ t3 'Any))
  17213. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17214. ['Any
  17215. (define e2^^ (make-cast e2^ t2 'Integer))
  17216. (define e3^^ (make-cast e3^ t3 'Any))
  17217. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17218. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17219. \end{lstlisting}
  17220. \caption{Type checker for the \LangGrad{} language, part 1.}
  17221. \label{fig:type-check-Rgradual-1}
  17222. \end{figure}
  17223. \begin{figure}[tbp]
  17224. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17225. [(Prim 'eq? (list e1 e2))
  17226. (define-values (e1^ t1) (recur e1))
  17227. (define-values (e2^ t2) (recur e2))
  17228. (check-consistent? t1 t2 e)
  17229. (define T (meet t1 t2))
  17230. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17231. 'Boolean)]
  17232. [(Prim 'not (list e1))
  17233. (define-values (e1^ t1) (recur e1))
  17234. (match t1
  17235. ['Any
  17236. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17237. (Bool #t) (Bool #f)))]
  17238. [else
  17239. (define-values (t-ret new-es^)
  17240. (type-check-op 'not (list t1) (list e1^) e))
  17241. (values (Prim 'not new-es^) t-ret)])]
  17242. [(Prim 'and (list e1 e2))
  17243. (recur (If e1 e2 (Bool #f)))]
  17244. [(Prim 'or (list e1 e2))
  17245. (define tmp (gensym 'tmp))
  17246. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17247. [(Prim op es)
  17248. #:when (not (set-member? explicit-prim-ops op))
  17249. (define-values (new-es ts)
  17250. (for/lists (exprs types) ([e es])
  17251. (recur e)))
  17252. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17253. (values (Prim op new-es^) t-ret)]
  17254. [(If e1 e2 e3)
  17255. (define-values (e1^ T1) (recur e1))
  17256. (define-values (e2^ T2) (recur e2))
  17257. (define-values (e3^ T3) (recur e3))
  17258. (check-consistent? T2 T3 e)
  17259. (match T1
  17260. ['Boolean
  17261. (define Tif (join T2 T3))
  17262. (values (If e1^ (make-cast e2^ T2 Tif)
  17263. (make-cast e3^ T3 Tif)) Tif)]
  17264. ['Any
  17265. (define Tif (meet T2 T3))
  17266. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17267. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17268. Tif)]
  17269. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17270. [(HasType e1 T)
  17271. (define-values (e1^ T1) (recur e1))
  17272. (check-consistent? T1 T)
  17273. (values (make-cast e1^ T1 T) T)]
  17274. [(SetBang x e1)
  17275. (define-values (e1^ T1) (recur e1))
  17276. (define varT (dict-ref env x))
  17277. (check-consistent? T1 varT e)
  17278. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17279. [(WhileLoop e1 e2)
  17280. (define-values (e1^ T1) (recur e1))
  17281. (check-consistent? T1 'Boolean e)
  17282. (define-values (e2^ T2) ((type-check-exp env) e2))
  17283. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17284. \end{lstlisting}
  17285. \caption{Type checker for the \LangGrad{} language, part 2.}
  17286. \label{fig:type-check-Rgradual-2}
  17287. \end{figure}
  17288. \begin{figure}[tbp]
  17289. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17290. [(Apply e1 e2s)
  17291. (define-values (e1^ T1) (recur e1))
  17292. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17293. (match T1
  17294. [`(,T1ps ... -> ,T1rt)
  17295. (for ([T2 T2s] [Tp T1ps])
  17296. (check-consistent? T2 Tp e))
  17297. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17298. (make-cast e2 src tgt)))
  17299. (values (Apply e1^ e2s^^) T1rt)]
  17300. [`Any
  17301. (define e1^^ (make-cast e1^ 'Any
  17302. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17303. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17304. (make-cast e2 src 'Any)))
  17305. (values (Apply e1^^ e2s^^) 'Any)]
  17306. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17307. [(Lambda params Tr e1)
  17308. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17309. (match p
  17310. [`[,x : ,T] (values x T)]
  17311. [(? symbol? x) (values x 'Any)])))
  17312. (define-values (e1^ T1)
  17313. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17314. (check-consistent? Tr T1 e)
  17315. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17316. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17317. [else ((super type-check-exp env) e)]
  17318. )))
  17319. \end{lstlisting}
  17320. \caption{Type checker for the \LangGrad{} language, part 3.}
  17321. \label{fig:type-check-Rgradual-3}
  17322. \end{figure}
  17323. \begin{figure}[tbp]
  17324. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17325. (define/public (join t1 t2)
  17326. (match* (t1 t2)
  17327. [('Integer 'Integer) 'Integer]
  17328. [('Boolean 'Boolean) 'Boolean]
  17329. [('Void 'Void) 'Void]
  17330. [('Any t2) t2]
  17331. [(t1 'Any) t1]
  17332. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17333. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17334. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17335. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17336. -> ,(join rt1 rt2))]))
  17337. (define/public (meet t1 t2)
  17338. (match* (t1 t2)
  17339. [('Integer 'Integer) 'Integer]
  17340. [('Boolean 'Boolean) 'Boolean]
  17341. [('Void 'Void) 'Void]
  17342. [('Any t2) 'Any]
  17343. [(t1 'Any) 'Any]
  17344. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17345. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17346. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17347. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17348. -> ,(meet rt1 rt2))]))
  17349. (define/public (make-cast e src tgt)
  17350. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17351. (define/public (check-consistent? t1 t2 e)
  17352. (unless (consistent? t1 t2)
  17353. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17354. (define/override (type-check-op op arg-types args e)
  17355. (match (dict-ref (operator-types) op)
  17356. [`(,param-types . ,return-type)
  17357. (for ([at arg-types] [pt param-types])
  17358. (check-consistent? at pt e))
  17359. (values return-type
  17360. (for/list ([e args] [s arg-types] [t param-types])
  17361. (make-cast e s t)))]
  17362. [else (error 'type-check-op "unrecognized ~a" op)]))
  17363. (define explicit-prim-ops
  17364. (set-union
  17365. (type-predicates)
  17366. (set 'procedure-arity 'eq?
  17367. 'vector 'vector-length 'vector-ref 'vector-set!
  17368. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17369. (define/override (fun-def-type d)
  17370. (match d
  17371. [(Def f params rt info body)
  17372. (define ps
  17373. (for/list ([p params])
  17374. (match p
  17375. [`[,x : ,T] T]
  17376. [(? symbol?) 'Any]
  17377. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17378. `(,@ps -> ,rt)]
  17379. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17380. \end{lstlisting}
  17381. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17382. \label{fig:type-check-Rgradual-aux}
  17383. \end{figure}
  17384. \clearpage
  17385. \section{Interpreting \LangCast{}}
  17386. \label{sec:interp-casts}
  17387. The runtime behavior of first-order casts is straightforward, that is,
  17388. casts involving simple types such as \code{Integer} and
  17389. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  17390. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  17391. puts the integer into a tagged value
  17392. (Figure~\ref{fig:interp-Lany}). Similarly, a cast from \code{Any} to
  17393. \code{Integer} is accomplished with the \code{Project} operator, that
  17394. is, by checking the value's tag and either retrieving the underlying
  17395. integer or signaling an error if it the tag is not the one for
  17396. integers (Figure~\ref{fig:interp-Lany-aux}).
  17397. %
  17398. Things get more interesting for higher-order casts, that is, casts
  17399. involving function or vector types.
  17400. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  17401. Any)} to \code{(Integer -> Integer)}. When a function flows through
  17402. this cast at runtime, we can't know in general whether the function
  17403. will always return an integer.\footnote{Predicting the return value of
  17404. a function is equivalent to the halting problem, which is
  17405. undecidable.} The \LangCast{} interpreter therefore delays the checking
  17406. of the cast until the function is applied. This is accomplished by
  17407. wrapping \code{maybe-inc} in a new function that casts its parameter
  17408. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  17409. casts the return value from \code{Any} to \code{Integer}.
  17410. Turning our attention to casts involving vector types, we consider the
  17411. example in Figure~\ref{fig:map-bang} that defines a
  17412. partially-typed version of \code{map} whose parameter \code{v} has
  17413. type \code{(Vector Any Any)} and that updates \code{v} in place
  17414. instead of returning a new vector. So we name this function
  17415. \code{map!}. We apply \code{map!} to a vector of integers, so
  17416. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17417. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17418. cast between vector types would be a build a new vector whose elements
  17419. are the result of casting each of the original elements to the
  17420. appropriate target type. However, this approach is only valid for
  17421. immutable vectors; and our vectors are mutable. In the example of
  17422. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  17423. the updates inside of \code{map!} would happen to the new vector
  17424. and not the original one.
  17425. \begin{figure}[tbp]
  17426. % gradual_test_11.rkt
  17427. \begin{lstlisting}
  17428. (define (map! [f : (Any -> Any)]
  17429. [v : (Vector Any Any)]) : Void
  17430. (begin
  17431. (vector-set! v 0 (f (vector-ref v 0)))
  17432. (vector-set! v 1 (f (vector-ref v 1)))))
  17433. (define (inc x) (+ x 1))
  17434. (let ([v (vector 0 41)])
  17435. (begin (map! inc v) (vector-ref v 1)))
  17436. \end{lstlisting}
  17437. \caption{An example involving casts on vectors.}
  17438. \label{fig:map-bang}
  17439. \end{figure}
  17440. Instead the interpreter needs to create a new kind of value, a
  17441. \emph{vector proxy}, that intercepts every vector operation. On a
  17442. read, the proxy reads from the underlying vector and then applies a
  17443. cast to the resulting value. On a write, the proxy casts the argument
  17444. value and then performs the write to the underlying vector. For the
  17445. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17446. \code{0} from \code{Integer} to \code{Any}. For the first
  17447. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  17448. to \code{Integer}.
  17449. The final category of cast that we need to consider are casts between
  17450. the \code{Any} type and either a function or a vector
  17451. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17452. in which parameter \code{v} does not have a type annotation, so it is
  17453. given type \code{Any}. In the call to \code{map!}, the vector has
  17454. type \code{(Vector Integer Integer)} so the type checker inserts a
  17455. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  17456. thought is to use \code{Inject}, but that doesn't work because
  17457. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17458. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17459. to \code{Any}.
  17460. \begin{figure}[tbp]
  17461. \begin{lstlisting}
  17462. (define (map! [f : (Any -> Any)] v) : Void
  17463. (begin
  17464. (vector-set! v 0 (f (vector-ref v 0)))
  17465. (vector-set! v 1 (f (vector-ref v 1)))))
  17466. (define (inc x) (+ x 1))
  17467. (let ([v (vector 0 41)])
  17468. (begin (map! inc v) (vector-ref v 1)))
  17469. \end{lstlisting}
  17470. \caption{Casting a vector to \code{Any}.}
  17471. \label{fig:map-any}
  17472. \end{figure}
  17473. The \LangCast{} interpreter uses an auxiliary function named
  17474. \code{apply-cast} to cast a value from a source type to a target type,
  17475. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17476. of the kinds of casts that we've discussed in this section.
  17477. \begin{figure}[tbp]
  17478. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17479. (define/public (apply-cast v s t)
  17480. (match* (s t)
  17481. [(t1 t2) #:when (equal? t1 t2) v]
  17482. [('Any t2)
  17483. (match t2
  17484. [`(,ts ... -> ,rt)
  17485. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17486. (define v^ (apply-project v any->any))
  17487. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17488. [`(Vector ,ts ...)
  17489. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17490. (define v^ (apply-project v vec-any))
  17491. (apply-cast v^ vec-any `(Vector ,@ts))]
  17492. [else (apply-project v t2)])]
  17493. [(t1 'Any)
  17494. (match t1
  17495. [`(,ts ... -> ,rt)
  17496. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17497. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17498. (apply-inject v^ (any-tag any->any))]
  17499. [`(Vector ,ts ...)
  17500. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17501. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17502. (apply-inject v^ (any-tag vec-any))]
  17503. [else (apply-inject v (any-tag t1))])]
  17504. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17505. (define x (gensym 'x))
  17506. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17507. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17508. (define cast-writes
  17509. (for/list ([t1 ts1] [t2 ts2])
  17510. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17511. `(vector-proxy ,(vector v (apply vector cast-reads)
  17512. (apply vector cast-writes)))]
  17513. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17514. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17515. `(function ,xs ,(Cast
  17516. (Apply (Value v)
  17517. (for/list ([x xs][t1 ts1][t2 ts2])
  17518. (Cast (Var x) t2 t1)))
  17519. rt1 rt2) ())]
  17520. ))
  17521. \end{lstlisting}
  17522. \caption{The \code{apply-cast} auxiliary method.}
  17523. \label{fig:apply-cast}
  17524. \end{figure}
  17525. The interpreter for \LangCast{} is defined in
  17526. Figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  17527. dispatching to \code{apply-cast}. To handle the addition of vector
  17528. proxies, we update the vector primitives in \code{interp-op} using the
  17529. functions in Figure~\ref{fig:guarded-vector}.
  17530. \begin{figure}[tbp]
  17531. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17532. (define interp-Lcast-class
  17533. (class interp-Lwhile-class
  17534. (super-new)
  17535. (inherit apply-fun apply-inject apply-project)
  17536. (define/override (interp-op op)
  17537. (match op
  17538. ['vector-length guarded-vector-length]
  17539. ['vector-ref guarded-vector-ref]
  17540. ['vector-set! guarded-vector-set!]
  17541. ['any-vector-ref (lambda (v i)
  17542. (match v [`(tagged ,v^ ,tg)
  17543. (guarded-vector-ref v^ i)]))]
  17544. ['any-vector-set! (lambda (v i a)
  17545. (match v [`(tagged ,v^ ,tg)
  17546. (guarded-vector-set! v^ i a)]))]
  17547. ['any-vector-length (lambda (v)
  17548. (match v [`(tagged ,v^ ,tg)
  17549. (guarded-vector-length v^)]))]
  17550. [else (super interp-op op)]
  17551. ))
  17552. (define/override ((interp-exp env) e)
  17553. (define (recur e) ((interp-exp env) e))
  17554. (match e
  17555. [(Value v) v]
  17556. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17557. [else ((super interp-exp env) e)]))
  17558. ))
  17559. (define (interp-Lcast p)
  17560. (send (new interp-Lcast-class) interp-program p))
  17561. \end{lstlisting}
  17562. \caption{The interpreter for \LangCast{}.}
  17563. \label{fig:interp-Lcast}
  17564. \end{figure}
  17565. \begin{figure}[tbp]
  17566. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17567. (define (guarded-vector-ref vec i)
  17568. (match vec
  17569. [`(vector-proxy ,proxy)
  17570. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17571. (define rd (vector-ref (vector-ref proxy 1) i))
  17572. (apply-fun rd (list val) 'guarded-vector-ref)]
  17573. [else (vector-ref vec i)]))
  17574. (define (guarded-vector-set! vec i arg)
  17575. (match vec
  17576. [`(vector-proxy ,proxy)
  17577. (define wr (vector-ref (vector-ref proxy 2) i))
  17578. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17579. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17580. [else (vector-set! vec i arg)]))
  17581. (define (guarded-vector-length vec)
  17582. (match vec
  17583. [`(vector-proxy ,proxy)
  17584. (guarded-vector-length (vector-ref proxy 0))]
  17585. [else (vector-length vec)]))
  17586. \end{lstlisting}
  17587. \caption{The guarded-vector auxiliary functions.}
  17588. \label{fig:guarded-vector}
  17589. \end{figure}
  17590. \section{Lower Casts}
  17591. \label{sec:lower-casts}
  17592. The next step in the journey towards x86 is the \code{lower-casts}
  17593. pass that translates the casts in \LangCast{} to the lower-level
  17594. \code{Inject} and \code{Project} operators and a new operator for
  17595. creating vector proxies, extending the \LangLoop{} language to create
  17596. \LangProxy{}. We recommend creating an auxiliary function named
  17597. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17598. and a target type, and translates it to expression in \LangProxy{} that has
  17599. the same behavior as casting the expression from the source to the
  17600. target type in the interpreter.
  17601. The \code{lower-cast} function can follow a code structure similar to
  17602. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17603. the interpreter for \LangCast{} because it must handle the same cases as
  17604. \code{apply-cast} and it needs to mimic the behavior of
  17605. \code{apply-cast}. The most interesting cases are those concerning the
  17606. casts between two vector types and between two function types.
  17607. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  17608. type to another vector type is accomplished by creating a proxy that
  17609. intercepts the operations on the underlying vector. Here we make the
  17610. creation of the proxy explicit with the \code{vector-proxy} primitive
  17611. operation. It takes three arguments, the first is an expression for
  17612. the vector, the second is a vector of functions for casting an element
  17613. that is being read from the vector, and the third is a vector of
  17614. functions for casting an element that is being written to the vector.
  17615. You can create the functions using \code{Lambda}. Also, as we shall
  17616. see in the next section, we need to differentiate these vectors from
  17617. the user-created ones, so we recommend using a new primitive operator
  17618. named \code{raw-vector} instead of \code{vector} to create these
  17619. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17620. the output of \code{lower-casts} on the example in
  17621. Figure~\ref{fig:map-bang} that involved casting a vector of
  17622. integers to a vector of \code{Any}.
  17623. \begin{figure}[tbp]
  17624. \begin{lstlisting}
  17625. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17626. (begin
  17627. (vector-set! v 0 (f (vector-ref v 0)))
  17628. (vector-set! v 1 (f (vector-ref v 1)))))
  17629. (define (inc [x : Any]) : Any
  17630. (inject (+ (project x Integer) 1) Integer))
  17631. (let ([v (vector 0 41)])
  17632. (begin
  17633. (map! inc (vector-proxy v
  17634. (raw-vector (lambda: ([x9 : Integer]) : Any
  17635. (inject x9 Integer))
  17636. (lambda: ([x9 : Integer]) : Any
  17637. (inject x9 Integer)))
  17638. (raw-vector (lambda: ([x9 : Any]) : Integer
  17639. (project x9 Integer))
  17640. (lambda: ([x9 : Any]) : Integer
  17641. (project x9 Integer)))))
  17642. (vector-ref v 1)))
  17643. \end{lstlisting}
  17644. \caption{Output of \code{lower-casts} on the example in
  17645. Figure~\ref{fig:map-bang}.}
  17646. \label{fig:map-bang-lower-cast}
  17647. \end{figure}
  17648. A cast from one function type to another function type is accomplished
  17649. by generating a \code{Lambda} whose parameter and return types match
  17650. the target function type. The body of the \code{Lambda} should cast
  17651. the parameters from the target type to the source type (yes,
  17652. backwards! functions are contravariant\index{subject}{contravariant} in the
  17653. parameters), then call the underlying function, and finally cast the
  17654. result from the source return type to the target return type.
  17655. Figure~\ref{fig:map-lower-cast} shows the output of the
  17656. \code{lower-casts} pass on the \code{map} example in
  17657. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  17658. in the call to \code{map} is wrapped in a \code{lambda}.
  17659. \begin{figure}[tbp]
  17660. \begin{lstlisting}
  17661. (define (map [f : (Integer -> Integer)]
  17662. [v : (Vector Integer Integer)])
  17663. : (Vector Integer Integer)
  17664. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17665. (define (inc [x : Any]) : Any
  17666. (inject (+ (project x Integer) 1) Integer))
  17667. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17668. (project (inc (inject x9 Integer)) Integer))
  17669. (vector 0 41)) 1)
  17670. \end{lstlisting}
  17671. \caption{Output of \code{lower-casts} on the example in
  17672. Figure~\ref{fig:gradual-map}.}
  17673. \label{fig:map-lower-cast}
  17674. \end{figure}
  17675. \section{Differentiate Proxies}
  17676. \label{sec:differentiate-proxies}
  17677. So far the job of differentiating vectors and vector proxies has been
  17678. the job of the interpreter. For example, the interpreter for \LangCast{}
  17679. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17680. function in Figure~\ref{fig:guarded-vector}. In the
  17681. \code{differentiate-proxies} pass we shift this responsibility to the
  17682. generated code.
  17683. We begin by designing the output language $R^p_8$. In
  17684. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  17685. proxies. In $R^p_8$ we return the \code{Vector} type to
  17686. its original meaning, as the type of real vectors, and we introduce a
  17687. new type, \code{PVector}, whose values can be either real vectors or
  17688. vector proxies. This new type comes with a suite of new primitive
  17689. operations for creating and using values of type \code{PVector}. We
  17690. don't need to introduce a new type to represent vector proxies. A
  17691. proxy is represented by a vector containing three things: 1) the
  17692. underlying vector, 2) a vector of functions for casting elements that
  17693. are read from the vector, and 3) a vector of functions for casting
  17694. values to be written to the vector. So we define the following
  17695. abbreviation for the type of a vector proxy:
  17696. \[
  17697. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17698. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17699. \to (\key{PVector}~ T' \ldots)
  17700. \]
  17701. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17702. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17703. %
  17704. Next we describe each of the new primitive operations.
  17705. \begin{description}
  17706. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17707. (\key{PVector} $T \ldots$)]\ \\
  17708. %
  17709. This operation brands a vector as a value of the \code{PVector} type.
  17710. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17711. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17712. %
  17713. This operation brands a vector proxy as value of the \code{PVector} type.
  17714. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17715. \code{Boolean}] \ \\
  17716. %
  17717. returns true if the value is a vector proxy and false if it is a
  17718. real vector.
  17719. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17720. (\key{Vector} $T \ldots$)]\ \\
  17721. %
  17722. Assuming that the input is a vector (and not a proxy), this
  17723. operation returns the vector.
  17724. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17725. $\to$ \code{Boolean}]\ \\
  17726. %
  17727. Given a vector proxy, this operation returns the length of the
  17728. underlying vector.
  17729. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17730. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17731. %
  17732. Given a vector proxy, this operation returns the $i$th element of
  17733. the underlying vector.
  17734. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17735. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  17736. proxy, this operation writes a value to the $i$th element of the
  17737. underlying vector.
  17738. \end{description}
  17739. Now to discuss the translation that differentiates vectors from
  17740. proxies. First, every type annotation in the program must be
  17741. translated (recursively) to replace \code{Vector} with \code{PVector}.
  17742. Next, we must insert uses of \code{PVector} operations in the
  17743. appropriate places. For example, we wrap every vector creation with an
  17744. \code{inject-vector}.
  17745. \begin{lstlisting}
  17746. (vector |$e_1 \ldots e_n$|)
  17747. |$\Rightarrow$|
  17748. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17749. \end{lstlisting}
  17750. The \code{raw-vector} operator that we introduced in the previous
  17751. section does not get injected.
  17752. \begin{lstlisting}
  17753. (raw-vector |$e_1 \ldots e_n$|)
  17754. |$\Rightarrow$|
  17755. (vector |$e'_1 \ldots e'_n$|)
  17756. \end{lstlisting}
  17757. The \code{vector-proxy} primitive translates as follows.
  17758. \begin{lstlisting}
  17759. (vector-proxy |$e_1~e_2~e_3$|)
  17760. |$\Rightarrow$|
  17761. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17762. \end{lstlisting}
  17763. We translate the vector operations into conditional expressions that
  17764. check whether the value is a proxy and then dispatch to either the
  17765. appropriate proxy vector operation or the regular vector operation.
  17766. For example, the following is the translation for \code{vector-ref}.
  17767. \begin{lstlisting}
  17768. (vector-ref |$e_1$| |$i$|)
  17769. |$\Rightarrow$|
  17770. (let ([|$v~e_1$|])
  17771. (if (proxy? |$v$|)
  17772. (proxy-vector-ref |$v$| |$i$|)
  17773. (vector-ref (project-vector |$v$|) |$i$|)
  17774. \end{lstlisting}
  17775. Note in the case of a real vector, we must apply \code{project-vector}
  17776. before the \code{vector-ref}.
  17777. \section{Reveal Casts}
  17778. \label{sec:reveal-casts-gradual}
  17779. Recall that the \code{reveal-casts} pass
  17780. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  17781. \code{Inject} and \code{Project} into lower-level operations. In
  17782. particular, \code{Project} turns into a conditional expression that
  17783. inspects the tag and retrieves the underlying value. Here we need to
  17784. augment the translation of \code{Project} to handle the situation when
  17785. the target type is \code{PVector}. Instead of using
  17786. \code{vector-length} we need to use \code{proxy-vector-length}.
  17787. \begin{lstlisting}
  17788. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17789. |$\Rightarrow$|
  17790. (let |$\itm{tmp}$| |$e'$|
  17791. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17792. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17793. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17794. (exit)))
  17795. \end{lstlisting}
  17796. \section{Closure Conversion}
  17797. \label{sec:closure-conversion-gradual}
  17798. The closure conversion pass only requires one minor adjustment. The
  17799. auxiliary function that translates type annotations needs to be
  17800. updated to handle the \code{PVector} type.
  17801. \section{Explicate Control}
  17802. \label{sec:explicate-control-gradual}
  17803. Update the \code{explicate\_control} pass to handle the new primitive
  17804. operations on the \code{PVector} type.
  17805. \section{Select Instructions}
  17806. \label{sec:select-instructions-gradual}
  17807. Recall that the \code{select\_instructions} pass is responsible for
  17808. lowering the primitive operations into x86 instructions. So we need
  17809. to translate the new \code{PVector} operations to x86. To do so, the
  17810. first question we need to answer is how will we differentiate the two
  17811. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  17812. We need just one bit to accomplish this, and use the bit in position
  17813. $57$ of the 64-bit tag at the front of every vector (see
  17814. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  17815. for \code{inject-vector} we leave it that way.
  17816. \begin{lstlisting}
  17817. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  17818. |$\Rightarrow$|
  17819. movq |$e'_1$|, |$\itm{lhs'}$|
  17820. \end{lstlisting}
  17821. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  17822. \begin{lstlisting}
  17823. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  17824. |$\Rightarrow$|
  17825. movq |$e'_1$|, %r11
  17826. movq |$(1 << 57)$|, %rax
  17827. orq 0(%r11), %rax
  17828. movq %rax, 0(%r11)
  17829. movq %r11, |$\itm{lhs'}$|
  17830. \end{lstlisting}
  17831. The \code{proxy?} operation consumes the information so carefully
  17832. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  17833. isolates the $57$th bit to tell whether the value is a real vector or
  17834. a proxy.
  17835. \begin{lstlisting}
  17836. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  17837. |$\Rightarrow$|
  17838. movq |$e_1'$|, %r11
  17839. movq 0(%r11), %rax
  17840. sarq $57, %rax
  17841. andq $1, %rax
  17842. movq %rax, |$\itm{lhs'}$|
  17843. \end{lstlisting}
  17844. The \code{project-vector} operation is straightforward to translate,
  17845. so we leave it up to the reader.
  17846. Regarding the \code{proxy-vector} operations, the runtime provides
  17847. procedures that implement them (they are recursive functions!) so
  17848. here we simply need to translate these vector operations into the
  17849. appropriate function call. For example, here is the translation for
  17850. \code{proxy-vector-ref}.
  17851. \begin{lstlisting}
  17852. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  17853. |$\Rightarrow$|
  17854. movq |$e_1'$|, %rdi
  17855. movq |$e_2'$|, %rsi
  17856. callq proxy_vector_ref
  17857. movq %rax, |$\itm{lhs'}$|
  17858. \end{lstlisting}
  17859. We have another batch of vector operations to deal with, those for the
  17860. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  17861. \code{any-vector-ref} when there is a \code{vector-ref} on something
  17862. of type \code{Any}, and similarly for \code{any-vector-set!} and
  17863. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  17864. Section~\ref{sec:select-Rany} we selected instructions for these
  17865. operations based on the idea that the underlying value was a real
  17866. vector. But in the current setting, the underlying value is of type
  17867. \code{PVector}. So \code{any-vector-ref} can be translates to
  17868. pseudo-x86 as follows. We begin by projecting the underlying value out
  17869. of the tagged value and then call the \code{proxy\_vector\_ref}
  17870. procedure in the runtime.
  17871. \begin{lstlisting}
  17872. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17873. movq |$\neg 111$|, %rdi
  17874. andq |$e_1'$|, %rdi
  17875. movq |$e_2'$|, %rsi
  17876. callq proxy_vector_ref
  17877. movq %rax, |$\itm{lhs'}$|
  17878. \end{lstlisting}
  17879. The \code{any-vector-set!} and \code{any-vector-length} operators can
  17880. be translated in a similar way.
  17881. \begin{exercise}\normalfont\normalsize
  17882. Implement a compiler for the gradually-typed \LangGrad{} language by
  17883. extending and adapting your compiler for \LangLoop{}. Create 10 new
  17884. partially-typed test programs. In addition to testing with these
  17885. new programs, also test your compiler on all the tests for \LangLoop{}
  17886. and tests for \LangDyn{}. Sometimes you may get a type checking error
  17887. on the \LangDyn{} programs but you can adapt them by inserting
  17888. a cast to the \code{Any} type around each subexpression
  17889. causing a type error. While \LangDyn{} does not have explicit casts,
  17890. you can induce one by wrapping the subexpression \code{e}
  17891. with a call to an un-annotated identity function, like this:
  17892. \code{((lambda (x) x) e)}.
  17893. \end{exercise}
  17894. \begin{figure}[p]
  17895. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17896. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  17897. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17898. \node (Lwhilepp) at (0,4) {\large \LangProxy{}};
  17899. \node (Lwhileproxy) at (0,2) {\large \LangPVec{}};
  17900. \node (Lwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17901. \node (Lwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17902. \node (Lwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17903. \node (Lwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17904. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17905. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17906. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17907. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17908. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17909. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17910. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17911. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17912. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17913. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17914. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17915. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17916. \path[->,bend right=15] (Rgradual) edge [above] node
  17917. {\ttfamily\footnotesize type\_check} (Rgradualp);
  17918. \path[->,bend right=15] (Rgradualp) edge [above] node
  17919. {\ttfamily\footnotesize lower\_casts} (Lwhilepp);
  17920. \path[->,bend right=15] (Lwhilepp) edge [right] node
  17921. {\ttfamily\footnotesize differentiate\_proxies} (Lwhileproxy);
  17922. \path[->,bend left=15] (Lwhileproxy) edge [above] node
  17923. {\ttfamily\footnotesize shrink} (Lwhileproxy-2);
  17924. \path[->,bend left=15] (Lwhileproxy-2) edge [above] node
  17925. {\ttfamily\footnotesize uniquify} (Lwhileproxy-3);
  17926. \path[->,bend left=15] (Lwhileproxy-3) edge [above] node
  17927. {\ttfamily\footnotesize reveal\_functions} (Lwhileproxy-4);
  17928. \path[->,bend left=15] (Lwhileproxy-4) edge [above] node
  17929. {\ttfamily\footnotesize reveal\_casts} (Lwhileproxy-5);
  17930. \path[->,bend left=15] (Lwhileproxy-5) edge [left] node
  17931. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17932. \path[->,bend left=15] (F1-1) edge [below] node
  17933. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17934. \path[->,bend right=15] (F1-2) edge [above] node
  17935. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17936. \path[->,bend right=15] (F1-3) edge [above] node
  17937. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17938. \path[->,bend right=15] (F1-4) edge [above] node
  17939. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17940. \path[->,bend right=15] (F1-5) edge [right] node
  17941. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17942. \path[->,bend left=15] (C3-2) edge [left] node
  17943. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17944. \path[->,bend right=15] (x86-2) edge [left] node
  17945. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17946. \path[->,bend right=15] (x86-2-1) edge [below] node
  17947. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17948. \path[->,bend right=15] (x86-2-2) edge [left] node
  17949. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17950. \path[->,bend left=15] (x86-3) edge [above] node
  17951. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17952. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  17953. \end{tikzpicture}
  17954. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17955. \label{fig:Rgradual-passes}
  17956. \end{figure}
  17957. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  17958. for the compilation of \LangGrad{}.
  17959. \section{Further Reading}
  17960. This chapter just scratches the surface of gradual typing. The basic
  17961. approach described here is missing two key ingredients that one would
  17962. want in a implementation of gradual typing: blame
  17963. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17964. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17965. problem addressed by blame tracking is that when a cast on a
  17966. higher-order value fails, it often does so at a point in the program
  17967. that is far removed from the original cast. Blame tracking is a
  17968. technique for propagating extra information through casts and proxies
  17969. so that when a cast fails, the error message can point back to the
  17970. original location of the cast in the source program.
  17971. The problem addressed by space-efficient casts also relates to
  17972. higher-order casts. It turns out that in partially typed programs, a
  17973. function or vector can flow through very-many casts at runtime. With
  17974. the approach described in this chapter, each cast adds another
  17975. \code{lambda} wrapper or a vector proxy. Not only does this take up
  17976. considerable space, but it also makes the function calls and vector
  17977. operations slow. For example, a partially-typed version of quicksort
  17978. could, in the worst case, build a chain of proxies of length $O(n)$
  17979. around the vector, changing the overall time complexity of the
  17980. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17981. solution to this problem by representing casts using the coercion
  17982. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17983. long chains of proxies by compressing them into a concise normal
  17984. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17985. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17986. the Grift compiler.
  17987. \begin{center}
  17988. \url{https://github.com/Gradual-Typing/Grift}
  17989. \end{center}
  17990. There are also interesting interactions between gradual typing and
  17991. other language features, such as parametetric polymorphism,
  17992. information-flow types, and type inference, to name a few. We
  17993. recommend the reader to the online gradual typing bibliography:
  17994. \begin{center}
  17995. \url{http://samth.github.io/gradual-typing-bib/}
  17996. \end{center}
  17997. % TODO: challenge problem:
  17998. % type analysis and type specialization?
  17999. % coercions?
  18000. \fi
  18001. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18002. \chapter{Parametric Polymorphism}
  18003. \label{ch:Lpoly}
  18004. \index{subject}{parametric polymorphism}
  18005. \index{subject}{generics}
  18006. \if\edition\pythonEd
  18007. UNDER CONSTRUCTION
  18008. \fi
  18009. \if\edition\racketEd
  18010. This chapter studies the compilation of parametric
  18011. polymorphism\index{subject}{parametric polymorphism}
  18012. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  18013. Racket. Parametric polymorphism enables improved code reuse by
  18014. parameterizing functions and data structures with respect to the types
  18015. that they operate on. For example, Figure~\ref{fig:map-poly}
  18016. revisits the \code{map} example but this time gives it a more
  18017. fitting type. This \code{map} function is parameterized with
  18018. respect to the element type of the vector. The type of \code{map}
  18019. is the following polymorphic type as specified by the \code{All} and
  18020. the type parameter \code{a}.
  18021. \begin{lstlisting}
  18022. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18023. \end{lstlisting}
  18024. The idea is that \code{map} can be used at \emph{all} choices of a
  18025. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  18026. \code{map} to a vector of integers, a choice of \code{Integer} for
  18027. \code{a}, but we could have just as well applied \code{map} to a
  18028. vector of Booleans (and a function on Booleans).
  18029. \begin{figure}[tbp]
  18030. % poly_test_2.rkt
  18031. \begin{lstlisting}
  18032. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  18033. (define (map f v)
  18034. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18035. (define (inc [x : Integer]) : Integer (+ x 1))
  18036. (vector-ref (map inc (vector 0 41)) 1)
  18037. \end{lstlisting}
  18038. \caption{The \code{map} example using parametric polymorphism.}
  18039. \label{fig:map-poly}
  18040. \end{figure}
  18041. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  18042. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  18043. syntax. We add a second form for function definitions in which a type
  18044. declaration comes before the \code{define}. In the abstract syntax,
  18045. the return type in the \code{Def} is \code{Any}, but that should be
  18046. ignored in favor of the return type in the type declaration. (The
  18047. \code{Any} comes from using the same parser as in
  18048. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  18049. enables the use of an \code{All} type for a function, thereby making
  18050. it polymorphic. The grammar for types is extended to include
  18051. polymorphic types and type variables.
  18052. \begin{figure}[tp]
  18053. \centering
  18054. \fbox{
  18055. \begin{minipage}{0.96\textwidth}
  18056. \small
  18057. \[
  18058. \begin{array}{lcl}
  18059. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18060. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  18061. &\MID& \LP\key{:}~\Var~\Type\RP \\
  18062. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  18063. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  18064. \end{array}
  18065. \]
  18066. \end{minipage}
  18067. }
  18068. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  18069. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  18070. \label{fig:Rpoly-concrete-syntax}
  18071. \end{figure}
  18072. \begin{figure}[tp]
  18073. \centering
  18074. \fbox{
  18075. \begin{minipage}{0.96\textwidth}
  18076. \small
  18077. \[
  18078. \begin{array}{lcl}
  18079. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18080. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18081. &\MID& \DECL{\Var}{\Type} \\
  18082. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  18083. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18084. \end{array}
  18085. \]
  18086. \end{minipage}
  18087. }
  18088. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  18089. (Figure~\ref{fig:Lwhile-syntax}).}
  18090. \label{fig:Rpoly-syntax}
  18091. \end{figure}
  18092. By including polymorphic types in the $\Type$ non-terminal we choose
  18093. to make them first-class which has interesting repercussions on the
  18094. compiler. Many languages with polymorphism, such as
  18095. C++~\citep{stroustrup88:_param_types} and Standard
  18096. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  18097. it is useful to see an example of first-class polymorphism. In
  18098. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  18099. whose parameter is a polymorphic function. The occurrence of a
  18100. polymorphic type underneath a function type is enabled by the normal
  18101. recursive structure of the grammar for $\Type$ and the categorization
  18102. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  18103. applies the polymorphic function to a Boolean and to an integer.
  18104. \begin{figure}[tbp]
  18105. \begin{lstlisting}
  18106. (: apply-twice ((All (b) (b -> b)) -> Integer))
  18107. (define (apply-twice f)
  18108. (if (f #t) (f 42) (f 777)))
  18109. (: id (All (a) (a -> a)))
  18110. (define (id x) x)
  18111. (apply-twice id)
  18112. \end{lstlisting}
  18113. \caption{An example illustrating first-class polymorphism.}
  18114. \label{fig:apply-twice}
  18115. \end{figure}
  18116. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18117. three new responsibilities (compared to \LangLoop{}). The type checking of
  18118. function application is extended to handle the case where the operator
  18119. expression is a polymorphic function. In that case the type arguments
  18120. are deduced by matching the type of the parameters with the types of
  18121. the arguments.
  18122. %
  18123. The \code{match-types} auxiliary function carries out this deduction
  18124. by recursively descending through a parameter type \code{pt} and the
  18125. corresponding argument type \code{at}, making sure that they are equal
  18126. except when there is a type parameter on the left (in the parameter
  18127. type). If it is the first time that the type parameter has been
  18128. encountered, then the algorithm deduces an association of the type
  18129. parameter to the corresponding type on the right (in the argument
  18130. type). If it is not the first time that the type parameter has been
  18131. encountered, the algorithm looks up its deduced type and makes sure
  18132. that it is equal to the type on the right.
  18133. %
  18134. Once the type arguments are deduced, the operator expression is
  18135. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18136. type of the operator, but more importantly, records the deduced type
  18137. arguments. The return type of the application is the return type of
  18138. the polymorphic function, but with the type parameters replaced by the
  18139. deduced type arguments, using the \code{subst-type} function.
  18140. The second responsibility of the type checker is extending the
  18141. function \code{type-equal?} to handle the \code{All} type. This is
  18142. not quite a simple as equal on other types, such as function and
  18143. vector types, because two polymorphic types can be syntactically
  18144. different even though they are equivalent types. For example,
  18145. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  18146. Two polymorphic types should be considered equal if they differ only
  18147. in the choice of the names of the type parameters. The
  18148. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  18149. renames the type parameters of the first type to match the type
  18150. parameters of the second type.
  18151. The third responsibility of the type checker is making sure that only
  18152. defined type variables appear in type annotations. The
  18153. \code{check-well-formed} function defined in
  18154. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18155. sure that each type variable has been defined.
  18156. The output language of the type checker is \LangInst{}, defined in
  18157. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  18158. declaration and polymorphic function into a single definition, using
  18159. the \code{Poly} form, to make polymorphic functions more convenient to
  18160. process in next pass of the compiler.
  18161. \begin{figure}[tp]
  18162. \centering
  18163. \fbox{
  18164. \begin{minipage}{0.96\textwidth}
  18165. \small
  18166. \[
  18167. \begin{array}{lcl}
  18168. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18169. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18170. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18171. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18172. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18173. \end{array}
  18174. \]
  18175. \end{minipage}
  18176. }
  18177. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  18178. (Figure~\ref{fig:Lwhile-syntax}).}
  18179. \label{fig:Rpoly-prime-syntax}
  18180. \end{figure}
  18181. The output of the type checker on the polymorphic \code{map}
  18182. example is listed in Figure~\ref{fig:map-type-check}.
  18183. \begin{figure}[tbp]
  18184. % poly_test_2.rkt
  18185. \begin{lstlisting}
  18186. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18187. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18188. (define (inc [x : Integer]) : Integer (+ x 1))
  18189. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18190. (Integer))
  18191. inc (vector 0 41)) 1)
  18192. \end{lstlisting}
  18193. \caption{Output of the type checker on the \code{map} example.}
  18194. \label{fig:map-type-check}
  18195. \end{figure}
  18196. \begin{figure}[tbp]
  18197. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18198. (define type-check-poly-class
  18199. (class type-check-Lwhile-class
  18200. (super-new)
  18201. (inherit check-type-equal?)
  18202. (define/override (type-check-apply env e1 es)
  18203. (define-values (e^ ty) ((type-check-exp env) e1))
  18204. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18205. ((type-check-exp env) e)))
  18206. (match ty
  18207. [`(,ty^* ... -> ,rt)
  18208. (for ([arg-ty ty*] [param-ty ty^*])
  18209. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18210. (values e^ es^ rt)]
  18211. [`(All ,xs (,tys ... -> ,rt))
  18212. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18213. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18214. (match-types env^^ param-ty arg-ty)))
  18215. (define targs
  18216. (for/list ([x xs])
  18217. (match (dict-ref env^^ x (lambda () #f))
  18218. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18219. x (Apply e1 es))]
  18220. [ty ty])))
  18221. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18222. [else (error 'type-check "expected a function, not ~a" ty)]))
  18223. (define/override ((type-check-exp env) e)
  18224. (match e
  18225. [(Lambda `([,xs : ,Ts] ...) rT body)
  18226. (for ([T Ts]) ((check-well-formed env) T))
  18227. ((check-well-formed env) rT)
  18228. ((super type-check-exp env) e)]
  18229. [(HasType e1 ty)
  18230. ((check-well-formed env) ty)
  18231. ((super type-check-exp env) e)]
  18232. [else ((super type-check-exp env) e)]))
  18233. (define/override ((type-check-def env) d)
  18234. (verbose 'type-check "poly/def" d)
  18235. (match d
  18236. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18237. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18238. (for ([p ps]) ((check-well-formed ts-env) p))
  18239. ((check-well-formed ts-env) rt)
  18240. (define new-env (append ts-env (map cons xs ps) env))
  18241. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18242. (check-type-equal? ty^ rt body)
  18243. (Generic ts (Def f p:t* rt info body^))]
  18244. [else ((super type-check-def env) d)]))
  18245. (define/override (type-check-program p)
  18246. (match p
  18247. [(Program info body)
  18248. (type-check-program (ProgramDefsExp info '() body))]
  18249. [(ProgramDefsExp info ds body)
  18250. (define ds^ (combine-decls-defs ds))
  18251. (define new-env (for/list ([d ds^])
  18252. (cons (def-name d) (fun-def-type d))))
  18253. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18254. (define-values (body^ ty) ((type-check-exp new-env) body))
  18255. (check-type-equal? ty 'Integer body)
  18256. (ProgramDefsExp info ds^^ body^)]))
  18257. ))
  18258. \end{lstlisting}
  18259. \caption{Type checker for the \LangPoly{} language.}
  18260. \label{fig:type-check-Lvar0}
  18261. \end{figure}
  18262. \begin{figure}[tbp]
  18263. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18264. (define/override (type-equal? t1 t2)
  18265. (match* (t1 t2)
  18266. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18267. (define env (map cons xs ys))
  18268. (type-equal? (subst-type env T1) T2)]
  18269. [(other wise)
  18270. (super type-equal? t1 t2)]))
  18271. (define/public (match-types env pt at)
  18272. (match* (pt at)
  18273. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18274. [('Void 'Void) env] [('Any 'Any) env]
  18275. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18276. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18277. (match-types env^ pt1 at1))]
  18278. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18279. (define env^ (match-types env prt art))
  18280. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18281. (match-types env^^ pt1 at1))]
  18282. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18283. (define env^ (append (map cons pxs axs) env))
  18284. (match-types env^ pt1 at1)]
  18285. [((? symbol? x) at)
  18286. (match (dict-ref env x (lambda () #f))
  18287. [#f (error 'type-check "undefined type variable ~a" x)]
  18288. ['Type (cons (cons x at) env)]
  18289. [t^ (check-type-equal? at t^ 'matching) env])]
  18290. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18291. (define/public (subst-type env pt)
  18292. (match pt
  18293. ['Integer 'Integer] ['Boolean 'Boolean]
  18294. ['Void 'Void] ['Any 'Any]
  18295. [`(Vector ,ts ...)
  18296. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18297. [`(,ts ... -> ,rt)
  18298. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18299. [`(All ,xs ,t)
  18300. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18301. [(? symbol? x) (dict-ref env x)]
  18302. [else (error 'type-check "expected a type not ~a" pt)]))
  18303. (define/public (combine-decls-defs ds)
  18304. (match ds
  18305. ['() '()]
  18306. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18307. (unless (equal? name f)
  18308. (error 'type-check "name mismatch, ~a != ~a" name f))
  18309. (match type
  18310. [`(All ,xs (,ps ... -> ,rt))
  18311. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18312. (cons (Generic xs (Def name params^ rt info body))
  18313. (combine-decls-defs ds^))]
  18314. [`(,ps ... -> ,rt)
  18315. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18316. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18317. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18318. [`(,(Def f params rt info body) . ,ds^)
  18319. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18320. \end{lstlisting}
  18321. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18322. \label{fig:type-check-Lvar0-aux}
  18323. \end{figure}
  18324. \begin{figure}[tbp]
  18325. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18326. (define/public ((check-well-formed env) ty)
  18327. (match ty
  18328. ['Integer (void)]
  18329. ['Boolean (void)]
  18330. ['Void (void)]
  18331. [(? symbol? a)
  18332. (match (dict-ref env a (lambda () #f))
  18333. ['Type (void)]
  18334. [else (error 'type-check "undefined type variable ~a" a)])]
  18335. [`(Vector ,ts ...)
  18336. (for ([t ts]) ((check-well-formed env) t))]
  18337. [`(,ts ... -> ,t)
  18338. (for ([t ts]) ((check-well-formed env) t))
  18339. ((check-well-formed env) t)]
  18340. [`(All ,xs ,t)
  18341. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18342. ((check-well-formed env^) t)]
  18343. [else (error 'type-check "unrecognized type ~a" ty)]))
  18344. \end{lstlisting}
  18345. \caption{Well-formed types.}
  18346. \label{fig:well-formed-types}
  18347. \end{figure}
  18348. % TODO: interpreter for R'_10
  18349. \section{Compiling Polymorphism}
  18350. \label{sec:compiling-poly}
  18351. Broadly speaking, there are four approaches to compiling parametric
  18352. polymorphism, which we describe below.
  18353. \begin{description}
  18354. \item[Monomorphization] generates a different version of a polymorphic
  18355. function for each set of type arguments that it is used with,
  18356. producing type-specialized code. This approach results in the most
  18357. efficient code but requires whole-program compilation (no separate
  18358. compilation) and increases code size. For our current purposes
  18359. monomorphization is a non-starter because, with first-class
  18360. polymorphism, it is sometimes not possible to determine which
  18361. generic functions are used with which type arguments during
  18362. compilation. (It can be done at runtime, with just-in-time
  18363. compilation.) This approach is used to compile C++
  18364. templates~\citep{stroustrup88:_param_types} and polymorphic
  18365. functions in NESL~\citep{Blelloch:1993aa} and
  18366. ML~\citep{Weeks:2006aa}.
  18367. \item[Uniform representation] generates one version of each
  18368. polymorphic function but requires all values have a common ``boxed''
  18369. format, such as the tagged values of type \code{Any} in
  18370. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  18371. similarly to code in a dynamically typed language (like \LangDyn{}),
  18372. in which primitive operators require their arguments to be projected
  18373. from \code{Any} and their results are injected into \code{Any}. (In
  18374. object-oriented languages, the projection is accomplished via
  18375. virtual method dispatch.) The uniform representation approach is
  18376. compatible with separate compilation and with first-class
  18377. polymorphism. However, it produces the least-efficient code because
  18378. it introduces overhead in the entire program, including
  18379. non-polymorphic code. This approach is used in implementations of
  18380. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18381. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18382. Java~\citep{Bracha:1998fk}.
  18383. \item[Mixed representation] generates one version of each polymorphic
  18384. function, using a boxed representation for type
  18385. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  18386. and conversions are performed at the boundaries between monomorphic
  18387. and polymorphic (e.g. when a polymorphic function is instantiated
  18388. and called). This approach is compatible with separate compilation
  18389. and first-class polymorphism and maintains the efficiency of
  18390. monomorphic code. The tradeoff is increased overhead at the boundary
  18391. between monomorphic and polymorphic code. This approach is used in
  18392. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18393. Java 5 with the addition of autoboxing.
  18394. \item[Type passing] uses the unboxed representation in both
  18395. monomorphic and polymorphic code. Each polymorphic function is
  18396. compiled to a single function with extra parameters that describe
  18397. the type arguments. The type information is used by the generated
  18398. code to know how to access the unboxed values at runtime. This
  18399. approach is used in implementation of the Napier88
  18400. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18401. passing is compatible with separate compilation and first-class
  18402. polymorphism and maintains the efficiency for monomorphic
  18403. code. There is runtime overhead in polymorphic code from dispatching
  18404. on type information.
  18405. \end{description}
  18406. In this chapter we use the mixed representation approach, partly
  18407. because of its favorable attributes, and partly because it is
  18408. straightforward to implement using the tools that we have already
  18409. built to support gradual typing. To compile polymorphic functions, we
  18410. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18411. \LangCast{}.
  18412. \section{Erase Types}
  18413. \label{sec:erase-types}
  18414. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  18415. represent type variables. For example, Figure~\ref{fig:map-erase}
  18416. shows the output of the \code{erase-types} pass on the polymorphic
  18417. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18418. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  18419. \code{All} types are removed from the type of \code{map}.
  18420. \begin{figure}[tbp]
  18421. \begin{lstlisting}
  18422. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18423. : (Vector Any Any)
  18424. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18425. (define (inc [x : Integer]) : Integer (+ x 1))
  18426. (vector-ref ((cast map
  18427. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18428. ((Integer -> Integer) (Vector Integer Integer)
  18429. -> (Vector Integer Integer)))
  18430. inc (vector 0 41)) 1)
  18431. \end{lstlisting}
  18432. \caption{The polymorphic \code{map} example after type erasure.}
  18433. \label{fig:map-erase}
  18434. \end{figure}
  18435. This process of type erasure creates a challenge at points of
  18436. instantiation. For example, consider the instantiation of
  18437. \code{map} in Figure~\ref{fig:map-type-check}.
  18438. The type of \code{map} is
  18439. \begin{lstlisting}
  18440. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18441. \end{lstlisting}
  18442. and it is instantiated to
  18443. \begin{lstlisting}
  18444. ((Integer -> Integer) (Vector Integer Integer)
  18445. -> (Vector Integer Integer))
  18446. \end{lstlisting}
  18447. After erasure, the type of \code{map} is
  18448. \begin{lstlisting}
  18449. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18450. \end{lstlisting}
  18451. but we need to convert it to the instantiated type. This is easy to
  18452. do in the target language \LangCast{} with a single \code{cast}. In
  18453. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  18454. has been compiled to a \code{cast} from the type of \code{map} to
  18455. the instantiated type. The source and target type of a cast must be
  18456. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18457. because both the source and target are obtained from the same
  18458. polymorphic type of \code{map}, replacing the type parameters with
  18459. \code{Any} in the former and with the deduced type arguments in the
  18460. later. (Recall that the \code{Any} type is consistent with any type.)
  18461. To implement the \code{erase-types} pass, we recommend defining a
  18462. recursive auxiliary function named \code{erase-type} that applies the
  18463. following two transformations. It replaces type variables with
  18464. \code{Any}
  18465. \begin{lstlisting}
  18466. |$x$|
  18467. |$\Rightarrow$|
  18468. Any
  18469. \end{lstlisting}
  18470. and it removes the polymorphic \code{All} types.
  18471. \begin{lstlisting}
  18472. (All |$xs$| |$T_1$|)
  18473. |$\Rightarrow$|
  18474. |$T'_1$|
  18475. \end{lstlisting}
  18476. Apply the \code{erase-type} function to all of the type annotations in
  18477. the program.
  18478. Regarding the translation of expressions, the case for \code{Inst} is
  18479. the interesting one. We translate it into a \code{Cast}, as shown
  18480. below. The type of the subexpression $e$ is the polymorphic type
  18481. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  18482. $T$, the type $T'$. The target type $T''$ is the result of
  18483. substituting the arguments types $ts$ for the type parameters $xs$ in
  18484. $T$ followed by doing type erasure.
  18485. \begin{lstlisting}
  18486. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18487. |$\Rightarrow$|
  18488. (Cast |$e'$| |$T'$| |$T''$|)
  18489. \end{lstlisting}
  18490. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18491. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18492. Finally, each polymorphic function is translated to a regular
  18493. functions in which type erasure has been applied to all the type
  18494. annotations and the body.
  18495. \begin{lstlisting}
  18496. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18497. |$\Rightarrow$|
  18498. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18499. \end{lstlisting}
  18500. \begin{exercise}\normalfont\normalsize
  18501. Implement a compiler for the polymorphic language \LangPoly{} by
  18502. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18503. programs that use polymorphic functions. Some of them should make
  18504. use of first-class polymorphism.
  18505. \end{exercise}
  18506. \begin{figure}[p]
  18507. \begin{tikzpicture}[baseline=(current bounding box.center)]
  18508. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  18509. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  18510. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  18511. \node (Lwhilepp) at (0,4) {\large \LangProxy{}};
  18512. \node (Lwhileproxy) at (0,2) {\large \LangPVec{}};
  18513. \node (Lwhileproxy-2) at (3,2) {\large \LangPVec{}};
  18514. \node (Lwhileproxy-3) at (6,2) {\large \LangPVec{}};
  18515. \node (Lwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  18516. \node (Lwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  18517. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  18518. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  18519. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  18520. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  18521. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  18522. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18523. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18524. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18525. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18526. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18527. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18528. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18529. \path[->,bend right=15] (Rpoly) edge [above] node
  18530. {\ttfamily\footnotesize type\_check} (Rpolyp);
  18531. \path[->,bend right=15] (Rpolyp) edge [above] node
  18532. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  18533. \path[->,bend right=15] (Rgradualp) edge [above] node
  18534. {\ttfamily\footnotesize lower\_casts} (Lwhilepp);
  18535. \path[->,bend right=15] (Lwhilepp) edge [right] node
  18536. {\ttfamily\footnotesize differentiate\_proxies} (Lwhileproxy);
  18537. \path[->,bend left=15] (Lwhileproxy) edge [above] node
  18538. {\ttfamily\footnotesize shrink} (Lwhileproxy-2);
  18539. \path[->,bend left=15] (Lwhileproxy-2) edge [above] node
  18540. {\ttfamily\footnotesize uniquify} (Lwhileproxy-3);
  18541. \path[->,bend left=15] (Lwhileproxy-3) edge [above] node
  18542. {\ttfamily\footnotesize reveal\_functions} (Lwhileproxy-4);
  18543. \path[->,bend left=15] (Lwhileproxy-4) edge [above] node
  18544. {\ttfamily\footnotesize reveal\_casts} (Lwhileproxy-5);
  18545. \path[->,bend left=15] (Lwhileproxy-5) edge [left] node
  18546. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18547. \path[->,bend left=15] (F1-1) edge [below] node
  18548. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18549. \path[->,bend right=15] (F1-2) edge [above] node
  18550. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18551. \path[->,bend right=15] (F1-3) edge [above] node
  18552. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18553. \path[->,bend right=15] (F1-4) edge [above] node
  18554. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  18555. \path[->,bend right=15] (F1-5) edge [right] node
  18556. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18557. \path[->,bend left=15] (C3-2) edge [left] node
  18558. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18559. \path[->,bend right=15] (x86-2) edge [left] node
  18560. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18561. \path[->,bend right=15] (x86-2-1) edge [below] node
  18562. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18563. \path[->,bend right=15] (x86-2-2) edge [left] node
  18564. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18565. \path[->,bend left=15] (x86-3) edge [above] node
  18566. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18567. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  18568. \end{tikzpicture}
  18569. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18570. \label{fig:Rpoly-passes}
  18571. \end{figure}
  18572. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  18573. for the compilation of \LangPoly{}.
  18574. % TODO: challenge problem: specialization of instantiations
  18575. % Further Reading
  18576. \fi
  18577. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18578. \clearpage
  18579. \appendix
  18580. \chapter{Appendix}
  18581. \if\edition\racketEd
  18582. \section{Interpreters}
  18583. \label{appendix:interp}
  18584. \index{subject}{interpreter}
  18585. We provide interpreters for each of the source languages \LangInt{},
  18586. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18587. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18588. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18589. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18590. and x86 are in the \key{interp.rkt} file.
  18591. \section{Utility Functions}
  18592. \label{appendix:utilities}
  18593. The utility functions described in this section are in the
  18594. \key{utilities.rkt} file of the support code.
  18595. \paragraph{\code{interp-tests}}
  18596. The \key{interp-tests} function runs the compiler passes and the
  18597. interpreters on each of the specified tests to check whether each pass
  18598. is correct. The \key{interp-tests} function has the following
  18599. parameters:
  18600. \begin{description}
  18601. \item[name (a string)] a name to identify the compiler,
  18602. \item[typechecker] a function of exactly one argument that either
  18603. raises an error using the \code{error} function when it encounters a
  18604. type error, or returns \code{\#f} when it encounters a type
  18605. error. If there is no type error, the type checker returns the
  18606. program.
  18607. \item[passes] a list with one entry per pass. An entry is a list with
  18608. four things:
  18609. \begin{enumerate}
  18610. \item a string giving the name of the pass,
  18611. \item the function that implements the pass (a translator from AST
  18612. to AST),
  18613. \item a function that implements the interpreter (a function from
  18614. AST to result value) for the output language,
  18615. \item and a type checker for the output language. Type checkers for
  18616. the $R$ and $C$ languages are provided in the support code. For
  18617. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18618. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18619. type checker entry is optional. The support code does not provide
  18620. type checkers for the x86 languages.
  18621. \end{enumerate}
  18622. \item[source-interp] an interpreter for the source language. The
  18623. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18624. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  18625. \item[tests] a list of test numbers that specifies which tests to
  18626. run. (see below)
  18627. \end{description}
  18628. %
  18629. The \key{interp-tests} function assumes that the subdirectory
  18630. \key{tests} has a collection of Racket programs whose names all start
  18631. with the family name, followed by an underscore and then the test
  18632. number, ending with the file extension \key{.rkt}. Also, for each test
  18633. program that calls \code{read} one or more times, there is a file with
  18634. the same name except that the file extension is \key{.in} that
  18635. provides the input for the Racket program. If the test program is
  18636. expected to fail type checking, then there should be an empty file of
  18637. the same name but with extension \key{.tyerr}.
  18638. \paragraph{\code{compiler-tests}}
  18639. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18640. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18641. machine code and checks that the output is $42$. The parameters to the
  18642. \code{compiler-tests} function are similar to those of the
  18643. \code{interp-tests} function, and consist of
  18644. \begin{itemize}
  18645. \item a compiler name (a string),
  18646. \item a type checker,
  18647. \item description of the passes,
  18648. \item name of a test-family, and
  18649. \item a list of test numbers.
  18650. \end{itemize}
  18651. \paragraph{\code{compile-file}}
  18652. takes a description of the compiler passes (see the comment for
  18653. \key{interp-tests}) and returns a function that, given a program file
  18654. name (a string ending in \key{.rkt}), applies all of the passes and
  18655. writes the output to a file whose name is the same as the program file
  18656. name but with \key{.rkt} replaced with \key{.s}.
  18657. \paragraph{\code{read-program}}
  18658. takes a file path and parses that file (it must be a Racket program)
  18659. into an abstract syntax tree.
  18660. \paragraph{\code{parse-program}}
  18661. takes an S-expression representation of an abstract syntax tree and converts it into
  18662. the struct-based representation.
  18663. \paragraph{\code{assert}}
  18664. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18665. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18666. \paragraph{\code{lookup}}
  18667. % remove discussion of lookup? -Jeremy
  18668. takes a key and an alist, and returns the first value that is
  18669. associated with the given key, if there is one. If not, an error is
  18670. triggered. The alist may contain both immutable pairs (built with
  18671. \key{cons}) and mutable pairs (built with \key{mcons}).
  18672. %The \key{map2} function ...
  18673. \fi %\racketEd
  18674. \section{x86 Instruction Set Quick-Reference}
  18675. \label{sec:x86-quick-reference}
  18676. \index{subject}{x86}
  18677. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18678. do. We write $A \to B$ to mean that the value of $A$ is written into
  18679. location $B$. Address offsets are given in bytes. The instruction
  18680. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18681. registers (such as \code{\%rax}), or memory references (such as
  18682. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18683. reference per instruction. Other operands must be immediates or
  18684. registers.
  18685. \begin{table}[tbp]
  18686. \centering
  18687. \begin{tabular}{l|l}
  18688. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18689. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18690. \texttt{negq} $A$ & $- A \to A$ \\
  18691. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18692. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18693. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18694. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18695. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18696. \texttt{retq} & Pops the return address and jumps to it \\
  18697. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18698. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18699. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18700. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18701. be an immediate) \\
  18702. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18703. matches the condition code of the instruction, otherwise go to the
  18704. next instructions. The condition codes are \key{e} for ``equal'',
  18705. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18706. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18707. \texttt{jl} $L$ & \\
  18708. \texttt{jle} $L$ & \\
  18709. \texttt{jg} $L$ & \\
  18710. \texttt{jge} $L$ & \\
  18711. \texttt{jmp} $L$ & Jump to label $L$ \\
  18712. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18713. \texttt{movzbq} $A$, $B$ &
  18714. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18715. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18716. and the extra bytes of $B$ are set to zero.} \\
  18717. & \\
  18718. & \\
  18719. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18720. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18721. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18722. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18723. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18724. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18725. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18726. description of the condition codes. $A$ must be a single byte register
  18727. (e.g., \texttt{al} or \texttt{cl}).} \\
  18728. \texttt{setl} $A$ & \\
  18729. \texttt{setle} $A$ & \\
  18730. \texttt{setg} $A$ & \\
  18731. \texttt{setge} $A$ &
  18732. \end{tabular}
  18733. \vspace{5pt}
  18734. \caption{Quick-reference for the x86 instructions used in this book.}
  18735. \label{tab:x86-instr}
  18736. \end{table}
  18737. \if\edition\racketEd
  18738. \cleardoublepage
  18739. \section{Concrete Syntax for Intermediate Languages}
  18740. The concrete syntax of \LangAny{} is defined in
  18741. Figure~\ref{fig:Rany-concrete-syntax}.
  18742. \begin{figure}[tp]
  18743. \centering
  18744. \fbox{
  18745. \begin{minipage}{0.97\textwidth}\small
  18746. \[
  18747. \begin{array}{lcl}
  18748. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18749. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18750. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18751. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18752. \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18753. &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18754. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18755. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18756. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18757. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18758. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18759. \MID \LP\key{void?}\;\Exp\RP \\
  18760. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18761. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18762. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  18763. \end{array}
  18764. \]
  18765. \end{minipage}
  18766. }
  18767. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  18768. (Figure~\ref{fig:Rlam-syntax}).}
  18769. \label{fig:Rany-concrete-syntax}
  18770. \end{figure}
  18771. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  18772. \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  18773. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  18774. \ref{fig:c3-concrete-syntax}, respectively.
  18775. \begin{figure}[tbp]
  18776. \fbox{
  18777. \begin{minipage}{0.96\textwidth}
  18778. \small
  18779. \[
  18780. \begin{array}{lcl}
  18781. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  18782. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18783. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  18784. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  18785. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  18786. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  18787. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  18788. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  18789. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  18790. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  18791. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  18792. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  18793. \end{array}
  18794. \]
  18795. \end{minipage}
  18796. }
  18797. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  18798. \label{fig:c2-concrete-syntax}
  18799. \end{figure}
  18800. \begin{figure}[tp]
  18801. \fbox{
  18802. \begin{minipage}{0.96\textwidth}
  18803. \small
  18804. \[
  18805. \begin{array}{lcl}
  18806. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  18807. \\
  18808. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18809. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  18810. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  18811. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  18812. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  18813. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  18814. &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  18815. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  18816. \MID \LP\key{collect} \,\itm{int}\RP }\\
  18817. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  18818. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  18819. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  18820. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  18821. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  18822. \LangCFunM{} & ::= & \Def\ldots
  18823. \end{array}
  18824. \]
  18825. \end{minipage}
  18826. }
  18827. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  18828. \label{fig:c3-concrete-syntax}
  18829. \end{figure}
  18830. \fi % racketEd
  18831. \backmatter
  18832. \addtocontents{toc}{\vspace{11pt}}
  18833. %% \addtocontents{toc}{\vspace{11pt}}
  18834. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  18835. \nocite{*}\let\bibname\refname
  18836. \addcontentsline{toc}{fmbm}{\refname}
  18837. \printbibliography
  18838. \printindex{authors}{Author Index}
  18839. \printindex{subject}{Subject Index}
  18840. \end{document}
  18841. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  18842. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  18843. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  18844. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  18845. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  18846. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  18847. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  18848. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  18849. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  18850. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  18851. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  18852. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  18853. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  18854. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  18855. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  18856. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  18857. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  18858. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  18859. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  18860. % LocalWords: morekeywords fullflexible