book.tex 835 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  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. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. \makeatletter
  35. \newcommand{\captionabove}[2][]{%
  36. \vskip-\abovecaptionskip
  37. \vskip+\belowcaptionskip
  38. \ifx\@nnil#1\@nnil
  39. \caption{#2}%
  40. \else
  41. \caption[#1]{#2}%
  42. \fi
  43. \vskip+\abovecaptionskip
  44. \vskip-\belowcaptionskip
  45. }
  46. %% For multiple indices:
  47. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  48. \makeindex{subject}
  49. %\makeindex{authors}
  50. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  51. \if\edition\racketEd
  52. \lstset{%
  53. language=Lisp,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  56. deletekeywords={read,mapping,vector},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. \if\edition\pythonEd
  64. \lstset{%
  65. language=Python,
  66. basicstyle=\ttfamily\small,
  67. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  68. deletekeywords={},
  69. escapechar=|,
  70. columns=flexible,
  71. %moredelim=[is][\color{red}]{~}{~},
  72. showstringspaces=false
  73. }
  74. \fi
  75. %%% Any shortcut own defined macros place here
  76. %% sample of author macro:
  77. \input{defs}
  78. \newtheorem{exercise}[theorem]{Exercise}
  79. \numberwithin{theorem}{chapter}
  80. \numberwithin{definition}{chapter}
  81. \numberwithin{equation}{chapter}
  82. % Adjusted settings
  83. \setlength{\columnsep}{4pt}
  84. %% \begingroup
  85. %% \setlength{\intextsep}{0pt}%
  86. %% \setlength{\columnsep}{0pt}%
  87. %% \begin{wrapfigure}{r}{0.5\textwidth}
  88. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  89. %% \caption{Basic layout}
  90. %% \end{wrapfigure}
  91. %% \lipsum[1]
  92. %% \endgroup
  93. \newbox\oiintbox
  94. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  95. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  96. \def\oiint{\copy\oiintbox}
  97. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  98. %\usepackage{showframe}
  99. \def\ShowFrameLinethickness{0.125pt}
  100. \addbibresource{book.bib}
  101. \if\edition\pythonEd
  102. \addbibresource{python.bib}
  103. \fi
  104. \begin{document}
  105. \frontmatter
  106. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  107. \HalfTitle{Essentials of Compilation}
  108. \halftitlepage
  109. \clearemptydoublepage
  110. \Title{Essentials of Compilation}
  111. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  112. %\edition{First Edition}
  113. \BookAuthor{Jeremy G. Siek}
  114. \imprint{The MIT Press\\
  115. Cambridge, Massachusetts\\
  116. London, England}
  117. \begin{copyrightpage}
  118. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  119. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  120. Subject to such license, all rights are reserved. \\[2ex]
  121. \includegraphics{CCBY-logo}
  122. The MIT Press would like to thank the anonymous peer reviewers who
  123. provided comments on drafts of this book. The generous work of
  124. academic experts is essential for establishing the authority and
  125. quality of our publications. We acknowledge with gratitude the
  126. contributions of these otherwise uncredited readers.
  127. This book was set in Times LT Std Roman by the author. Printed and
  128. bound in the United States of America.
  129. {\if\edition\racketEd
  130. Library of Congress Cataloging-in-Publication Data\\
  131. \ \\
  132. Names: Siek, Jeremy, author. \\
  133. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  134. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  135. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  136. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  137. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  138. LC record available at https://lccn.loc.gov/2022015399\\
  139. LC ebook record available at https://lccn.loc.gov/2022015400\\
  140. \ \\
  141. \fi}
  142. %
  143. {\if\edition\pythonEd
  144. Library of Congress Cataloging-in-Publication Data\\
  145. \ \\
  146. Names: Siek, Jeremy, author. \\
  147. Title: Essentials of compilation : an incremental approach in Python / Jeremy G. Siek. \\
  148. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  149. bibliographical references and index. \\
  150. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  151. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  152. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  153. language) | Programming languages (Electronic computers) | Computer
  154. programming. \\
  155. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  156. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  157. LC record available at https://lccn.loc.gov/2022043053\\
  158. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  159. \ \\
  160. \fi}
  161. 10 9 8 7 6 5 4 3 2 1
  162. %% Jeremy G. Siek. Available for free viewing
  163. %% or personal downloading under the
  164. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  165. %% license.
  166. %% Copyright in this monograph has been licensed exclusively to The MIT
  167. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  168. %% version to the public in 2022. All inquiries regarding rights should
  169. %% be addressed to The MIT Press, Rights and Permissions Department.
  170. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  171. %% All rights reserved. No part of this book may be reproduced in any
  172. %% form by any electronic or mechanical means (including photocopying,
  173. %% recording, or information storage and retrieval) without permission in
  174. %% writing from the publisher.
  175. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  176. %% United States of America.
  177. %% Library of Congress Cataloging-in-Publication Data is available.
  178. %% ISBN:
  179. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  180. \end{copyrightpage}
  181. \dedication{This book is dedicated to Katie, my partner in everything,
  182. my children, who grew up during the writing of this book, and the
  183. programming language students at Indiana University, whose
  184. thoughtful questions made this a better book.}
  185. %% \begin{epigraphpage}
  186. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  187. %% \textit{Book Name if any}}
  188. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  189. %% \end{epigraphpage}
  190. \tableofcontents
  191. %\listoffigures
  192. %\listoftables
  193. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  194. \chapter*{Preface}
  195. \addcontentsline{toc}{fmbm}{Preface}
  196. There is a magical moment when a programmer presses the \emph{run}
  197. button and the software begins to execute. Somehow a program written
  198. in a high-level language is running on a computer that is capable only
  199. of shuffling bits. Here we reveal the wizardry that makes that moment
  200. possible. Beginning with the groundbreaking work of Backus and
  201. colleagues in the 1950s, computer scientists developed techniques for
  202. constructing programs called \emph{compilers} that automatically
  203. translate high-level programs into machine code.
  204. We take you on a journey through constructing your own compiler for a
  205. small but powerful language. Along the way we explain the essential
  206. concepts, algorithms, and data structures that underlie compilers. We
  207. develop your understanding of how programs are mapped onto computer
  208. hardware, which is helpful in reasoning about properties at the
  209. junction of hardware and software, such as execution time, software
  210. errors, and security vulnerabilities. For those interested in
  211. pursuing compiler construction as a career, our goal is to provide a
  212. stepping-stone to advanced topics such as just-in-time compilation,
  213. program analysis, and program optimization. For those interested in
  214. designing and implementing programming languages, we connect language
  215. design choices to their impact on the compiler and the generated code.
  216. A compiler is typically organized as a sequence of stages that
  217. progressively translate a program to the code that runs on
  218. hardware. We take this approach to the extreme by partitioning our
  219. compiler into a large number of \emph{nanopasses}, each of which
  220. performs a single task. This enables the testing of each pass in
  221. isolation and focuses our attention, making the compiler far easier to
  222. understand.
  223. The most familiar approach to describing compilers is to dedicate each
  224. chapter to one pass. The problem with that approach is that it
  225. obfuscates how language features motivate design choices in a
  226. compiler. We instead take an \emph{incremental} approach in which we
  227. build a complete compiler in each chapter, starting with a small input
  228. language that includes only arithmetic and variables. We add new
  229. language features in subsequent chapters, extending the compiler as
  230. necessary.
  231. Our choice of language features is designed to elicit fundamental
  232. concepts and algorithms used in compilers.
  233. \begin{itemize}
  234. \item We begin with integer arithmetic and local variables in
  235. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  236. the fundamental tools of compiler construction: \emph{abstract
  237. syntax trees} and \emph{recursive functions}.
  238. {\if\edition\pythonEd\pythonColor
  239. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  240. parser framework to create a parser for the language of integer
  241. arithmetic and local variables. We learn about the parsing
  242. algorithms inside Lark, including Earley and LALR(1).
  243. %
  244. \fi}
  245. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  246. \emph{graph coloring} to assign variables to machine registers.
  247. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  248. motivates an elegant recursive algorithm for translating them into
  249. conditional \code{goto} statements.
  250. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  251. variables}. This elicits the need for \emph{dataflow
  252. analysis} in the register allocator.
  253. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  254. \emph{garbage collection}.
  255. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  256. without lexical scoping, similar to functions in the C programming
  257. language~\citep{Kernighan:1988nx}. The reader learns about the
  258. procedure call stack and \emph{calling conventions} and how they interact
  259. with register allocation and garbage collection. The chapter also
  260. describes how to generate efficient tail calls.
  261. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  262. scoping, that is, \emph{lambda} expressions. The reader learns about
  263. \emph{closure conversion}, in which lambdas are translated into a
  264. combination of functions and tuples.
  265. % Chapter about classes and objects?
  266. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  267. point the input languages are statically typed. The reader extends
  268. the statically typed language with an \code{Any} type that serves
  269. as a target for compiling the dynamically typed language.
  270. %% {\if\edition\pythonEd\pythonColor
  271. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  272. %% \emph{classes}.
  273. %% \fi}
  274. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  275. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  276. in which different regions of a program may be static or dynamically
  277. typed. The reader implements runtime support for \emph{proxies} that
  278. allow values to safely move between regions.
  279. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  280. leveraging the \code{Any} type and type casts developed in chapters
  281. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  282. \end{itemize}
  283. There are many language features that we do not include. Our choices
  284. balance the incidental complexity of a feature versus the fundamental
  285. concepts that it exposes. For example, we include tuples and not
  286. records because although they both elicit the study of heap allocation and
  287. garbage collection, records come with more incidental complexity.
  288. Since 2009, drafts of this book have served as the textbook for
  289. sixteen-week compiler courses for upper-level undergraduates and
  290. first-year graduate students at the University of Colorado and Indiana
  291. University.
  292. %
  293. Students come into the course having learned the basics of
  294. programming, data structures and algorithms, and discrete
  295. mathematics.
  296. %
  297. At the beginning of the course, students form groups of two to four
  298. people. The groups complete approximately one chapter every two
  299. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  300. according to the students interests while respecting the dependencies
  301. between chapters shown in
  302. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  303. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  304. implementation of efficient tail calls.
  305. %
  306. The last two weeks of the course involve a final project in which
  307. students design and implement a compiler extension of their choosing.
  308. The last few chapters can be used in support of these projects. Many
  309. chapters include a challenge problem that we assign to the graduate
  310. students.
  311. For compiler courses at universities on the quarter system
  312. (about ten weeks in length), we recommend completing the course
  313. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  314. some scaffolding code to the students for each compiler pass.
  315. %
  316. The course can be adapted to emphasize functional languages by
  317. skipping chapter~\ref{ch:Lwhile} (loops) and including
  318. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  319. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  320. %
  321. %% \python{A course that emphasizes object-oriented languages would
  322. %% include Chapter~\ref{ch:Lobject}.}
  323. This book has been used in compiler courses at California Polytechnic
  324. State University, Portland State University, Rose–Hulman Institute of
  325. Technology, University of Freiburg, University of Massachusetts
  326. Lowell, and the University of Vermont.
  327. \begin{figure}[tp]
  328. \begin{tcolorbox}[colback=white]
  329. {\if\edition\racketEd
  330. \begin{tikzpicture}[baseline=(current bounding box.center)]
  331. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  332. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  333. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  334. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  335. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  336. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  337. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  338. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  339. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  340. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  341. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  342. \path[->] (C1) edge [above] node {} (C2);
  343. \path[->] (C2) edge [above] node {} (C3);
  344. \path[->] (C3) edge [above] node {} (C4);
  345. \path[->] (C4) edge [above] node {} (C5);
  346. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  347. \path[->] (C5) edge [above] node {} (C7);
  348. \path[->] (C6) edge [above] node {} (C7);
  349. \path[->] (C4) edge [above] node {} (C8);
  350. \path[->] (C4) edge [above] node {} (C9);
  351. \path[->] (C7) edge [above] node {} (C10);
  352. \path[->] (C8) edge [above] node {} (C10);
  353. \path[->] (C10) edge [above] node {} (C11);
  354. \end{tikzpicture}
  355. \fi}
  356. {\if\edition\pythonEd\pythonColor
  357. \begin{tikzpicture}[baseline=(current bounding box.center)]
  358. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  359. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  360. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  361. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  362. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  363. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  364. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  365. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  366. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  367. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  368. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  369. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  370. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  371. \path[->] (Prelim) edge [above] node {} (Var);
  372. \path[->] (Var) edge [above] node {} (Reg);
  373. \path[->] (Var) edge [above] node {} (Parse);
  374. \path[->] (Reg) edge [above] node {} (Cond);
  375. \path[->] (Cond) edge [above] node {} (Tuple);
  376. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  377. \path[->] (Cond) edge [above] node {} (Fun);
  378. \path[->] (Tuple) edge [above] node {} (Lam);
  379. \path[->] (Fun) edge [above] node {} (Lam);
  380. \path[->] (Cond) edge [above] node {} (Dyn);
  381. \path[->] (Cond) edge [above] node {} (Loop);
  382. \path[->] (Lam) edge [above] node {} (Gradual);
  383. \path[->] (Dyn) edge [above] node {} (Gradual);
  384. % \path[->] (Dyn) edge [above] node {} (CO);
  385. \path[->] (Gradual) edge [above] node {} (Generic);
  386. \end{tikzpicture}
  387. \fi}
  388. \end{tcolorbox}
  389. \caption{Diagram of chapter dependencies.}
  390. \label{fig:chapter-dependences}
  391. \end{figure}
  392. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  393. the implementation of the compiler and for the input language, so the
  394. reader should be proficient with Racket or Scheme. There are many
  395. excellent resources for learning Scheme and
  396. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  397. %
  398. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  399. both for the implementation of the compiler and for the input language, so the
  400. reader should be proficient with Python. There are many
  401. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  402. %
  403. The support code for this book is in the GitHub repository at
  404. the following location:
  405. \begin{center}\small\texttt
  406. https://github.com/IUCompilerCourse/
  407. \end{center}
  408. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  409. is helpful but not necessary for the reader to have taken a computer
  410. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  411. assembly language that are needed in the compiler.
  412. %
  413. We follow the System V calling
  414. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  415. that we generate works with the runtime system (written in C) when it
  416. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  417. operating systems on Intel hardware.
  418. %
  419. On the Windows operating system, \code{gcc} uses the Microsoft x64
  420. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  421. assembly code that we generate does \emph{not} work with the runtime
  422. system on Windows. One workaround is to use a virtual machine with
  423. Linux as the guest operating system.
  424. \section*{Acknowledgments}
  425. The tradition of compiler construction at Indiana University goes back
  426. to research and courses on programming languages by Daniel Friedman in
  427. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  428. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  429. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  430. the compiler course and continued the development of Chez Scheme.
  431. %
  432. The compiler course evolved to incorporate novel pedagogical ideas
  433. while also including elements of real-world compilers. One of
  434. Friedman's ideas was to split the compiler into many small
  435. passes. Another idea, called ``the game,'' was to test the code
  436. generated by each pass using interpreters.
  437. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  438. developed infrastructure to support this approach and evolved the
  439. course to use even smaller
  440. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  441. design decisions in this book are inspired by the assignment
  442. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  443. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  444. organization of the course made it difficult for students to
  445. understand the rationale for the compiler design. Ghuloum proposed the
  446. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  447. based.
  448. I thank the many students who served as teaching assistants for the
  449. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  450. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  451. garbage collector and x86 interpreter, Michael Vollmer for work on
  452. efficient tail calls, and Michael Vitousek for help with the first
  453. offering of the incremental compiler course at IU.
  454. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  455. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  456. Michael Wollowski for teaching courses based on drafts of this book
  457. and for their feedback. I thank the National Science Foundation for
  458. the grants that helped to support this work: Grant Numbers 1518844,
  459. 1763922, and 1814460.
  460. I thank Ronald Garcia for helping me survive Dybvig's compiler
  461. course in the early 2000s and especially for finding the bug that
  462. sent our garbage collector on a wild goose chase!
  463. \mbox{}\\
  464. \noindent Jeremy G. Siek \\
  465. Bloomington, Indiana
  466. \mainmatter
  467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  468. \chapter{Preliminaries}
  469. \label{ch:trees-recur}
  470. \setcounter{footnote}{0}
  471. In this chapter we introduce the basic tools needed to implement a
  472. compiler. Programs are typically input by a programmer as text, that
  473. is, a sequence of characters. The program-as-text representation is
  474. called \emph{concrete syntax}. We use concrete syntax to concisely
  475. write down and talk about programs. Inside the compiler, we use
  476. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  477. that efficiently supports the operations that the compiler needs to
  478. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  479. syntax}\index{subject}{abstract syntax
  480. tree}\index{subject}{AST}\index{subject}{program}
  481. The process of translating concrete syntax to abstract syntax is
  482. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  483. chapter~\ref{ch:parsing}}.
  484. \racket{This book does not cover the theory and implementation of parsing.
  485. We refer the readers interested in parsing to the thorough treatment
  486. of parsing by \citet{Aho:2006wb}. }%
  487. %
  488. \racket{A parser is provided in the support code for translating from
  489. concrete to abstract syntax.}%
  490. %
  491. \python{For now we use the \code{parse} function in Python's
  492. \code{ast} module to translate from concrete to abstract syntax.}
  493. ASTs can be represented inside the compiler in many different ways,
  494. depending on the programming language used to write the compiler.
  495. %
  496. \racket{We use Racket's
  497. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  498. feature to represent ASTs (section~\ref{sec:ast}).}
  499. %
  500. \python{We use Python classes and objects to represent ASTs, especially the
  501. classes defined in the standard \code{ast} module for the Python
  502. source language.}
  503. %
  504. We use grammars to define the abstract syntax of programming languages
  505. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  506. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  507. recursive functions to construct and deconstruct ASTs
  508. (section~\ref{sec:recursion}). This chapter provides a brief
  509. introduction to these components.
  510. \racket{\index{subject}{struct}}
  511. \python{\index{subject}{class}\index{subject}{object}}
  512. \section{Abstract Syntax Trees}
  513. \label{sec:ast}
  514. Compilers use abstract syntax trees to represent programs because they
  515. often need to ask questions such as, for a given part of a program,
  516. what kind of language feature is it? What are its subparts? Consider
  517. the program on the left and the diagram of its AST on the
  518. right~\eqref{eq:arith-prog}. This program is an addition operation
  519. that has two subparts, a \racket{read}\python{input} operation and a
  520. negation. The negation has another subpart, the integer constant
  521. \code{8}. By using a tree to represent the program, we can easily
  522. follow the links to go from one part of a program to its subparts.
  523. \begin{center}
  524. \begin{minipage}{0.4\textwidth}
  525. {\if\edition\racketEd
  526. \begin{lstlisting}
  527. (+ (read) (- 8))
  528. \end{lstlisting}
  529. \fi}
  530. {\if\edition\pythonEd\pythonColor
  531. \begin{lstlisting}
  532. input_int() + -8
  533. \end{lstlisting}
  534. \fi}
  535. \end{minipage}
  536. \begin{minipage}{0.4\textwidth}
  537. \begin{equation}
  538. \begin{tikzpicture}
  539. \node[draw] (plus) at (0 , 0) {\key{+}};
  540. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  541. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  542. \node[draw] (8) at (1 , -2) {\key{8}};
  543. \draw[->] (plus) to (read);
  544. \draw[->] (plus) to (minus);
  545. \draw[->] (minus) to (8);
  546. \end{tikzpicture}
  547. \label{eq:arith-prog}
  548. \end{equation}
  549. \end{minipage}
  550. \end{center}
  551. We use the standard terminology for trees to describe ASTs: each
  552. rectangle above is called a \emph{node}. The arrows connect a node to its
  553. \emph{children}, which are also nodes. The top-most node is the
  554. \emph{root}. Every node except for the root has a \emph{parent} (the
  555. node of which it is the child). If a node has no children, it is a
  556. \emph{leaf} node; otherwise it is an \emph{internal} node.
  557. \index{subject}{node}
  558. \index{subject}{children}
  559. \index{subject}{root}
  560. \index{subject}{parent}
  561. \index{subject}{leaf}
  562. \index{subject}{internal node}
  563. %% Recall that an \emph{symbolic expression} (S-expression) is either
  564. %% \begin{enumerate}
  565. %% \item an atom, or
  566. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  567. %% where $e_1$ and $e_2$ are each an S-expression.
  568. %% \end{enumerate}
  569. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  570. %% null value \code{'()}, etc. We can create an S-expression in Racket
  571. %% simply by writing a backquote (called a quasi-quote in Racket)
  572. %% followed by the textual representation of the S-expression. It is
  573. %% quite common to use S-expressions to represent a list, such as $a, b
  574. %% ,c$ in the following way:
  575. %% \begin{lstlisting}
  576. %% `(a . (b . (c . ())))
  577. %% \end{lstlisting}
  578. %% Each element of the list is in the first slot of a pair, and the
  579. %% second slot is either the rest of the list or the null value, to mark
  580. %% the end of the list. Such lists are so common that Racket provides
  581. %% special notation for them that removes the need for the periods
  582. %% and so many parenthesis:
  583. %% \begin{lstlisting}
  584. %% `(a b c)
  585. %% \end{lstlisting}
  586. %% The following expression creates an S-expression that represents AST
  587. %% \eqref{eq:arith-prog}.
  588. %% \begin{lstlisting}
  589. %% `(+ (read) (- 8))
  590. %% \end{lstlisting}
  591. %% When using S-expressions to represent ASTs, the convention is to
  592. %% represent each AST node as a list and to put the operation symbol at
  593. %% the front of the list. The rest of the list contains the children. So
  594. %% in the above case, the root AST node has operation \code{`+} and its
  595. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  596. %% diagram \eqref{eq:arith-prog}.
  597. %% To build larger S-expressions one often needs to splice together
  598. %% several smaller S-expressions. Racket provides the comma operator to
  599. %% splice an S-expression into a larger one. For example, instead of
  600. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  601. %% we could have first created an S-expression for AST
  602. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  603. %% S-expression.
  604. %% \begin{lstlisting}
  605. %% (define ast1.4 `(- 8))
  606. %% (define ast1_1 `(+ (read) ,ast1.4))
  607. %% \end{lstlisting}
  608. %% In general, the Racket expression that follows the comma (splice)
  609. %% can be any expression that produces an S-expression.
  610. {\if\edition\racketEd
  611. We define a Racket \code{struct} for each kind of node. For this
  612. chapter we require just two kinds of nodes: one for integer constants
  613. (aka literals\index{subject}{literals})
  614. and one for primitive operations. The following is the \code{struct}
  615. definition for integer constants.\footnote{All the AST structures are
  616. defined in the file \code{utilities.rkt} in the support code.}
  617. \begin{lstlisting}
  618. (struct Int (value))
  619. \end{lstlisting}
  620. An integer node contains just one thing: the integer value.
  621. We establish the convention that \code{struct} names, such
  622. as \code{Int}, are capitalized.
  623. To create an AST node for the integer $8$, we write \INT{8}.
  624. \begin{lstlisting}
  625. (define eight (Int 8))
  626. \end{lstlisting}
  627. We say that the value created by \INT{8} is an
  628. \emph{instance} of the
  629. \code{Int} structure.
  630. The following is the \code{struct} definition for primitive operations.
  631. \begin{lstlisting}
  632. (struct Prim (op args))
  633. \end{lstlisting}
  634. A primitive operation node includes an operator symbol \code{op} and a
  635. list of child arguments called \code{args}. For example, to create an
  636. AST that negates the number $8$, we write the following.
  637. \begin{lstlisting}
  638. (define neg-eight (Prim '- (list eight)))
  639. \end{lstlisting}
  640. Primitive operations may have zero or more children. The \code{read}
  641. operator has zero:
  642. \begin{lstlisting}
  643. (define rd (Prim 'read '()))
  644. \end{lstlisting}
  645. The addition operator has two children:
  646. \begin{lstlisting}
  647. (define ast1_1 (Prim '+ (list rd neg-eight)))
  648. \end{lstlisting}
  649. We have made a design choice regarding the \code{Prim} structure.
  650. Instead of using one structure for many different operations
  651. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  652. structure for each operation, as follows:
  653. \begin{lstlisting}
  654. (struct Read ())
  655. (struct Add (left right))
  656. (struct Neg (value))
  657. \end{lstlisting}
  658. The reason that we choose to use just one structure is that many parts
  659. of the compiler can use the same code for the different primitive
  660. operators, so we might as well just write that code once by using a
  661. single structure.
  662. %
  663. \fi}
  664. {\if\edition\pythonEd\pythonColor
  665. We use a Python \code{class} for each kind of node.
  666. The following is the class definition for
  667. constants (aka literals\index{subject}{literals})
  668. from the Python \code{ast} module.
  669. \begin{lstlisting}
  670. class Constant:
  671. def __init__(self, value):
  672. self.value = value
  673. \end{lstlisting}
  674. An integer constant node includes just one thing: the integer value.
  675. To create an AST node for the integer $8$, we write \INT{8}.
  676. \begin{lstlisting}
  677. eight = Constant(8)
  678. \end{lstlisting}
  679. We say that the value created by \INT{8} is an
  680. \emph{instance} of the \code{Constant} class.
  681. The following is the class definition for unary operators.
  682. \begin{lstlisting}
  683. class UnaryOp:
  684. def __init__(self, op, operand):
  685. self.op = op
  686. self.operand = operand
  687. \end{lstlisting}
  688. The specific operation is specified by the \code{op} parameter. For
  689. example, the class \code{USub} is for unary subtraction.
  690. (More unary operators are introduced in later chapters.) To create an AST that
  691. negates the number $8$, we write the following.
  692. \begin{lstlisting}
  693. neg_eight = UnaryOp(USub(), eight)
  694. \end{lstlisting}
  695. The call to the \code{input\_int} function is represented by the
  696. \code{Call} and \code{Name} classes.
  697. \begin{lstlisting}
  698. class Call:
  699. def __init__(self, func, args):
  700. self.func = func
  701. self.args = args
  702. class Name:
  703. def __init__(self, id):
  704. self.id = id
  705. \end{lstlisting}
  706. To create an AST node that calls \code{input\_int}, we write
  707. \begin{lstlisting}
  708. read = Call(Name('input_int'), [])
  709. \end{lstlisting}
  710. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  711. the \code{BinOp} class for binary operators.
  712. \begin{lstlisting}
  713. class BinOp:
  714. def __init__(self, left, op, right):
  715. self.op = op
  716. self.left = left
  717. self.right = right
  718. \end{lstlisting}
  719. Similar to \code{UnaryOp}, the specific operation is specified by the
  720. \code{op} parameter, which for now is just an instance of the
  721. \code{Add} class. So to create the AST
  722. node that adds negative eight to some user input, we write the following.
  723. \begin{lstlisting}
  724. ast1_1 = BinOp(read, Add(), neg_eight)
  725. \end{lstlisting}
  726. \fi}
  727. To compile a program such as \eqref{eq:arith-prog}, we need to know
  728. that the operation associated with the root node is addition and we
  729. need to be able to access its two
  730. children. \racket{Racket}\python{Python} provides pattern matching to
  731. support these kinds of queries, as we see in
  732. section~\ref{sec:pattern-matching}.
  733. We often write down the concrete syntax of a program even when we
  734. actually have in mind the AST, because the concrete syntax is more
  735. concise. We recommend that you always think of programs as abstract
  736. syntax trees.
  737. \section{Grammars}
  738. \label{sec:grammar}
  739. \index{subject}{integer}
  740. %\index{subject}{constant}
  741. A programming language can be thought of as a \emph{set} of programs.
  742. The set is infinite (that is, one can always create larger programs),
  743. so one cannot simply describe a language by listing all the
  744. programs in the language. Instead we write down a set of rules, a
  745. \emph{context-free grammar}, for building programs. Grammars are often used to
  746. define the concrete syntax of a language, but they can also be used to
  747. describe the abstract syntax. We write our rules in a variant of
  748. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  749. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  750. we describe a small language, named \LangInt{}, that consists of
  751. integers and arithmetic operations.\index{subject}{grammar}
  752. \index{subject}{context-free grammar}
  753. The first grammar rule for the abstract syntax of \LangInt{} says that an
  754. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  755. \begin{equation}
  756. \Exp ::= \INT{\Int} \label{eq:arith-int}
  757. \end{equation}
  758. %
  759. Each rule has a left-hand side and a right-hand side.
  760. If you have an AST node that matches the
  761. right-hand side, then you can categorize it according to the
  762. left-hand side.
  763. %
  764. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  765. are \emph{terminal} symbols and must literally appear in the program for the
  766. rule to be applicable.\index{subject}{terminal}
  767. %
  768. Our grammars do not mention \emph{white space}, that is, delimiter
  769. characters like spaces, tabs, and new lines. White space may be
  770. inserted between symbols for disambiguation and to improve
  771. readability. \index{subject}{white space}
  772. %
  773. A name such as $\Exp$ that is defined by the grammar rules is a
  774. \emph{nonterminal}. \index{subject}{nonterminal}
  775. %
  776. The name $\Int$ is also a nonterminal, but instead of defining it with
  777. a grammar rule, we define it with the following explanation. An
  778. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  779. $-$ (for negative integers), such that the sequence of decimals
  780. %
  781. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  782. enables the representation of integers using 63 bits, which simplifies
  783. several aspects of compilation.
  784. %
  785. Thus, these integers correspond to the Racket \texttt{fixnum}
  786. datatype on a 64-bit machine.}
  787. %
  788. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  789. enables the representation of integers using 64 bits, which simplifies
  790. several aspects of compilation. In contrast, integers in Python have
  791. unlimited precision, but the techniques needed to handle unlimited
  792. precision fall outside the scope of this book.}
  793. The second grammar rule is the \READOP{} operation, which receives an
  794. input integer from the user of the program.
  795. \begin{equation}
  796. \Exp ::= \READ{} \label{eq:arith-read}
  797. \end{equation}
  798. The third rule categorizes the negation of an $\Exp$ node as an
  799. $\Exp$.
  800. \begin{equation}
  801. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  802. \end{equation}
  803. We can apply these rules to categorize the ASTs that are in the
  804. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  805. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  806. following AST is an $\Exp$.
  807. \begin{center}
  808. \begin{minipage}{0.5\textwidth}
  809. \NEG{\INT{\code{8}}}
  810. \end{minipage}
  811. \begin{minipage}{0.25\textwidth}
  812. \begin{equation}
  813. \begin{tikzpicture}
  814. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  815. \node[draw, circle] (8) at (0, -1.2) {$8$};
  816. \draw[->] (minus) to (8);
  817. \end{tikzpicture}
  818. \label{eq:arith-neg8}
  819. \end{equation}
  820. \end{minipage}
  821. \end{center}
  822. The next two grammar rules are for addition and subtraction expressions:
  823. \begin{align}
  824. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  825. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  826. \end{align}
  827. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  828. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  829. \eqref{eq:arith-read}, and we have already categorized
  830. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  831. to show that
  832. \[
  833. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  834. \]
  835. is an $\Exp$ in the \LangInt{} language.
  836. If you have an AST for which these rules do not apply, then the
  837. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  838. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  839. because there is no rule for the \key{*} operator. Whenever we
  840. define a language with a grammar, the language includes only those
  841. programs that are justified by the grammar rules.
  842. {\if\edition\pythonEd\pythonColor
  843. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  844. There is a statement for printing the value of an expression
  845. \[
  846. \Stmt{} ::= \PRINT{\Exp}
  847. \]
  848. and a statement that evaluates an expression but ignores the result.
  849. \[
  850. \Stmt{} ::= \EXPR{\Exp}
  851. \]
  852. \fi}
  853. {\if\edition\racketEd
  854. The last grammar rule for \LangInt{} states that there is a
  855. \code{Program} node to mark the top of the whole program:
  856. \[
  857. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  858. \]
  859. The \code{Program} structure is defined as follows:
  860. \begin{lstlisting}
  861. (struct Program (info body))
  862. \end{lstlisting}
  863. where \code{body} is an expression. In further chapters, the \code{info}
  864. part is used to store auxiliary information, but for now it is
  865. just the empty list.
  866. \fi}
  867. {\if\edition\pythonEd\pythonColor
  868. The last grammar rule for \LangInt{} states that there is a
  869. \code{Module} node to mark the top of the whole program:
  870. \[
  871. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  872. \]
  873. The asterisk $*$ indicates a list of the preceding grammar item, in
  874. this case a list of statements.
  875. %
  876. The \code{Module} class is defined as follows:
  877. \begin{lstlisting}
  878. class Module:
  879. def __init__(self, body):
  880. self.body = body
  881. \end{lstlisting}
  882. where \code{body} is a list of statements.
  883. \fi}
  884. It is common to have many grammar rules with the same left-hand side
  885. but different right-hand sides, such as the rules for $\Exp$ in the
  886. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  887. combine several right-hand sides into a single rule.
  888. The concrete syntax for \LangInt{} is shown in
  889. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  890. \LangInt{} is shown in figure~\ref{fig:r0-syntax}. %
  891. %
  892. \racket{The \code{read-program} function provided in
  893. \code{utilities.rkt} of the support code reads a program from a file
  894. (the sequence of characters in the concrete syntax of Racket) and
  895. parses it into an abstract syntax tree. Refer to the description of
  896. \code{read-program} in appendix~\ref{appendix:utilities} for more
  897. details.}
  898. %
  899. \python{We recommend using the \code{parse} function in Python's
  900. \code{ast} module to convert the concrete syntax into an abstract
  901. syntax tree.}
  902. \newcommand{\LintGrammarRacket}{
  903. \begin{array}{rcl}
  904. \Type &::=& \key{Integer} \\
  905. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  906. \MID \CSUB{\Exp}{\Exp}
  907. \end{array}
  908. }
  909. \newcommand{\LintASTRacket}{
  910. \begin{array}{rcl}
  911. \Type &::=& \key{Integer} \\
  912. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  913. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  914. \end{array}
  915. }
  916. \newcommand{\LintGrammarPython}{
  917. \begin{array}{rcl}
  918. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  919. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  920. \end{array}
  921. }
  922. \newcommand{\LintASTPython}{
  923. \begin{array}{rcl}
  924. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  925. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  926. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  927. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  928. \end{array}
  929. }
  930. \begin{figure}[tp]
  931. \begin{tcolorbox}[colback=white]
  932. {\if\edition\racketEd
  933. \[
  934. \begin{array}{l}
  935. \LintGrammarRacket \\
  936. \begin{array}{rcl}
  937. \LangInt{} &::=& \Exp
  938. \end{array}
  939. \end{array}
  940. \]
  941. \fi}
  942. {\if\edition\pythonEd\pythonColor
  943. \[
  944. \begin{array}{l}
  945. \LintGrammarPython \\
  946. \begin{array}{rcl}
  947. \LangInt{} &::=& \Stmt^{*}
  948. \end{array}
  949. \end{array}
  950. \]
  951. \fi}
  952. \end{tcolorbox}
  953. \caption{The concrete syntax of \LangInt{}.}
  954. \label{fig:r0-concrete-syntax}
  955. \index{subject}{Lint@\LangInt{} concrete syntax}
  956. \end{figure}
  957. \begin{figure}[tp]
  958. \begin{tcolorbox}[colback=white]
  959. {\if\edition\racketEd
  960. \[
  961. \begin{array}{l}
  962. \LintASTRacket{} \\
  963. \begin{array}{rcl}
  964. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  965. \end{array}
  966. \end{array}
  967. \]
  968. \fi}
  969. {\if\edition\pythonEd\pythonColor
  970. \[
  971. \begin{array}{l}
  972. \LintASTPython\\
  973. \begin{array}{rcl}
  974. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  975. \end{array}
  976. \end{array}
  977. \]
  978. \fi}
  979. \end{tcolorbox}
  980. \python{
  981. \index{subject}{Constant@\texttt{Constant}}
  982. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  983. \index{subject}{USub@\texttt{USub}}
  984. \index{subject}{inputint@\texttt{input\_int}}
  985. \index{subject}{Call@\texttt{Call}}
  986. \index{subject}{Name@\texttt{Name}}
  987. \index{subject}{BinOp@\texttt{BinOp}}
  988. \index{subject}{Add@\texttt{Add}}
  989. \index{subject}{Sub@\texttt{Sub}}
  990. \index{subject}{print@\texttt{print}}
  991. \index{subject}{Expr@\texttt{Expr}}
  992. \index{subject}{Module@\texttt{Module}}
  993. }
  994. \caption{The abstract syntax of \LangInt{}.}
  995. \label{fig:r0-syntax}
  996. \index{subject}{Lint@\LangInt{} abstract syntax}
  997. \end{figure}
  998. \section{Pattern Matching}
  999. \label{sec:pattern-matching}
  1000. As mentioned in section~\ref{sec:ast}, compilers often need to access
  1001. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  1002. provides the \texttt{match} feature to access the parts of a value.
  1003. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  1004. \begin{center}
  1005. \begin{minipage}{1.0\textwidth}
  1006. {\if\edition\racketEd
  1007. \begin{lstlisting}
  1008. (match ast1_1
  1009. [(Prim op (list child1 child2))
  1010. (print op)])
  1011. \end{lstlisting}
  1012. \fi}
  1013. {\if\edition\pythonEd\pythonColor
  1014. \begin{lstlisting}
  1015. match ast1_1:
  1016. case BinOp(child1, op, child2):
  1017. print(op)
  1018. \end{lstlisting}
  1019. \fi}
  1020. \end{minipage}
  1021. \end{center}
  1022. {\if\edition\racketEd
  1023. %
  1024. In this example, the \texttt{match} form checks whether the AST
  1025. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1026. three pattern variables \texttt{op}, \texttt{child1}, and
  1027. \texttt{child2}. In general, a match clause consists of a
  1028. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1029. recursively defined to be a pattern variable, a structure name
  1030. followed by a pattern for each of the structure's arguments, or an
  1031. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1032. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1033. and chapter 9 of The Racket
  1034. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1035. for complete descriptions of \code{match}.)
  1036. %
  1037. The body of a match clause may contain arbitrary Racket code. The
  1038. pattern variables can be used in the scope of the body, such as
  1039. \code{op} in \code{(print op)}.
  1040. %
  1041. \fi}
  1042. %
  1043. %
  1044. {\if\edition\pythonEd\pythonColor
  1045. %
  1046. In the example above, the \texttt{match} form checks whether the AST
  1047. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1048. three pattern variables (\texttt{child1}, \texttt{op}, and
  1049. \texttt{child2}). In general, each \code{case} consists of a
  1050. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1051. recursively defined to be one of the following: a pattern variable, a
  1052. class name followed by a pattern for each of its constructor's
  1053. arguments, or other literals\index{subject}{literals} such as strings
  1054. or lists.
  1055. %
  1056. The body of each \code{case} may contain arbitrary Python code. The
  1057. pattern variables can be used in the body, such as \code{op} in
  1058. \code{print(op)}.
  1059. %
  1060. \fi}
  1061. A \code{match} form may contain several clauses, as in the following
  1062. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1063. the AST. The \code{match} proceeds through the clauses in order,
  1064. checking whether the pattern can match the input AST. The body of the
  1065. first clause that matches is executed. The output of \code{leaf} for
  1066. several ASTs is shown on the right side of the following:
  1067. \begin{center}
  1068. \begin{minipage}{0.6\textwidth}
  1069. {\if\edition\racketEd
  1070. \begin{lstlisting}
  1071. (define (leaf arith)
  1072. (match arith
  1073. [(Int n) #t]
  1074. [(Prim 'read '()) #t]
  1075. [(Prim '- (list e1)) #f]
  1076. [(Prim '+ (list e1 e2)) #f]
  1077. [(Prim '- (list e1 e2)) #f]))
  1078. (leaf (Prim 'read '()))
  1079. (leaf (Prim '- (list (Int 8))))
  1080. (leaf (Int 8))
  1081. \end{lstlisting}
  1082. \fi}
  1083. {\if\edition\pythonEd\pythonColor
  1084. \begin{lstlisting}
  1085. def leaf(arith):
  1086. match arith:
  1087. case Constant(n):
  1088. return True
  1089. case Call(Name('input_int'), []):
  1090. return True
  1091. case UnaryOp(USub(), e1):
  1092. return False
  1093. case BinOp(e1, Add(), e2):
  1094. return False
  1095. case BinOp(e1, Sub(), e2):
  1096. return False
  1097. print(leaf(Call(Name('input_int'), [])))
  1098. print(leaf(UnaryOp(USub(), eight)))
  1099. print(leaf(Constant(8)))
  1100. \end{lstlisting}
  1101. \fi}
  1102. \end{minipage}
  1103. \vrule
  1104. \begin{minipage}{0.25\textwidth}
  1105. {\if\edition\racketEd
  1106. \begin{lstlisting}
  1107. #t
  1108. #f
  1109. #t
  1110. \end{lstlisting}
  1111. \fi}
  1112. {\if\edition\pythonEd\pythonColor
  1113. \begin{lstlisting}
  1114. True
  1115. False
  1116. True
  1117. \end{lstlisting}
  1118. \fi}
  1119. \end{minipage}
  1120. \index{subject}{True@\TRUE{}}
  1121. \index{subject}{False@\FALSE{}}
  1122. \end{center}
  1123. When constructing a \code{match} expression, we refer to the grammar
  1124. definition to identify which nonterminal we are expecting to match
  1125. against, and then we make sure that (1) we have one
  1126. \racket{clause}\python{case} for each alternative of that nonterminal
  1127. and (2) the pattern in each \racket{clause}\python{case}
  1128. corresponds to the corresponding right-hand side of a grammar
  1129. rule. For the \code{match} in the \code{leaf} function, we refer to
  1130. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1131. nonterminal has five alternatives, so the \code{match} has five
  1132. \racket{clauses}\python{cases}. The pattern in each
  1133. \racket{clause}\python{case} corresponds to the right-hand side of a
  1134. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1135. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1136. translating from grammars to patterns, replace nonterminals such as
  1137. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1138. \code{e2}).
  1139. \section{Recursive Functions}
  1140. \label{sec:recursion}
  1141. \index{subject}{recursive function}
  1142. Programs are inherently recursive. For example, an expression is often
  1143. made of smaller expressions. Thus, the natural way to process an
  1144. entire program is to use a recursive function. As a first example of
  1145. such a recursive function, we define the function \code{is\_exp} as
  1146. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1147. value and determine whether or not it is an expression in \LangInt{}.
  1148. %
  1149. We say that a function is defined by \emph{structural recursion} if
  1150. it is defined using a sequence of match \racket{clauses}\python{cases}
  1151. that correspond to a grammar and the body of each
  1152. \racket{clause}\python{case} makes a recursive call on each child
  1153. node.\footnote{This principle of structuring code according to the
  1154. data definition is advocated in the book \emph{How to Design
  1155. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1156. second function, named \code{is\_stmt}, that recognizes whether a value
  1157. is a \LangInt{} statement.} \python{Finally, }
  1158. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1159. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1160. In general, we can write one recursive function to handle each
  1161. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1162. two examples at the bottom of the figure, the first is in
  1163. \LangInt{} and the second is not.
  1164. \begin{figure}[tp]
  1165. \begin{tcolorbox}[colback=white]
  1166. {\if\edition\racketEd
  1167. \begin{lstlisting}
  1168. (define (is_exp ast)
  1169. (match ast
  1170. [(Int n) #t]
  1171. [(Prim 'read '()) #t]
  1172. [(Prim '- (list e)) (is_exp e)]
  1173. [(Prim '+ (list e1 e2))
  1174. (and (is_exp e1) (is_exp e2))]
  1175. [(Prim '- (list e1 e2))
  1176. (and (is_exp e1) (is_exp e2))]
  1177. [else #f]))
  1178. (define (is_Lint ast)
  1179. (match ast
  1180. [(Program '() e) (is_exp e)]
  1181. [else #f]))
  1182. (is_Lint (Program '() ast1_1)
  1183. (is_Lint (Program '()
  1184. (Prim '* (list (Prim 'read '())
  1185. (Prim '+ (list (Int 8)))))))
  1186. \end{lstlisting}
  1187. \fi}
  1188. {\if\edition\pythonEd\pythonColor
  1189. \begin{lstlisting}
  1190. def is_exp(e):
  1191. match e:
  1192. case Constant(n):
  1193. return True
  1194. case Call(Name('input_int'), []):
  1195. return True
  1196. case UnaryOp(USub(), e1):
  1197. return is_exp(e1)
  1198. case BinOp(e1, Add(), e2):
  1199. return is_exp(e1) and is_exp(e2)
  1200. case BinOp(e1, Sub(), e2):
  1201. return is_exp(e1) and is_exp(e2)
  1202. case _:
  1203. return False
  1204. def is_stmt(s):
  1205. match s:
  1206. case Expr(Call(Name('print'), [e])):
  1207. return is_exp(e)
  1208. case Expr(e):
  1209. return is_exp(e)
  1210. case _:
  1211. return False
  1212. def is_Lint(p):
  1213. match p:
  1214. case Module(body):
  1215. return all([is_stmt(s) for s in body])
  1216. case _:
  1217. return False
  1218. print(is_Lint(Module([Expr(ast1_1)])))
  1219. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1220. UnaryOp(Add(), Constant(8))))])))
  1221. \end{lstlisting}
  1222. \fi}
  1223. \end{tcolorbox}
  1224. \caption{Example of recursive functions for \LangInt{}. These functions
  1225. recognize whether an AST is in \LangInt{}.}
  1226. \label{fig:exp-predicate}
  1227. \end{figure}
  1228. %% You may be tempted to merge the two functions into one, like this:
  1229. %% \begin{center}
  1230. %% \begin{minipage}{0.5\textwidth}
  1231. %% \begin{lstlisting}
  1232. %% (define (Lint ast)
  1233. %% (match ast
  1234. %% [(Int n) #t]
  1235. %% [(Prim 'read '()) #t]
  1236. %% [(Prim '- (list e)) (Lint e)]
  1237. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1238. %% [(Program '() e) (Lint e)]
  1239. %% [else #f]))
  1240. %% \end{lstlisting}
  1241. %% \end{minipage}
  1242. %% \end{center}
  1243. %% %
  1244. %% Sometimes such a trick will save a few lines of code, especially when
  1245. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1246. %% \emph{not} recommended because it can get you into trouble.
  1247. %% %
  1248. %% For example, the above function is subtly wrong:
  1249. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1250. %% returns true when it should return false.
  1251. \section{Interpreters}
  1252. \label{sec:interp_Lint}
  1253. \index{subject}{interpreter}
  1254. The behavior of a program is defined by the specification of the
  1255. programming language.
  1256. %
  1257. \racket{For example, the Scheme language is defined in the report by
  1258. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1259. reference manual~\citep{plt-tr}.}
  1260. %
  1261. \python{For example, the Python language is defined in the Python
  1262. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1263. %
  1264. In this book we use interpreters to specify each language that we
  1265. consider. An interpreter that is designated as the definition of a
  1266. language is called a \emph{definitional
  1267. interpreter}~\citep{reynolds72:_def_interp}.
  1268. \index{subject}{definitional interpreter} We warm up by creating a
  1269. definitional interpreter for the \LangInt{} language. This interpreter
  1270. serves as a second example of structural recursion. The definition of the
  1271. \code{interp\_Lint} function is shown in
  1272. figure~\ref{fig:interp_Lint}.
  1273. %
  1274. \racket{The body of the function is a match on the input program
  1275. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1276. which in turn has one match clause per grammar rule for \LangInt{}
  1277. expressions.}
  1278. %
  1279. \python{The body of the function matches on the \code{Module} AST node
  1280. and then invokes \code{interp\_stmt} on each statement in the
  1281. module. The \code{interp\_stmt} function includes a case for each
  1282. grammar rule of the \Stmt{} nonterminal, and it calls
  1283. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1284. function includes a case for each grammar rule of the \Exp{}
  1285. nonterminal. We use several auxiliary functions such as \code{add64}
  1286. and \code{input\_int} that are defined in the support code for this book.}
  1287. \begin{figure}[tp]
  1288. \begin{tcolorbox}[colback=white]
  1289. {\if\edition\racketEd
  1290. \begin{lstlisting}
  1291. (define (interp_exp e)
  1292. (match e
  1293. [(Int n) n]
  1294. [(Prim 'read '())
  1295. (define r (read))
  1296. (cond [(fixnum? r) r]
  1297. [else (error 'interp_exp "read expected an integer: ~v" r)])]
  1298. [(Prim '- (list e))
  1299. (define v (interp_exp e))
  1300. (fx- 0 v)]
  1301. [(Prim '+ (list e1 e2))
  1302. (define v1 (interp_exp e1))
  1303. (define v2 (interp_exp e2))
  1304. (fx+ v1 v2)]
  1305. [(Prim '- (list e1 e2))
  1306. (define v1 (interp_exp e1))
  1307. (define v2 (interp_exp e2))
  1308. (fx- v1 v2)]))
  1309. (define (interp_Lint p)
  1310. (match p
  1311. [(Program '() e) (interp_exp e)]))
  1312. \end{lstlisting}
  1313. \fi}
  1314. {\if\edition\pythonEd\pythonColor
  1315. \begin{lstlisting}
  1316. def interp_exp(e):
  1317. match e:
  1318. case BinOp(left, Add(), right):
  1319. l = interp_exp(left); r = interp_exp(right)
  1320. return add64(l, r)
  1321. case BinOp(left, Sub(), right):
  1322. l = interp_exp(left); r = interp_exp(right)
  1323. return sub64(l, r)
  1324. case UnaryOp(USub(), v):
  1325. return neg64(interp_exp(v))
  1326. case Constant(value):
  1327. return value
  1328. case Call(Name('input_int'), []):
  1329. return input_int()
  1330. def interp_stmt(s):
  1331. match s:
  1332. case Expr(Call(Name('print'), [arg])):
  1333. print(interp_exp(arg))
  1334. case Expr(value):
  1335. interp_exp(value)
  1336. def interp_Lint(p):
  1337. match p:
  1338. case Module(body):
  1339. for s in body:
  1340. interp_stmt(s)
  1341. \end{lstlisting}
  1342. \fi}
  1343. \end{tcolorbox}
  1344. \caption{Interpreter for the \LangInt{} language.}
  1345. \label{fig:interp_Lint}
  1346. \end{figure}
  1347. Let us consider the result of interpreting a few \LangInt{} programs. The
  1348. following program adds two integers:
  1349. {\if\edition\racketEd
  1350. \begin{lstlisting}
  1351. (+ 10 32)
  1352. \end{lstlisting}
  1353. \fi}
  1354. {\if\edition\pythonEd\pythonColor
  1355. \begin{lstlisting}
  1356. print(10 + 32)
  1357. \end{lstlisting}
  1358. \fi}
  1359. %
  1360. \noindent The result is \key{42}, the answer to life, the universe,
  1361. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1362. the Galaxy} by Douglas Adams.}
  1363. %
  1364. We wrote this program in concrete syntax, whereas the parsed
  1365. abstract syntax is
  1366. {\if\edition\racketEd
  1367. \begin{lstlisting}
  1368. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1369. \end{lstlisting}
  1370. \fi}
  1371. {\if\edition\pythonEd\pythonColor
  1372. \begin{lstlisting}
  1373. Module([Expr(Call(Name('print'),
  1374. [BinOp(Constant(10), Add(), Constant(32))]))])
  1375. \end{lstlisting}
  1376. \fi}
  1377. The following program demonstrates that expressions may be nested within
  1378. each other, in this case nesting several additions and negations.
  1379. {\if\edition\racketEd
  1380. \begin{lstlisting}
  1381. (+ 10 (- (+ 12 20)))
  1382. \end{lstlisting}
  1383. \fi}
  1384. {\if\edition\pythonEd\pythonColor
  1385. \begin{lstlisting}
  1386. print(10 + -(12 + 20))
  1387. \end{lstlisting}
  1388. \fi}
  1389. %
  1390. \noindent What is the result of this program?
  1391. {\if\edition\racketEd
  1392. As mentioned previously, the \LangInt{} language does not support
  1393. arbitrarily large integers but only $63$-bit integers, so we
  1394. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1395. in Racket.
  1396. Suppose that
  1397. \[
  1398. n = 999999999999999999
  1399. \]
  1400. which indeed fits in $63$ bits. What happens when we run the
  1401. following program in our interpreter?
  1402. \begin{lstlisting}
  1403. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1404. \end{lstlisting}
  1405. It produces the following error:
  1406. \begin{lstlisting}
  1407. fx+: result is not a fixnum
  1408. \end{lstlisting}
  1409. We establish the convention that if running the definitional
  1410. interpreter on a program produces an error, then the meaning of that
  1411. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1412. error is a \code{trapped-error}. A compiler for the language is under
  1413. no obligation regarding programs with unspecified behavior; it does
  1414. not have to produce an executable, and if it does, that executable can
  1415. do anything. On the other hand, if the error is a
  1416. \code{trapped-error}, then the compiler must produce an executable and
  1417. it is required to report that an error occurred. To signal an error,
  1418. exit with a return code of \code{255}. The interpreters in chapters
  1419. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1420. \code{trapped-error}.
  1421. \fi}
  1422. % TODO: how to deal with too-large integers in the Python interpreter?
  1423. %% This convention applies to the languages defined in this
  1424. %% book, as a way to simplify the student's task of implementing them,
  1425. %% but this convention is not applicable to all programming languages.
  1426. %%
  1427. The last feature of the \LangInt{} language, the \READOP{} operation,
  1428. prompts the user of the program for an integer. Recall that program
  1429. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1430. \code{8}. So, if we run {\if\edition\racketEd
  1431. \begin{lstlisting}
  1432. (interp_Lint (Program '() ast1_1))
  1433. \end{lstlisting}
  1434. \fi}
  1435. {\if\edition\pythonEd\pythonColor
  1436. \begin{lstlisting}
  1437. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1438. \end{lstlisting}
  1439. \fi}
  1440. \noindent and if the input is \code{50}, the result is \code{42}.
  1441. We include the \READOP{} operation in \LangInt{} so that a clever
  1442. student cannot implement a compiler for \LangInt{} that simply runs
  1443. the interpreter during compilation to obtain the output and then
  1444. generates the trivial code to produce the output.\footnote{Yes, a
  1445. clever student did this in the first instance of this course!}
  1446. The job of a compiler is to translate a program in one language into a
  1447. program in another language so that the output program behaves the
  1448. same way as the input program. This idea is depicted in the
  1449. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1450. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1451. Given a compiler that translates from language $\mathcal{L}_1$ to
  1452. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1453. compiler must translate it into some program $P_2$ such that
  1454. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1455. same input $i$ yields the same output $o$.
  1456. \begin{equation} \label{eq:compile-correct}
  1457. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1458. \node (p1) at (0, 0) {$P_1$};
  1459. \node (p2) at (3, 0) {$P_2$};
  1460. \node (o) at (3, -2.5) {$o$};
  1461. \path[->] (p1) edge [above] node {compile} (p2);
  1462. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1463. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1464. \end{tikzpicture}
  1465. \end{equation}
  1466. \python{We establish the convention that if running the definitional
  1467. interpreter on a program produces an error, then the meaning of that
  1468. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1469. unless the exception raised is a \code{TrappedError}. A compiler for
  1470. the language is under no obligation regarding programs with
  1471. unspecified behavior; it does not have to produce an executable, and
  1472. if it does, that executable can do anything. On the other hand, if
  1473. the error is a \code{TrappedError}, then the compiler must produce
  1474. an executable and it is required to report that an error
  1475. occurred. To signal an error, exit with a return code of \code{255}.
  1476. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1477. section \ref{sec:arrays} use \code{TrappedError}.}
  1478. In the next section we see our first example of a compiler.
  1479. \section{Example Compiler: A Partial Evaluator}
  1480. \label{sec:partial-evaluation}
  1481. In this section we consider a compiler that translates \LangInt{}
  1482. programs into \LangInt{} programs that may be more efficient. The
  1483. compiler eagerly computes the parts of the program that do not depend
  1484. on any inputs, a process known as \emph{partial
  1485. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1486. For example, given the following program
  1487. {\if\edition\racketEd
  1488. \begin{lstlisting}
  1489. (+ (read) (- (+ 5 3)))
  1490. \end{lstlisting}
  1491. \fi}
  1492. {\if\edition\pythonEd\pythonColor
  1493. \begin{lstlisting}
  1494. print(input_int() + -(5 + 3) )
  1495. \end{lstlisting}
  1496. \fi}
  1497. \noindent our compiler translates it into the program
  1498. {\if\edition\racketEd
  1499. \begin{lstlisting}
  1500. (+ (read) -8)
  1501. \end{lstlisting}
  1502. \fi}
  1503. {\if\edition\pythonEd\pythonColor
  1504. \begin{lstlisting}
  1505. print(input_int() + -8)
  1506. \end{lstlisting}
  1507. \fi}
  1508. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1509. evaluator for the \LangInt{} language. The output of the partial evaluator
  1510. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1511. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1512. whereas the code for partially evaluating the negation and addition
  1513. operations is factored into three auxiliary functions:
  1514. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1515. functions is the output of partially evaluating the children.
  1516. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1517. arguments are integers and if they are, perform the appropriate
  1518. arithmetic. Otherwise, they create an AST node for the arithmetic
  1519. operation.
  1520. \begin{figure}[tp]
  1521. \begin{tcolorbox}[colback=white]
  1522. {\if\edition\racketEd
  1523. \begin{lstlisting}
  1524. (define (pe_neg r)
  1525. (match r
  1526. [(Int n) (Int (fx- 0 n))]
  1527. [else (Prim '- (list r))]))
  1528. (define (pe_add r1 r2)
  1529. (match* (r1 r2)
  1530. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1531. [(_ _) (Prim '+ (list r1 r2))]))
  1532. (define (pe_sub r1 r2)
  1533. (match* (r1 r2)
  1534. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1535. [(_ _) (Prim '- (list r1 r2))]))
  1536. (define (pe_exp e)
  1537. (match e
  1538. [(Int n) (Int n)]
  1539. [(Prim 'read '()) (Prim 'read '())]
  1540. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1541. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1542. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1543. (define (pe_Lint p)
  1544. (match p
  1545. [(Program '() e) (Program '() (pe_exp e))]))
  1546. \end{lstlisting}
  1547. \fi}
  1548. {\if\edition\pythonEd\pythonColor
  1549. \begin{lstlisting}
  1550. def pe_neg(r):
  1551. match r:
  1552. case Constant(n):
  1553. return Constant(neg64(n))
  1554. case _:
  1555. return UnaryOp(USub(), r)
  1556. def pe_add(r1, r2):
  1557. match (r1, r2):
  1558. case (Constant(n1), Constant(n2)):
  1559. return Constant(add64(n1, n2))
  1560. case _:
  1561. return BinOp(r1, Add(), r2)
  1562. def pe_sub(r1, r2):
  1563. match (r1, r2):
  1564. case (Constant(n1), Constant(n2)):
  1565. return Constant(sub64(n1, n2))
  1566. case _:
  1567. return BinOp(r1, Sub(), r2)
  1568. def pe_exp(e):
  1569. match e:
  1570. case BinOp(left, Add(), right):
  1571. return pe_add(pe_exp(left), pe_exp(right))
  1572. case BinOp(left, Sub(), right):
  1573. return pe_sub(pe_exp(left), pe_exp(right))
  1574. case UnaryOp(USub(), v):
  1575. return pe_neg(pe_exp(v))
  1576. case Constant(value):
  1577. return e
  1578. case Call(Name('input_int'), []):
  1579. return e
  1580. def pe_stmt(s):
  1581. match s:
  1582. case Expr(Call(Name('print'), [arg])):
  1583. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1584. case Expr(value):
  1585. return Expr(pe_exp(value))
  1586. def pe_P_int(p):
  1587. match p:
  1588. case Module(body):
  1589. new_body = [pe_stmt(s) for s in body]
  1590. return Module(new_body)
  1591. \end{lstlisting}
  1592. \fi}
  1593. \end{tcolorbox}
  1594. \caption{A partial evaluator for \LangInt{}.}
  1595. \label{fig:pe-arith}
  1596. \end{figure}
  1597. To gain some confidence that the partial evaluator is correct, we can
  1598. test whether it produces programs that produce the same result as the
  1599. input programs. That is, we can test whether it satisfies the diagram
  1600. of \eqref{eq:compile-correct}.
  1601. %
  1602. {\if\edition\racketEd
  1603. The following code runs the partial evaluator on several examples and
  1604. tests the output program. The \texttt{parse-program} and
  1605. \texttt{assert} functions are defined in
  1606. appendix~\ref{appendix:utilities}.\\
  1607. \begin{minipage}{1.0\textwidth}
  1608. \begin{lstlisting}
  1609. (define (test_pe p)
  1610. (assert "testing pe_Lint"
  1611. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1612. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1613. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1614. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1615. \end{lstlisting}
  1616. \end{minipage}
  1617. \fi}
  1618. % TODO: python version of testing the PE
  1619. \begin{exercise}\normalfont\normalsize
  1620. Create three programs in the \LangInt{} language and test whether
  1621. partially evaluating them with \code{pe\_Lint} and then
  1622. interpreting them with \code{interp\_Lint} gives the same result
  1623. as directly interpreting them with \code{interp\_Lint}.
  1624. \end{exercise}
  1625. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1626. \chapter{Integers and Variables}
  1627. \label{ch:Lvar}
  1628. \setcounter{footnote}{0}
  1629. This chapter covers compiling a subset of
  1630. \racket{Racket}\python{Python} to x86-64 assembly
  1631. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1632. integer arithmetic and local variables. We often refer to x86-64
  1633. simply as x86. The chapter first describes the \LangVar{} language
  1634. (section~\ref{sec:s0}) and then introduces x86 assembly
  1635. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1636. discuss only the instructions needed for compiling \LangVar{}. We
  1637. introduce more x86 instructions in subsequent chapters. After
  1638. introducing \LangVar{} and x86, we reflect on their differences and
  1639. create a plan to break down the translation from \LangVar{} to x86
  1640. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1641. the chapter gives detailed hints regarding each step. We aim to give
  1642. enough hints that the well-prepared reader, together with a few
  1643. friends, can implement a compiler from \LangVar{} to x86 in a short
  1644. time. To suggest the scale of this first compiler, we note that the
  1645. instructor solution for the \LangVar{} compiler is approximately
  1646. \racket{500}\python{300} lines of code.
  1647. \section{The \LangVar{} Language}
  1648. \label{sec:s0}
  1649. \index{subject}{variable}
  1650. The \LangVar{} language extends the \LangInt{} language with
  1651. variables. The concrete syntax of the \LangVar{} language is defined
  1652. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1653. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1654. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1655. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1656. \key{-} is a unary operator, and \key{+} is a binary operator.
  1657. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1658. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1659. the top of the program.
  1660. %% The $\itm{info}$
  1661. %% field of the \key{Program} structure contains an \emph{association
  1662. %% list} (a list of key-value pairs) that is used to communicate
  1663. %% auxiliary data from one compiler pass the next.
  1664. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1665. exhibit several compilation techniques.
  1666. \newcommand{\LvarGrammarRacket}{
  1667. \begin{array}{rcl}
  1668. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1669. \end{array}
  1670. }
  1671. \newcommand{\LvarASTRacket}{
  1672. \begin{array}{rcl}
  1673. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1674. \end{array}
  1675. }
  1676. \newcommand{\LvarGrammarPython}{
  1677. \begin{array}{rcl}
  1678. \Exp &::=& \Var{} \\
  1679. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1680. \end{array}
  1681. }
  1682. \newcommand{\LvarASTPython}{
  1683. \begin{array}{rcl}
  1684. \Exp{} &::=& \VAR{\Var{}} \\
  1685. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1686. \end{array}
  1687. }
  1688. \begin{figure}[tp]
  1689. \centering
  1690. \begin{tcolorbox}[colback=white]
  1691. {\if\edition\racketEd
  1692. \[
  1693. \begin{array}{l}
  1694. \gray{\LintGrammarRacket{}} \\ \hline
  1695. \LvarGrammarRacket{} \\
  1696. \begin{array}{rcl}
  1697. \LangVarM{} &::=& \Exp
  1698. \end{array}
  1699. \end{array}
  1700. \]
  1701. \fi}
  1702. {\if\edition\pythonEd\pythonColor
  1703. \[
  1704. \begin{array}{l}
  1705. \gray{\LintGrammarPython} \\ \hline
  1706. \LvarGrammarPython \\
  1707. \begin{array}{rcl}
  1708. \LangVarM{} &::=& \Stmt^{*}
  1709. \end{array}
  1710. \end{array}
  1711. \]
  1712. \fi}
  1713. \end{tcolorbox}
  1714. \caption{The concrete syntax of \LangVar{}.}
  1715. \label{fig:Lvar-concrete-syntax}
  1716. \index{subject}{Lvar@\LangVar{} concrete syntax}
  1717. \end{figure}
  1718. \begin{figure}[tp]
  1719. \centering
  1720. \begin{tcolorbox}[colback=white]
  1721. {\if\edition\racketEd
  1722. \[
  1723. \begin{array}{l}
  1724. \gray{\LintASTRacket{}} \\ \hline
  1725. \LvarASTRacket \\
  1726. \begin{array}{rcl}
  1727. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1728. \end{array}
  1729. \end{array}
  1730. \]
  1731. \fi}
  1732. {\if\edition\pythonEd\pythonColor
  1733. \[
  1734. \begin{array}{l}
  1735. \gray{\LintASTPython}\\ \hline
  1736. \LvarASTPython \\
  1737. \begin{array}{rcl}
  1738. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1739. \end{array}
  1740. \end{array}
  1741. \]
  1742. \fi}
  1743. \end{tcolorbox}
  1744. \caption{The abstract syntax of \LangVar{}.}
  1745. \label{fig:Lvar-syntax}
  1746. \index{subject}{Lvar@\LangVar{} abstract syntax}
  1747. \end{figure}
  1748. {\if\edition\racketEd
  1749. Let us dive further into the syntax and semantics of the \LangVar{}
  1750. language. The \key{let} feature defines a variable for use within its
  1751. body and initializes the variable with the value of an expression.
  1752. The abstract syntax for \key{let} is shown in
  1753. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1754. \begin{lstlisting}
  1755. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1756. \end{lstlisting}
  1757. For example, the following program initializes \code{x} to $32$ and then
  1758. evaluates the body \code{(+ 10 x)}, producing $42$.
  1759. \begin{lstlisting}
  1760. (let ([x (+ 12 20)]) (+ 10 x))
  1761. \end{lstlisting}
  1762. \fi}
  1763. %
  1764. {\if\edition\pythonEd\pythonColor
  1765. %
  1766. The \LangVar{} language includes an assignment statement, which defines a
  1767. variable for use in later statements and initializes the variable with
  1768. the value of an expression. The abstract syntax for assignment is
  1769. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1770. assignment is \index{subject}{Assign@\texttt{Assign}}
  1771. \begin{lstlisting}
  1772. |$\itm{var}$| = |$\itm{exp}$|
  1773. \end{lstlisting}
  1774. For example, the following program initializes the variable \code{x}
  1775. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1776. \begin{lstlisting}
  1777. x = 12 + 20
  1778. print(10 + x)
  1779. \end{lstlisting}
  1780. \fi}
  1781. {\if\edition\racketEd
  1782. %
  1783. When there are multiple \key{let}s for the same variable, the closest
  1784. enclosing \key{let} is used. That is, variable definitions overshadow
  1785. prior definitions. Consider the following program with two \key{let}s
  1786. that define two variables named \code{x}. Can you figure out the
  1787. result?
  1788. \begin{lstlisting}
  1789. (let ([x 32]) (+ (let ([x 10]) x) x))
  1790. \end{lstlisting}
  1791. For the purposes of depicting which variable occurrences correspond to
  1792. which definitions, the following shows the \code{x}'s annotated with
  1793. subscripts to distinguish them. Double-check that your answer for the
  1794. previous program is the same as your answer for this annotated version
  1795. of the program.
  1796. \begin{lstlisting}
  1797. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1798. \end{lstlisting}
  1799. The initializing expression is always evaluated before the body of the
  1800. \key{let}, so in the following, the \key{read} for \code{x} is
  1801. performed before the \key{read} for \code{y}. Given the input
  1802. $52$ then $10$, the following produces $42$ (not $-42$).
  1803. \begin{lstlisting}
  1804. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1805. \end{lstlisting}
  1806. \fi}
  1807. \subsection{Extensible Interpreters via Method Overriding}
  1808. \label{sec:extensible-interp}
  1809. \index{subject}{method overriding}
  1810. To prepare for discussing the interpreter of \LangVar{}, we explain
  1811. why we implement it in an object-oriented style. Throughout this book
  1812. we define many interpreters, one for each language that we
  1813. study. Because each language builds on the prior one, there is a lot
  1814. of commonality between these interpreters. We want to write down the
  1815. common parts just once instead of many times. A naive interpreter for
  1816. \LangVar{} would handle the \racket{cases for variables and
  1817. \code{let}} \python{case for variables} but dispatch to an
  1818. interpreter for \LangInt{} in the rest of the cases. The following
  1819. code sketches this idea. (We explain the \code{env} parameter in
  1820. section~\ref{sec:interp-Lvar}.)
  1821. \begin{center}
  1822. {\if\edition\racketEd
  1823. \begin{minipage}{0.45\textwidth}
  1824. \begin{lstlisting}
  1825. (define ((interp_Lint env) e)
  1826. (match e
  1827. [(Prim '- (list e1))
  1828. (fx- 0 ((interp_Lint env) e1))]
  1829. ...))
  1830. \end{lstlisting}
  1831. \end{minipage}
  1832. \begin{minipage}{0.45\textwidth}
  1833. \begin{lstlisting}
  1834. (define ((interp_Lvar env) e)
  1835. (match e
  1836. [(Var x)
  1837. (dict-ref env x)]
  1838. [(Let x e body)
  1839. (define v ((interp_Lvar env) e))
  1840. (define env^ (dict-set env x v))
  1841. ((interp_Lvar env^) body)]
  1842. [else ((interp_Lint env) e)]))
  1843. \end{lstlisting}
  1844. \end{minipage}
  1845. \fi}
  1846. {\if\edition\pythonEd\pythonColor
  1847. \begin{minipage}{0.45\textwidth}
  1848. \begin{lstlisting}
  1849. def interp_Lint(e, env):
  1850. match e:
  1851. case UnaryOp(USub(), e1):
  1852. return - interp_Lint(e1, env)
  1853. ...
  1854. \end{lstlisting}
  1855. \end{minipage}
  1856. \begin{minipage}{0.45\textwidth}
  1857. \begin{lstlisting}
  1858. def interp_Lvar(e, env):
  1859. match e:
  1860. case Name(id):
  1861. return env[id]
  1862. case _:
  1863. return interp_Lint(e, env)
  1864. \end{lstlisting}
  1865. \end{minipage}
  1866. \fi}
  1867. \end{center}
  1868. The problem with this naive approach is that it does not handle
  1869. situations in which an \LangVar{} feature, such as a variable, is
  1870. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1871. in the following program.
  1872. {\if\edition\racketEd
  1873. \begin{lstlisting}
  1874. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1875. \end{lstlisting}
  1876. \fi}
  1877. {\if\edition\pythonEd\pythonColor
  1878. \begin{minipage}{1.0\textwidth}
  1879. \begin{lstlisting}
  1880. y = 10
  1881. print(-y)
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \fi}
  1885. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1886. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1887. then it recursively calls \code{interp\_Lint} again on its argument.
  1888. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1889. \code{interp\_Lint}, we get an error!
  1890. To make our interpreters extensible we need something called
  1891. \emph{open recursion}\index{subject}{open recursion}, in which the
  1892. tying of the recursive knot is delayed until the functions are
  1893. composed. Object-oriented languages provide open recursion via method
  1894. overriding. The following code uses
  1895. method overriding to interpret \LangInt{} and \LangVar{} using
  1896. %
  1897. \racket{the
  1898. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1899. \index{subject}{class} feature of Racket.}%
  1900. %
  1901. \python{Python \code{class} definitions.}
  1902. %
  1903. We define one class for each language and define a method for
  1904. interpreting expressions inside each class. The class for \LangVar{}
  1905. inherits from the class for \LangInt{}, and the method
  1906. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1907. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1908. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1909. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1910. \code{interp\_exp} in \LangInt{}.
  1911. \begin{center}
  1912. \hspace{-20pt}
  1913. {\if\edition\racketEd
  1914. \begin{minipage}{0.45\textwidth}
  1915. \begin{lstlisting}
  1916. (define interp-Lint-class
  1917. (class object%
  1918. (define/public ((interp_exp env) e)
  1919. (match e
  1920. [(Prim '- (list e))
  1921. (fx- 0 ((interp_exp env) e))]
  1922. ...))
  1923. ...))
  1924. \end{lstlisting}
  1925. \end{minipage}
  1926. \begin{minipage}{0.45\textwidth}
  1927. \begin{lstlisting}
  1928. (define interp-Lvar-class
  1929. (class interp-Lint-class
  1930. (define/override ((interp_exp env) e)
  1931. (match e
  1932. [(Var x)
  1933. (dict-ref env x)]
  1934. [(Let x e body)
  1935. (define v ((interp_exp env) e))
  1936. (define env^ (dict-set env x v))
  1937. ((interp_exp env^) body)]
  1938. [else
  1939. ((super interp_exp env) e)]))
  1940. ...
  1941. ))
  1942. \end{lstlisting}
  1943. \end{minipage}
  1944. \fi}
  1945. {\if\edition\pythonEd\pythonColor
  1946. \begin{minipage}{0.45\textwidth}
  1947. \begin{lstlisting}
  1948. class InterpLint:
  1949. def interp_exp(e):
  1950. match e:
  1951. case UnaryOp(USub(), e1):
  1952. return neg64(self.interp_exp(e1))
  1953. ...
  1954. ...
  1955. \end{lstlisting}
  1956. \end{minipage}
  1957. \begin{minipage}{0.45\textwidth}
  1958. \begin{lstlisting}
  1959. def InterpLvar(InterpLint):
  1960. def interp_exp(e):
  1961. match e:
  1962. case Name(id):
  1963. return env[id]
  1964. case _:
  1965. return super().interp_exp(e)
  1966. ...
  1967. \end{lstlisting}
  1968. \end{minipage}
  1969. \fi}
  1970. \end{center}
  1971. We return to the troublesome example, repeated here:
  1972. {\if\edition\racketEd
  1973. \begin{lstlisting}
  1974. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1975. \end{lstlisting}
  1976. \fi}
  1977. {\if\edition\pythonEd\pythonColor
  1978. \begin{lstlisting}
  1979. y = 10
  1980. print(-y)
  1981. \end{lstlisting}
  1982. \fi}
  1983. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1984. \racket{on this expression,}%
  1985. \python{on the \code{-y} expression,}
  1986. %
  1987. which we call \code{e0}, by creating an object of the \LangVar{} class
  1988. and calling the \code{interp\_exp} method
  1989. {\if\edition\racketEd
  1990. \begin{lstlisting}
  1991. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1992. \end{lstlisting}
  1993. \fi}
  1994. {\if\edition\pythonEd\pythonColor
  1995. \begin{lstlisting}
  1996. InterpLvar().interp_exp(e0)
  1997. \end{lstlisting}
  1998. \fi}
  1999. \noindent To process the \code{-} operator, the default case of
  2000. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  2001. method in \LangInt{}. But then for the recursive method call, it
  2002. dispatches to \code{interp\_exp} in \LangVar{}, where the
  2003. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  2004. Thus, method overriding gives us the open recursion that we need to
  2005. implement our interpreters in an extensible way.
  2006. \subsection{Definitional Interpreter for \LangVar{}}
  2007. \label{sec:interp-Lvar}
  2008. Having justified the use of classes and methods to implement
  2009. interpreters, we revisit the definitional interpreter for \LangInt{}
  2010. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  2011. create an interpreter for \LangVar{}, shown in
  2012. figure~\ref{fig:interp-Lvar}.
  2013. %
  2014. \python{We change the \code{interp\_stmt} method in the interpreter
  2015. for \LangInt{} to take two extra parameters named \code{env}, which
  2016. we discuss in the next paragraph, and \code{cont} for
  2017. \emph{continuation}, which is the technical name for what comes
  2018. after a particular point in a program. The \code{cont} parameter is
  2019. the list of statements that follow the current statement. Note
  2020. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2021. statement and passes the rest of the statements as the argument for
  2022. \code{cont}. This organization enables each statement to decide what
  2023. if anything should be evaluated after it, for example, allowing a
  2024. \code{return} statement to exit early from a function (see
  2025. Chapter~\ref{ch:Lfun}).}
  2026. The interpreter for \LangVar{} adds two new cases for
  2027. variables and \racket{\key{let}}\python{assignment}. For
  2028. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2029. value bound to a variable to all the uses of the variable. To
  2030. accomplish this, we maintain a mapping from variables to values called
  2031. an \emph{environment}\index{subject}{environment}.
  2032. %
  2033. We use
  2034. %
  2035. \racket{an association list (alist) }%
  2036. %
  2037. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2038. %
  2039. to represent the environment.
  2040. %
  2041. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2042. and the \code{racket/dict} package.}
  2043. %
  2044. The \code{interp\_exp} function takes the current environment,
  2045. \code{env}, as an extra parameter. When the interpreter encounters a
  2046. variable, it looks up the corresponding value in the environment. If
  2047. the variable is not in the environment (because the variable was not
  2048. defined) then the lookup will fail and the interpreter will
  2049. halt with an error. Recall that the compiler is not obligated to
  2050. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2051. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2052. prohibit access to undefined variables.}
  2053. %
  2054. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2055. initializing expression, extends the environment with the result
  2056. value bound to the variable, using \code{dict-set}, then evaluates
  2057. the body of the \key{Let}.}
  2058. %
  2059. \python{When the interpreter encounters an assignment, it evaluates
  2060. the initializing expression and then associates the resulting value
  2061. with the variable in the environment.}
  2062. \begin{figure}[tp]
  2063. \begin{tcolorbox}[colback=white]
  2064. {\if\edition\racketEd
  2065. \begin{lstlisting}
  2066. (define interp-Lint-class
  2067. (class object%
  2068. (super-new)
  2069. (define/public ((interp_exp env) e)
  2070. (match e
  2071. [(Int n) n]
  2072. [(Prim 'read '())
  2073. (define r (read))
  2074. (cond [(fixnum? r) r]
  2075. [else (error 'interp_exp "expected an integer" r)])]
  2076. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2077. [(Prim '+ (list e1 e2))
  2078. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2079. [(Prim '- (list e1 e2))
  2080. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2081. (define/public (interp_program p)
  2082. (match p
  2083. [(Program '() e) ((interp_exp '()) e)]))
  2084. ))
  2085. \end{lstlisting}
  2086. \fi}
  2087. {\if\edition\pythonEd\pythonColor
  2088. \begin{lstlisting}
  2089. class InterpLint:
  2090. def interp_exp(self, e, env):
  2091. match e:
  2092. case BinOp(left, Add(), right):
  2093. l = self.interp_exp(left, env)
  2094. r = self.interp_exp(right, env)
  2095. return add64(l, r)
  2096. case BinOp(left, Sub(), right):
  2097. l = self.interp_exp(left, env)
  2098. r = self.interp_exp(right, env)
  2099. return sub64(l, r)
  2100. case UnaryOp(USub(), v):
  2101. return neg64(self.interp_exp(v, env))
  2102. case Constant(value):
  2103. return value
  2104. case Call(Name('input_int'), []):
  2105. return int(input())
  2106. def interp_stmt(self, s, env, cont):
  2107. match s:
  2108. case Expr(Call(Name('print'), [arg])):
  2109. val = self.interp_exp(arg, env)
  2110. print(val, end='')
  2111. return self.interp_stmts(cont, env)
  2112. case Expr(value):
  2113. self.interp_exp(value, env)
  2114. return self.interp_stmts(cont, env)
  2115. case _:
  2116. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2117. def interp_stmts(self, ss, env):
  2118. match ss:
  2119. case []:
  2120. return 0
  2121. case [s, *ss]:
  2122. return self.interp_stmt(s, env, ss)
  2123. def interp(self, p):
  2124. match p:
  2125. case Module(body):
  2126. self.interp_stmts(body, {})
  2127. def interp_Lint(p):
  2128. return InterpLint().interp(p)
  2129. \end{lstlisting}
  2130. \fi}
  2131. \end{tcolorbox}
  2132. \caption{Interpreter for \LangInt{} as a class.}
  2133. \label{fig:interp-Lint-class}
  2134. \end{figure}
  2135. \begin{figure}[tp]
  2136. \begin{tcolorbox}[colback=white]
  2137. {\if\edition\racketEd
  2138. \begin{lstlisting}
  2139. (define interp-Lvar-class
  2140. (class interp-Lint-class
  2141. (super-new)
  2142. (define/override ((interp_exp env) e)
  2143. (match e
  2144. [(Var x) (dict-ref env x)]
  2145. [(Let x e body)
  2146. (define new-env (dict-set env x ((interp_exp env) e)))
  2147. ((interp_exp new-env) body)]
  2148. [else ((super interp_exp env) e)]))
  2149. ))
  2150. (define (interp_Lvar p)
  2151. (send (new interp-Lvar-class) interp_program p))
  2152. \end{lstlisting}
  2153. \fi}
  2154. {\if\edition\pythonEd\pythonColor
  2155. \begin{lstlisting}
  2156. class InterpLvar(InterpLint):
  2157. def interp_exp(self, e, env):
  2158. match e:
  2159. case Name(id):
  2160. return env[id]
  2161. case _:
  2162. return super().interp_exp(e, env)
  2163. def interp_stmt(self, s, env, cont):
  2164. match s:
  2165. case Assign([Name(id)], value):
  2166. env[id] = self.interp_exp(value, env)
  2167. return self.interp_stmts(cont, env)
  2168. case _:
  2169. return super().interp_stmt(s, env, cont)
  2170. def interp_Lvar(p):
  2171. return InterpLvar().interp(p)
  2172. \end{lstlisting}
  2173. \fi}
  2174. \end{tcolorbox}
  2175. \caption{Interpreter for the \LangVar{} language.}
  2176. \label{fig:interp-Lvar}
  2177. \end{figure}
  2178. {\if\edition\racketEd
  2179. \begin{figure}[tp]
  2180. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2181. \small
  2182. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2183. An \emph{association list} (called an alist) is a list of key-value pairs.
  2184. For example, we can map people to their ages with an alist
  2185. \index{subject}{alist}\index{subject}{association list}
  2186. \begin{lstlisting}[basicstyle=\ttfamily]
  2187. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2188. \end{lstlisting}
  2189. The \emph{dictionary} interface is for mapping keys to values.
  2190. Every alist implements this interface. \index{subject}{dictionary}
  2191. The package
  2192. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2193. provides many functions for working with dictionaries, such as
  2194. \begin{description}
  2195. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2196. returns the value associated with the given $\itm{key}$.
  2197. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2198. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2199. and otherwise is the same as $\itm{dict}$.
  2200. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2201. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2202. of keys and values in $\itm{dict}$. For example, the following
  2203. creates a new alist in which the ages are incremented:
  2204. \end{description}
  2205. \vspace{-10pt}
  2206. \begin{lstlisting}[basicstyle=\ttfamily]
  2207. (for/list ([(k v) (in-dict ages)])
  2208. (cons k (add1 v)))
  2209. \end{lstlisting}
  2210. \end{tcolorbox}
  2211. %\end{wrapfigure}
  2212. \caption{Association lists implement the dictionary interface.}
  2213. \label{fig:alist}
  2214. \end{figure}
  2215. \fi}
  2216. The goal for this chapter is to implement a compiler that translates
  2217. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2218. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2219. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2220. That is, they output the same integer $n$. We depict this correctness
  2221. criteria in the following diagram:
  2222. \[
  2223. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2224. \node (p1) at (0, 0) {$P_1$};
  2225. \node (p2) at (4, 0) {$P_2$};
  2226. \node (o) at (4, -2) {$n$};
  2227. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2228. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2229. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2230. \end{tikzpicture}
  2231. \]
  2232. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2233. compiling \LangVar{}.
  2234. \section{The \LangXInt{} Assembly Language}
  2235. \label{sec:x86}
  2236. \index{subject}{x86}
  2237. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2238. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2239. assembler.
  2240. %
  2241. A program begins with a \code{main} label followed by a sequence of
  2242. instructions. The \key{globl} directive makes the \key{main} procedure
  2243. externally visible so that the operating system can call it.
  2244. %
  2245. An x86 program is stored in the computer's memory. For our purposes,
  2246. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2247. values. The computer has a \emph{program counter}
  2248. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2249. \code{rip} register that points to the address of the next instruction
  2250. to be executed. For most instructions, the program counter is
  2251. incremented after the instruction is executed so that it points to the
  2252. next instruction in memory. Most x86 instructions take two operands,
  2253. each of which is an integer constant (called an \emph{immediate
  2254. value}\index{subject}{immediate value}), a
  2255. \emph{register}\index{subject}{register}, or a memory location.
  2256. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2257. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2258. && \key{r8} \MID \key{r9} \MID \key{r10}
  2259. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2260. \MID \key{r14} \MID \key{r15}}
  2261. \newcommand{\GrammarXIntRacket}{
  2262. \begin{array}{rcl}
  2263. \Reg &::=& \allregisters{} \\
  2264. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2265. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2266. \key{subq} \; \Arg\key{,} \Arg \MID
  2267. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2268. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2269. \key{callq} \; \mathit{label} \MID
  2270. \key{retq} \MID
  2271. \key{jmp}\,\itm{label} \MID \\
  2272. && \itm{label}\key{:}\; \Instr
  2273. \end{array}
  2274. }
  2275. \newcommand{\GrammarXIntPython}{
  2276. % no jmp and label in the python version
  2277. \begin{array}{rcl}
  2278. \Reg &::=& \allregisters{} \\
  2279. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2280. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2281. \key{subq} \; \Arg\key{,} \Arg \MID
  2282. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2283. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2284. \key{callq} \; \mathit{label} \MID \key{retq}
  2285. \end{array}
  2286. }
  2287. \begin{figure}[tp]
  2288. \begin{tcolorbox}[colback=white]
  2289. {\if\edition\racketEd
  2290. \[
  2291. \begin{array}{l}
  2292. \GrammarXIntRacket \\
  2293. \begin{array}{lcl}
  2294. \LangXIntM{} &::= & \key{.globl main}\\
  2295. & & \key{main:} \; \Instr\ldots
  2296. \end{array}
  2297. \end{array}
  2298. \]
  2299. \fi}
  2300. {\if\edition\pythonEd\pythonColor
  2301. \[
  2302. \begin{array}{lcl}
  2303. \Reg &::=& \allregisters{} \\
  2304. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2305. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2306. \key{subq} \; \Arg\key{,} \Arg \MID
  2307. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2308. && \key{callq} \; \mathit{label} \MID
  2309. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2310. \LangXIntM{} &::= & \key{.globl main}\\
  2311. & & \key{main:} \; \Instr^{*}
  2312. \end{array}
  2313. \]
  2314. \fi}
  2315. \end{tcolorbox}
  2316. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2317. \label{fig:x86-int-concrete}
  2318. \index{subject}{x86int@\LangXInt{} concrete syntax}
  2319. \end{figure}
  2320. A register is a special kind of variable that holds a 64-bit
  2321. value. There are 16 general-purpose registers in the computer; their
  2322. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2323. written with a percent sign, \key{\%}, followed by its name,
  2324. for example, \key{\%rax}.
  2325. An immediate value is written using the notation \key{\$}$n$ where $n$
  2326. is an integer.
  2327. %
  2328. %
  2329. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2330. which obtains the address stored in register $r$ and then adds $n$
  2331. bytes to the address. The resulting address is used to load or to store
  2332. to memory depending on whether it occurs as a source or destination
  2333. argument of an instruction.
  2334. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2335. the source $s$ and destination $d$, applies the arithmetic operation,
  2336. and then writes the result to the destination $d$. \index{subject}{instruction}
  2337. %
  2338. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2339. stores the result in $d$.
  2340. %
  2341. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2342. specified by the label, and $\key{retq}$ returns from a procedure to
  2343. its caller.
  2344. %
  2345. We discuss procedure calls in more detail further in this chapter and
  2346. in chapter~\ref{ch:Lfun}.
  2347. %
  2348. The last letter \key{q} indicates that these instructions operate on
  2349. quadwords, which are 64-bit values.
  2350. %
  2351. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2352. counter to the address of the instruction immediately after the
  2353. specified label.}
  2354. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2355. all the x86 instructions used in this book.
  2356. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2357. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2358. \lstinline{movq $10, %rax}
  2359. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2360. adds $32$ to the $10$ in \key{rax} and
  2361. puts the result, $42$, into \key{rax}.
  2362. %
  2363. The last instruction \key{retq} finishes the \key{main} function by
  2364. returning the integer in \key{rax} to the operating system. The
  2365. operating system interprets this integer as the program's exit
  2366. code. By convention, an exit code of 0 indicates that a program has
  2367. completed successfully, and all other exit codes indicate various
  2368. errors.
  2369. %
  2370. \racket{However, in this book we return the result of the program
  2371. as the exit code.}
  2372. \begin{figure}[tbp]
  2373. \begin{minipage}{0.45\textwidth}
  2374. \begin{tcolorbox}[colback=white]
  2375. \begin{lstlisting}
  2376. .globl main
  2377. main:
  2378. movq $10, %rax
  2379. addq $32, %rax
  2380. retq
  2381. \end{lstlisting}
  2382. \end{tcolorbox}
  2383. \end{minipage}
  2384. \caption{An x86 program that computes
  2385. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2386. \label{fig:p0-x86}
  2387. \end{figure}
  2388. We exhibit the use of memory for storing intermediate results in the
  2389. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2390. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2391. uses a region of memory called the \emph{procedure call stack}
  2392. (\emph{stack} for
  2393. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2394. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2395. for each procedure call. The memory layout for an individual frame is
  2396. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2397. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2398. address of the item at the top of the stack. In general, we use the
  2399. term \emph{pointer}\index{subject}{pointer} for something that
  2400. contains an address. The stack grows downward in memory, so we
  2401. increase the size of the stack by subtracting from the stack pointer.
  2402. In the context of a procedure call, the \emph{return
  2403. address}\index{subject}{return address} is the location of the
  2404. instruction that immediately follows the call instruction on the
  2405. caller side. The function call instruction, \code{callq}, pushes the
  2406. return address onto the stack prior to jumping to the procedure. The
  2407. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2408. pointer} and is used to access variables that are stored in the
  2409. frame of the current procedure call. The base pointer of the caller
  2410. is stored immediately after the return address.
  2411. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2412. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2413. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2414. $-16\key{(\%rbp)}$, and so on.
  2415. \begin{figure}[tbp]
  2416. \begin{minipage}{0.66\textwidth}
  2417. \begin{tcolorbox}[colback=white]
  2418. {\if\edition\racketEd
  2419. \begin{lstlisting}
  2420. start:
  2421. movq $10, -8(%rbp)
  2422. negq -8(%rbp)
  2423. movq -8(%rbp), %rax
  2424. addq $52, %rax
  2425. jmp conclusion
  2426. .globl main
  2427. main:
  2428. pushq %rbp
  2429. movq %rsp, %rbp
  2430. subq $16, %rsp
  2431. jmp start
  2432. conclusion:
  2433. addq $16, %rsp
  2434. popq %rbp
  2435. retq
  2436. \end{lstlisting}
  2437. \fi}
  2438. {\if\edition\pythonEd\pythonColor
  2439. \begin{lstlisting}
  2440. .globl main
  2441. main:
  2442. pushq %rbp
  2443. movq %rsp, %rbp
  2444. subq $16, %rsp
  2445. movq $10, -8(%rbp)
  2446. negq -8(%rbp)
  2447. movq -8(%rbp), %rax
  2448. addq $52, %rax
  2449. addq $16, %rsp
  2450. popq %rbp
  2451. retq
  2452. \end{lstlisting}
  2453. \fi}
  2454. \end{tcolorbox}
  2455. \end{minipage}
  2456. \caption{An x86 program that computes
  2457. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2458. \label{fig:p1-x86}
  2459. \end{figure}
  2460. \begin{figure}[tbp]
  2461. \begin{minipage}{0.66\textwidth}
  2462. \begin{tcolorbox}[colback=white]
  2463. \centering
  2464. \begin{tabular}{|r|l|} \hline
  2465. Position & Contents \\ \hline
  2466. $8$(\key{\%rbp}) & return address \\
  2467. $0$(\key{\%rbp}) & old \key{rbp} \\
  2468. $-8$(\key{\%rbp}) & variable $1$ \\
  2469. $-16$(\key{\%rbp}) & variable $2$ \\
  2470. \ldots & \ldots \\
  2471. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2472. \end{tabular}
  2473. \end{tcolorbox}
  2474. \end{minipage}
  2475. \caption{Memory layout of a frame.}
  2476. \label{fig:frame}
  2477. \end{figure}
  2478. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2479. is transferred from the operating system to the \code{main} function.
  2480. The operating system issues a \code{callq main} instruction that
  2481. pushes its return address on the stack and then jumps to
  2482. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2483. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2484. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2485. out of alignment (because the \code{callq} pushed the return address).
  2486. The first three instructions are the typical
  2487. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2488. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2489. pointer \code{rsp} and then saves the base pointer of the caller at
  2490. address \code{rsp} on the stack. The next instruction \code{movq
  2491. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2492. which is pointing to the location of the old base pointer. The
  2493. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2494. make enough room for storing variables. This program needs one
  2495. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2496. 16-byte-aligned, and then we are ready to make calls to other functions.
  2497. \racket{The last instruction of the prelude is \code{jmp start}, which
  2498. transfers control to the instructions that were generated from the
  2499. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2500. \racket{The first instruction under the \code{start} label is}
  2501. %
  2502. \python{The first instruction after the prelude is}
  2503. %
  2504. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2505. %
  2506. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2507. $1$ to $-10$.
  2508. %
  2509. The next instruction moves the $-10$ from variable $1$ into the
  2510. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2511. the value in \code{rax}, updating its contents to $42$.
  2512. \racket{The three instructions under the label \code{conclusion} are the
  2513. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2514. %
  2515. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2516. \code{main} function consists of the last three instructions.}
  2517. %
  2518. The first two restore the \code{rsp} and \code{rbp} registers to their
  2519. states at the beginning of the procedure. In particular,
  2520. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2521. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2522. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2523. \key{retq}, jumps back to the procedure that called this one and adds
  2524. $8$ to the stack pointer.
  2525. Our compiler needs a convenient representation for manipulating x86
  2526. programs, so we define an abstract syntax for x86, shown in
  2527. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2528. \LangXInt{}.
  2529. %
  2530. {\if\edition\pythonEd\pythonColor%
  2531. The main difference between this and the concrete syntax of \LangXInt{}
  2532. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2533. names, and register names are explicitly represented by strings.
  2534. \fi} %
  2535. {\if\edition\racketEd
  2536. The main difference between this and the concrete syntax of \LangXInt{}
  2537. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2538. front of every instruction. Instead instructions are grouped into
  2539. \emph{basic blocks}\index{subject}{basic block} with a
  2540. label associated with every basic block; this is why the \key{X86Program}
  2541. struct includes an alist mapping labels to basic blocks. The reason for this
  2542. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2543. introduce conditional branching. The \code{Block} structure includes
  2544. an $\itm{info}$ field that is not needed in this chapter but becomes
  2545. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2546. $\itm{info}$ field should contain an empty list.
  2547. \fi}
  2548. %
  2549. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2550. node includes an integer for representing the arity of the function,
  2551. that is, the number of arguments, which is helpful to know during
  2552. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2553. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2554. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2555. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2556. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2557. \MID \skey{r14} \MID \skey{r15}}
  2558. \newcommand{\ASTXIntRacket}{
  2559. \begin{array}{lcl}
  2560. \Reg &::=& \allregisters{} \\
  2561. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2562. \MID \DEREF{\Reg}{\Int} \\
  2563. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2564. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2565. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2566. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2567. &\MID& \PUSHQ{\Arg}
  2568. \MID \POPQ{\Arg} \\
  2569. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2570. \MID \RETQ{}
  2571. \MID \JMP{\itm{label}} \\
  2572. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2573. \end{array}
  2574. }
  2575. \newcommand{\ASTXIntPython}{
  2576. \begin{array}{lcl}
  2577. \Reg &::=& \allregisters{} \\
  2578. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2579. \MID \DEREF{\Reg}{\Int} \\
  2580. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2581. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2582. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2583. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2584. &\MID& \PUSHQ{\Arg}
  2585. \MID \POPQ{\Arg} \\
  2586. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2587. \MID \RETQ{} \\
  2588. \Block &::= & \Instr^{+}
  2589. \end{array}
  2590. }
  2591. \begin{figure}[tp]
  2592. \begin{tcolorbox}[colback=white]
  2593. \small
  2594. {\if\edition\racketEd
  2595. \[\arraycolsep=3pt
  2596. \begin{array}{l}
  2597. \ASTXIntRacket \\
  2598. \begin{array}{lcl}
  2599. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2600. \end{array}
  2601. \end{array}
  2602. \]
  2603. \fi}
  2604. {\if\edition\pythonEd\pythonColor
  2605. \[
  2606. \begin{array}{l}
  2607. \ASTXIntPython \\
  2608. \begin{array}{lcl}
  2609. \LangXIntM{} &::= & \XPROGRAM{}{\Block}{}
  2610. \end{array}
  2611. \end{array}
  2612. \]
  2613. \fi}
  2614. \end{tcolorbox}
  2615. \caption{The abstract syntax of \LangXInt{} assembly.}
  2616. \label{fig:x86-int-ast}
  2617. \index{subject}{x86int@\LangXInt{} abstract syntax}
  2618. \end{figure}
  2619. \section{Planning the Trip to x86}
  2620. \label{sec:plan-s0-x86}
  2621. To compile one language to another, it helps to focus on the
  2622. differences between the two languages because the compiler will need
  2623. to bridge those differences. What are the differences between \LangVar{}
  2624. and x86 assembly? Here are some of the most important ones:
  2625. \begin{enumerate}
  2626. \item x86 arithmetic instructions typically have two arguments and
  2627. update the second argument in place. In contrast, \LangVar{}
  2628. arithmetic operations take two arguments and produce a new value.
  2629. An x86 instruction may have at most one memory-accessing argument.
  2630. Furthermore, some x86 instructions place special restrictions on
  2631. their arguments.
  2632. \item An argument of an \LangVar{} operator can be a deeply nested
  2633. expression, whereas x86 instructions restrict their arguments to be
  2634. integer constants, registers, and memory locations.
  2635. {\if\edition\racketEd
  2636. \item The order of execution in x86 is explicit in the syntax, which
  2637. is a sequence of instructions and jumps to labeled positions,
  2638. whereas in \LangVar{} the order of evaluation is a left-to-right
  2639. depth-first traversal of the abstract syntax tree. \fi}
  2640. \item A program in \LangVar{} can have any number of variables,
  2641. whereas x86 has 16 registers and the procedure call stack.
  2642. {\if\edition\racketEd
  2643. \item Variables in \LangVar{} can shadow other variables with the
  2644. same name. In x86, registers have unique names, and memory locations
  2645. have unique addresses.
  2646. \fi}
  2647. \end{enumerate}
  2648. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2649. down the problem into several steps, which deal with these differences
  2650. one at a time. Each of these steps is called a \emph{pass} of the
  2651. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2652. %
  2653. This term indicates that each step passes over, or traverses, the AST
  2654. of the program.
  2655. %
  2656. Furthermore, we follow the nanopass approach, which means that we
  2657. strive for each pass to accomplish one clear objective rather than two
  2658. or three at the same time.
  2659. %
  2660. We begin by sketching how we might implement each pass and give each
  2661. pass a name. We then figure out an ordering of the passes and the
  2662. input/output language for each pass. The very first pass has
  2663. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2664. its output language. In between these two passes, we can choose
  2665. whichever language is most convenient for expressing the output of
  2666. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2667. \emph{intermediate language} of our own design. Finally, to
  2668. implement each pass we write one recursive function per nonterminal in
  2669. the grammar of the input language of the pass.
  2670. \index{subject}{intermediate language}
  2671. Our compiler for \LangVar{} consists of the following passes:
  2672. %
  2673. \begin{description}
  2674. {\if\edition\racketEd
  2675. \item[\key{uniquify}] deals with the shadowing of variables by
  2676. renaming every variable to a unique name.
  2677. \fi}
  2678. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2679. of a primitive operation or function call is a variable or integer,
  2680. that is, an \emph{atomic} expression. We refer to nonatomic
  2681. expressions as \emph{complex}. This pass introduces temporary
  2682. variables to hold the results of complex
  2683. subexpressions.\index{subject}{atomic
  2684. expression}\index{subject}{complex expression}%
  2685. {\if\edition\racketEd
  2686. \item[\key{explicate\_control}] makes the execution order of the
  2687. program explicit. It converts the abstract syntax tree
  2688. representation into a graph in which each node is a labeled sequence
  2689. of statements and the edges are \code{goto} statements.
  2690. \fi}
  2691. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2692. handles the difference between
  2693. \LangVar{} operations and x86 instructions. This pass converts each
  2694. \LangVar{} operation to a short sequence of instructions that
  2695. accomplishes the same task.
  2696. \item[\key{assign\_homes}] replaces variables with registers or stack
  2697. locations.
  2698. \end{description}
  2699. %
  2700. {\if\edition\racketEd
  2701. %
  2702. Our treatment of \code{remove\_complex\_operands} and
  2703. \code{explicate\_control} as separate passes is an example of the
  2704. nanopass approach.\footnote{For analogous decompositions of the
  2705. translation into continuation passing style, see the work of
  2706. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2707. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2708. %
  2709. \fi}
  2710. The next question is, in what order should we apply these passes? This
  2711. question can be challenging because it is difficult to know ahead of
  2712. time which orderings will be better (that is, will be easier to
  2713. implement, produce more efficient code, and so on), and therefore
  2714. ordering often involves trial and error. Nevertheless, we can plan
  2715. ahead and make educated choices regarding the ordering.
  2716. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2717. \key{uniquify}? The \key{uniquify} pass should come first because
  2718. \key{explicate\_control} changes all the \key{let}-bound variables to
  2719. become local variables whose scope is the entire program, which would
  2720. confuse variables with the same name.}
  2721. %
  2722. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2723. because the latter removes the \key{let} form, but it is convenient to
  2724. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2725. %
  2726. \racket{The ordering of \key{uniquify} with respect to
  2727. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2728. \key{uniquify} to come first.}
  2729. The \key{select\_instructions} and \key{assign\_homes} passes are
  2730. intertwined.
  2731. %
  2732. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2733. passing arguments to functions and that it is preferable to assign
  2734. parameters to their corresponding registers. This suggests that it
  2735. would be better to start with the \key{select\_instructions} pass,
  2736. which generates the instructions for argument passing, before
  2737. performing register allocation.
  2738. %
  2739. On the other hand, by selecting instructions first we may run into a
  2740. dead end in \key{assign\_homes}. Recall that only one argument of an
  2741. x86 instruction may be a memory access, but \key{assign\_homes} might
  2742. be forced to assign both arguments to memory locations.
  2743. %
  2744. A sophisticated approach is to repeat the two passes until a solution
  2745. is found. However, to reduce implementation complexity we recommend
  2746. placing \key{select\_instructions} first, followed by the
  2747. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2748. that uses a reserved register to fix outstanding problems.
  2749. \begin{figure}[tbp]
  2750. \begin{tcolorbox}[colback=white]
  2751. {\if\edition\racketEd
  2752. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2753. \node (Lvar) at (0,2) {\large \LangVar{}};
  2754. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2755. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2756. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2757. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2758. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2759. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2760. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2761. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2762. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2763. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2764. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2765. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2766. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2767. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2768. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2769. \end{tikzpicture}
  2770. \fi}
  2771. {\if\edition\pythonEd\pythonColor
  2772. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2773. \node (Lvar) at (0,2) {\large \LangVar{}};
  2774. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2775. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2776. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2777. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2778. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2779. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2780. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2781. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2782. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2783. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2784. \end{tikzpicture}
  2785. \fi}
  2786. \end{tcolorbox}
  2787. \caption{Diagram of the passes for compiling \LangVar{}. }
  2788. \label{fig:Lvar-passes}
  2789. \end{figure}
  2790. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2791. passes and identifies the input and output language of each pass.
  2792. %
  2793. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2794. language, which extends \LangXInt{} with an unbounded number of
  2795. program-scope variables and removes the restrictions regarding
  2796. instruction arguments.
  2797. %
  2798. The last pass, \key{prelude\_and\_conclusion}, places the program
  2799. instructions inside a \code{main} function with instructions for the
  2800. prelude and conclusion.
  2801. %
  2802. \racket{In the next section we discuss the \LangCVar{} intermediate
  2803. language that serves as the output of \code{explicate\_control}.}
  2804. %
  2805. The remainder of this chapter provides guidance on the implementation
  2806. of each of the compiler passes represented in
  2807. figure~\ref{fig:Lvar-passes}.
  2808. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2809. %% are programs that are still in the \LangVar{} language, though the
  2810. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2811. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2812. %% %
  2813. %% The output of \code{explicate\_control} is in an intermediate language
  2814. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2815. %% syntax, which we introduce in the next section. The
  2816. %% \key{select-instruction} pass translates from \LangCVar{} to
  2817. %% \LangXVar{}. The \key{assign-homes} and
  2818. %% \key{patch-instructions}
  2819. %% passes input and output variants of x86 assembly.
  2820. \newcommand{\CvarGrammarRacket}{
  2821. \begin{array}{lcl}
  2822. \Atm &::=& \Int \MID \Var \\
  2823. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2824. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2825. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2826. \end{array}
  2827. }
  2828. \newcommand{\CvarASTRacket}{
  2829. \begin{array}{lcl}
  2830. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2831. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2832. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2833. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2834. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2835. \end{array}
  2836. }
  2837. {\if\edition\racketEd
  2838. \subsection{The \LangCVar{} Intermediate Language}
  2839. The output of \code{explicate\_control} is similar to the C
  2840. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2841. categories for expressions and statements, so we name it \LangCVar{}.
  2842. This style of intermediate language is also known as
  2843. \emph{three-address code}, to emphasize that the typical form of a
  2844. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2845. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2846. The concrete syntax for \LangCVar{} is shown in
  2847. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2848. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2849. %
  2850. The \LangCVar{} language supports the same operators as \LangVar{} but
  2851. the arguments of operators are restricted to atomic
  2852. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2853. assignment statements that can be executed in sequence using the
  2854. \key{Seq} form. A sequence of statements always ends with
  2855. \key{Return}, a guarantee that is baked into the grammar rules for
  2856. \itm{tail}. The naming of this nonterminal comes from the term
  2857. \emph{tail position}\index{subject}{tail position}, which refers to an
  2858. expression that is the last one to execute within a function or
  2859. program.
  2860. A \LangCVar{} program consists of an alist mapping labels to
  2861. tails. This is more general than necessary for the present chapter, as
  2862. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2863. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2864. there is just one label, \key{start}, and the whole program is
  2865. its tail.
  2866. %
  2867. The $\itm{info}$ field of the \key{CProgram} form, after the
  2868. \code{explicate\_control} pass, contains an alist that associates the
  2869. symbol \key{locals} with a list of all the variables used in the
  2870. program. At the start of the program, these variables are
  2871. uninitialized; they become initialized on their first assignment.
  2872. \begin{figure}[tbp]
  2873. \begin{tcolorbox}[colback=white]
  2874. \[
  2875. \begin{array}{l}
  2876. \CvarGrammarRacket \\
  2877. \begin{array}{lcl}
  2878. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2879. \end{array}
  2880. \end{array}
  2881. \]
  2882. \end{tcolorbox}
  2883. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2884. \label{fig:c0-concrete-syntax}
  2885. \index{subject}{Cvar@\LangCVar{} concrete syntax}
  2886. \end{figure}
  2887. \begin{figure}[tbp]
  2888. \begin{tcolorbox}[colback=white]
  2889. \[
  2890. \begin{array}{l}
  2891. \CvarASTRacket \\
  2892. \begin{array}{lcl}
  2893. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2894. \end{array}
  2895. \end{array}
  2896. \]
  2897. \end{tcolorbox}
  2898. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2899. \label{fig:c0-syntax}
  2900. \index{subject}{Cvar@\LangCVar{} abstract syntax}
  2901. \end{figure}
  2902. The definitional interpreter for \LangCVar{} is in the support code,
  2903. in the file \code{interp-Cvar.rkt}.
  2904. \fi}
  2905. {\if\edition\racketEd
  2906. \section{Uniquify Variables}
  2907. \label{sec:uniquify-Lvar}
  2908. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2909. with a unique name. Both the input and output of the \code{uniquify}
  2910. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2911. should translate the program on the left into the program on the
  2912. right.
  2913. \begin{transformation}
  2914. \begin{lstlisting}
  2915. (let ([x 32])
  2916. (+ (let ([x 10]) x) x))
  2917. \end{lstlisting}
  2918. \compilesto
  2919. \begin{lstlisting}
  2920. (let ([x.1 32])
  2921. (+ (let ([x.2 10]) x.2) x.1))
  2922. \end{lstlisting}
  2923. \end{transformation}
  2924. The following is another example translation, this time of a program
  2925. with a \key{let} nested inside the initializing expression of another
  2926. \key{let}.
  2927. \begin{transformation}
  2928. \begin{lstlisting}
  2929. (let ([x (let ([x 4])
  2930. (+ x 1))])
  2931. (+ x 2))
  2932. \end{lstlisting}
  2933. \compilesto
  2934. \begin{lstlisting}
  2935. (let ([x.2 (let ([x.1 4])
  2936. (+ x.1 1))])
  2937. (+ x.2 2))
  2938. \end{lstlisting}
  2939. \end{transformation}
  2940. We recommend implementing \code{uniquify} by creating a structurally
  2941. recursive function named \code{uniquify\_exp} that does little other
  2942. than copy an expression. However, when encountering a \key{let}, it
  2943. should generate a unique name for the variable and associate the old
  2944. name with the new name in an alist.\footnote{The Racket function
  2945. \code{gensym} is handy for generating unique variable names.} The
  2946. \code{uniquify\_exp} function needs to access this alist when it gets
  2947. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2948. for the alist.
  2949. The skeleton of the \code{uniquify\_exp} function is shown in
  2950. figure~\ref{fig:uniquify-Lvar}.
  2951. %% The function is curried so that it is
  2952. %% convenient to partially apply it to an alist and then apply it to
  2953. %% different expressions, as in the last case for primitive operations in
  2954. %% figure~\ref{fig:uniquify-Lvar}.
  2955. The
  2956. %
  2957. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2958. %
  2959. form of Racket is useful for transforming the element of a list to
  2960. produce a new list.\index{subject}{for/list}
  2961. \begin{figure}[tbp]
  2962. \begin{tcolorbox}[colback=white]
  2963. \begin{lstlisting}
  2964. (define (uniquify_exp env)
  2965. (lambda (e)
  2966. (match e
  2967. [(Var x) ___]
  2968. [(Int n) (Int n)]
  2969. [(Let x e body) ___]
  2970. [(Prim op es)
  2971. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2972. (define (uniquify p)
  2973. (match p
  2974. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2975. \end{lstlisting}
  2976. \end{tcolorbox}
  2977. \caption{Skeleton for the \key{uniquify} pass.}
  2978. \label{fig:uniquify-Lvar}
  2979. \end{figure}
  2980. \begin{exercise}
  2981. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2982. Complete the \code{uniquify} pass by filling in the blanks in
  2983. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2984. variables and for the \key{let} form in the file \code{compiler.rkt}
  2985. in the support code.
  2986. \end{exercise}
  2987. \begin{exercise}
  2988. \normalfont\normalsize
  2989. \label{ex:Lvar}
  2990. Create five \LangVar{} programs that exercise the most interesting
  2991. parts of the \key{uniquify} pass; that is, the programs should include
  2992. \key{let} forms, variables, and variables that shadow each other.
  2993. The five programs should be placed in the subdirectory named
  2994. \key{tests}, and the file names should start with \code{var\_test\_}
  2995. followed by a unique integer and end with the file extension
  2996. \key{.rkt}.
  2997. %
  2998. The \key{run-tests.rkt} script in the support code checks whether the
  2999. output programs produce the same result as the input programs. The
  3000. script uses the \key{interp-tests} function
  3001. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3002. your \key{uniquify} pass on the example programs. The \code{passes}
  3003. parameter of \key{interp-tests} is a list that should have one entry
  3004. for each pass in your compiler. For now, define \code{passes} to
  3005. contain just one entry for \code{uniquify} as follows:
  3006. \begin{lstlisting}
  3007. (define passes
  3008. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3009. \end{lstlisting}
  3010. Run the \key{run-tests.rkt} script in the support code to check
  3011. whether the output programs produce the same result as the input
  3012. programs.
  3013. \end{exercise}
  3014. \fi}
  3015. \section{Remove Complex Operands}
  3016. \label{sec:remove-complex-opera-Lvar}
  3017. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3018. into a restricted form in which the arguments of operations are atomic
  3019. expressions. Put another way, this pass removes complex
  3020. operands\index{subject}{complex operand}, such as the expression
  3021. \racket{\code{(- 10)}}\python{\code{-10}}
  3022. in the following program. This is accomplished by introducing a new
  3023. temporary variable, assigning the complex operand to the new
  3024. variable, and then using the new variable in place of the complex
  3025. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3026. right.
  3027. {\if\edition\racketEd
  3028. \begin{transformation}
  3029. % var_test_19.rkt
  3030. \begin{lstlisting}
  3031. (let ([x (+ 42 (- 10))])
  3032. (+ x 10))
  3033. \end{lstlisting}
  3034. \compilesto
  3035. \begin{lstlisting}
  3036. (let ([x (let ([tmp.1 (- 10)])
  3037. (+ 42 tmp.1))])
  3038. (+ x 10))
  3039. \end{lstlisting}
  3040. \end{transformation}
  3041. \fi}
  3042. {\if\edition\pythonEd\pythonColor
  3043. \begin{transformation}
  3044. \begin{lstlisting}
  3045. x = 42 + -10
  3046. print(x + 10)
  3047. \end{lstlisting}
  3048. \compilesto
  3049. \begin{lstlisting}
  3050. tmp_0 = -10
  3051. x = 42 + tmp_0
  3052. tmp_1 = x + 10
  3053. print(tmp_1)
  3054. \end{lstlisting}
  3055. \end{transformation}
  3056. \fi}
  3057. \newcommand{\LvarMonadASTRacket}{
  3058. \begin{array}{rcl}
  3059. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3060. \Exp &::=& \Atm \MID \READ{} \\
  3061. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3062. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3063. \end{array}
  3064. }
  3065. \newcommand{\LvarMonadASTPython}{
  3066. \begin{array}{rcl}
  3067. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3068. \Exp{} &::=& \Atm \MID \READ{} \\
  3069. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3070. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3071. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3072. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3073. \end{array}
  3074. }
  3075. \begin{figure}[tp]
  3076. \centering
  3077. \begin{tcolorbox}[colback=white]
  3078. {\if\edition\racketEd
  3079. \[
  3080. \begin{array}{l}
  3081. \LvarMonadASTRacket \\
  3082. \begin{array}{rcl}
  3083. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3084. \end{array}
  3085. \end{array}
  3086. \]
  3087. \fi}
  3088. {\if\edition\pythonEd\pythonColor
  3089. \[
  3090. \begin{array}{l}
  3091. \LvarMonadASTPython \\
  3092. \begin{array}{rcl}
  3093. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3094. \end{array}
  3095. \end{array}
  3096. \]
  3097. \fi}
  3098. \end{tcolorbox}
  3099. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3100. atomic expressions.}
  3101. \label{fig:Lvar-anf-syntax}
  3102. \index{subject}{Lvarmon@\LangVarANF{} abstract syntax}
  3103. \end{figure}
  3104. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3105. of this pass, the language \LangVarANF{}. The only difference is that
  3106. operator arguments are restricted to be atomic expressions that are
  3107. defined by the \Atm{} nonterminal. In particular, integer constants
  3108. and variables are atomic.
  3109. The atomic expressions are pure (they do not cause or depend on side
  3110. effects) whereas complex expressions may have side effects, such as
  3111. \READ{}. A language with this separation between pure expressions
  3112. versus expressions with side effects is said to be in monadic normal
  3113. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3114. in the name \LangVarANF{}. An important invariant of the
  3115. \code{remove\_complex\_operands} pass is that the relative ordering
  3116. among complex expressions is not changed, but the relative ordering
  3117. between atomic expressions and complex expressions can change and
  3118. often does. These changes are behavior preserving because
  3119. atomic expressions are pure.
  3120. {\if\edition\racketEd
  3121. Another well-known form for intermediate languages is the
  3122. \emph{administrative normal form}
  3123. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3124. \index{subject}{administrative normal form} \index{subject}{ANF}
  3125. %
  3126. The \LangVarANF{} language is not quite in ANF because it allows the
  3127. right-hand side of a \code{let} to be a complex expression, such as
  3128. another \code{let}. The flattening of nested \code{let} expressions is
  3129. instead one of the responsibilities of the \code{explicate\_control}
  3130. pass.
  3131. \fi}
  3132. {\if\edition\racketEd
  3133. We recommend implementing this pass with two mutually recursive
  3134. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3135. \code{rco\_atom} to subexpressions that need to become atomic and to
  3136. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3137. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3138. returns an expression. The \code{rco\_atom} function returns two
  3139. things: an atomic expression and an alist mapping temporary variables to
  3140. complex subexpressions. You can return multiple things from a function
  3141. using Racket's \key{values} form, and you can receive multiple things
  3142. from a function call using the \key{define-values} form.
  3143. \fi}
  3144. %
  3145. {\if\edition\pythonEd\pythonColor
  3146. %
  3147. We recommend implementing this pass with an auxiliary method named
  3148. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3149. Boolean that specifies whether the expression needs to become atomic
  3150. or not. The \code{rco\_exp} method should return a pair consisting of
  3151. the new expression and a list of pairs, associating new temporary
  3152. variables with their initializing expressions.
  3153. %
  3154. \fi}
  3155. {\if\edition\racketEd
  3156. %
  3157. In the example program with the expression \code{(+ 42 (-
  3158. 10))}, the subexpression \code{(- 10)} should be processed using the
  3159. \code{rco\_atom} function because it is an argument of the \code{+}
  3160. operator and therefore needs to become atomic. The output of
  3161. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3162. \begin{transformation}
  3163. \begin{lstlisting}
  3164. (- 10)
  3165. \end{lstlisting}
  3166. \compilesto
  3167. \begin{lstlisting}
  3168. tmp.1
  3169. ((tmp.1 . (- 10)))
  3170. \end{lstlisting}
  3171. \end{transformation}
  3172. \fi}
  3173. %
  3174. {\if\edition\pythonEd\pythonColor
  3175. %
  3176. Returning to the example program with the expression \code{42 + -10},
  3177. the subexpression \code{-10} should be processed using the
  3178. \code{rco\_exp} function with \code{True} as the second argument,
  3179. because \code{-10} is an argument of the \code{+} operator and
  3180. therefore needs to become atomic. The output of \code{rco\_exp}
  3181. applied to \code{-10} is as follows.
  3182. \begin{transformation}
  3183. \begin{lstlisting}
  3184. -10
  3185. \end{lstlisting}
  3186. \compilesto
  3187. \begin{lstlisting}
  3188. tmp_1
  3189. [(tmp_1, -10)]
  3190. \end{lstlisting}
  3191. \end{transformation}
  3192. %
  3193. \fi}
  3194. Take special care of programs, such as the following, that
  3195. %
  3196. \racket{bind a variable to an atomic expression.}
  3197. %
  3198. \python{assign an atomic expression to a variable.}
  3199. %
  3200. You should leave such \racket{variable bindings}\python{assignments}
  3201. unchanged, as shown in the program on the right:\\
  3202. %
  3203. {\if\edition\racketEd
  3204. \begin{transformation}
  3205. % var_test_20.rkt
  3206. \begin{lstlisting}
  3207. (let ([a 42])
  3208. (let ([b a])
  3209. b))
  3210. \end{lstlisting}
  3211. \compilesto
  3212. \begin{lstlisting}
  3213. (let ([a 42])
  3214. (let ([b a])
  3215. b))
  3216. \end{lstlisting}
  3217. \end{transformation}
  3218. \fi}
  3219. {\if\edition\pythonEd\pythonColor
  3220. \begin{transformation}
  3221. \begin{lstlisting}
  3222. a = 42
  3223. b = a
  3224. print(b)
  3225. \end{lstlisting}
  3226. \compilesto
  3227. \begin{lstlisting}
  3228. a = 42
  3229. b = a
  3230. print(b)
  3231. \end{lstlisting}
  3232. \end{transformation}
  3233. \fi}
  3234. %
  3235. \noindent A careless implementation might produce the following output with
  3236. unnecessary temporary variables.
  3237. \begin{center}
  3238. \begin{minipage}{0.4\textwidth}
  3239. {\if\edition\racketEd
  3240. \begin{lstlisting}
  3241. (let ([tmp.1 42])
  3242. (let ([a tmp.1])
  3243. (let ([tmp.2 a])
  3244. (let ([b tmp.2])
  3245. b))))
  3246. \end{lstlisting}
  3247. \fi}
  3248. {\if\edition\pythonEd\pythonColor
  3249. \begin{lstlisting}
  3250. tmp_1 = 42
  3251. a = tmp_1
  3252. tmp_2 = a
  3253. b = tmp_2
  3254. print(b)
  3255. \end{lstlisting}
  3256. \fi}
  3257. \end{minipage}
  3258. \end{center}
  3259. \begin{exercise}
  3260. \normalfont\normalsize
  3261. {\if\edition\racketEd
  3262. Implement the \code{remove\_complex\_operands} function in
  3263. \code{compiler.rkt}.
  3264. %
  3265. Create three new \LangVar{} programs that exercise the interesting
  3266. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3267. regarding file names described in exercise~\ref{ex:Lvar}.
  3268. %
  3269. In the \code{run-tests.rkt} script, add the following entry to the
  3270. list of \code{passes}, and then run the script to test your compiler.
  3271. \begin{lstlisting}
  3272. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3273. \end{lstlisting}
  3274. In debugging your compiler, it is often useful to see the intermediate
  3275. programs that are output from each pass. To print the intermediate
  3276. programs, place \lstinline{(debug-level 1)} before the call to
  3277. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3278. %
  3279. {\if\edition\pythonEd\pythonColor
  3280. Implement the \code{remove\_complex\_operands} pass in
  3281. \code{compiler.py}, creating auxiliary functions for each
  3282. nonterminal in the grammar, that is, \code{rco\_exp}
  3283. and \code{rco\_stmt}. We recommend that you use the function
  3284. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3285. \fi}
  3286. \end{exercise}
  3287. {\if\edition\pythonEd\pythonColor
  3288. \begin{exercise}
  3289. \normalfont\normalsize
  3290. \label{ex:Lvar}
  3291. Create five \LangVar{} programs that exercise the most interesting
  3292. parts of the \code{remove\_complex\_operands} pass. The five programs
  3293. should be placed in the subdirectory \key{tests/var}, and the file
  3294. names should end with the file extension \key{.py}. Run the
  3295. \key{run-tests.py} script in the support code to check whether the
  3296. output programs produce the same result as the input programs.
  3297. \end{exercise}
  3298. \fi}
  3299. {\if\edition\racketEd
  3300. \section{Explicate Control}
  3301. \label{sec:explicate-control-Lvar}
  3302. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3303. programs that make the order of execution explicit in their
  3304. syntax. For now this amounts to flattening \key{let} constructs into a
  3305. sequence of assignment statements. For example, consider the following
  3306. \LangVar{} program:\\
  3307. % var_test_11.rkt
  3308. \begin{minipage}{0.96\textwidth}
  3309. \begin{lstlisting}
  3310. (let ([y (let ([x 20])
  3311. (+ x (let ([x 22]) x)))])
  3312. y)
  3313. \end{lstlisting}
  3314. \end{minipage}\\
  3315. %
  3316. The output of the previous pass is shown next, on the left, and the
  3317. output of \code{explicate\_control} is on the right. Recall that the
  3318. right-hand side of a \key{let} executes before its body, so that the order
  3319. of evaluation for this program is to assign \code{20} to \code{x.1},
  3320. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3321. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3322. this ordering explicit.
  3323. \begin{transformation}
  3324. \begin{lstlisting}
  3325. (let ([y (let ([x.1 20])
  3326. (let ([x.2 22])
  3327. (+ x.1 x.2)))])
  3328. y)
  3329. \end{lstlisting}
  3330. \compilesto
  3331. \begin{lstlisting}[language=C]
  3332. start:
  3333. x.1 = 20;
  3334. x.2 = 22;
  3335. y = (+ x.1 x.2);
  3336. return y;
  3337. \end{lstlisting}
  3338. \end{transformation}
  3339. \begin{figure}[tbp]
  3340. \begin{tcolorbox}[colback=white]
  3341. \begin{lstlisting}
  3342. (define (explicate_tail e)
  3343. (match e
  3344. [(Var x) ___]
  3345. [(Int n) (Return (Int n))]
  3346. [(Let x rhs body) ___]
  3347. [(Prim op es) ___]
  3348. [else (error "explicate_tail unhandled case" e)]))
  3349. (define (explicate_assign e x cont)
  3350. (match e
  3351. [(Var x) ___]
  3352. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3353. [(Let y rhs body) ___]
  3354. [(Prim op es) ___]
  3355. [else (error "explicate_assign unhandled case" e)]))
  3356. (define (explicate_control p)
  3357. (match p
  3358. [(Program info body) ___]))
  3359. \end{lstlisting}
  3360. \end{tcolorbox}
  3361. \caption{Skeleton for the \code{explicate\_control} pass.}
  3362. \label{fig:explicate-control-Lvar}
  3363. \end{figure}
  3364. The organization of this pass depends on the notion of tail position
  3365. to which we have alluded. Here is the definition.
  3366. \begin{definition}\normalfont
  3367. The following rules define when an expression is in \emph{tail
  3368. position}\index{subject}{tail position} for the language \LangVar{}.
  3369. \begin{enumerate}
  3370. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3371. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3372. \end{enumerate}
  3373. \end{definition}
  3374. We recommend implementing \code{explicate\_control} using two
  3375. recursive functions, \code{explicate\_tail} and
  3376. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3377. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3378. function should be applied to expressions in tail position, whereas the
  3379. \code{explicate\_assign} should be applied to expressions that occur on
  3380. the right-hand side of a \key{let}.
  3381. %
  3382. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3383. input and produces a \Tail{} in \LangCVar{} (see
  3384. figure~\ref{fig:c0-syntax}).
  3385. %
  3386. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3387. the variable to which it is to be assigned, and a \Tail{} in
  3388. \LangCVar{} for the code that comes after the assignment. The
  3389. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3390. The \code{explicate\_assign} function is in accumulator-passing style:
  3391. the \code{cont} parameter is used for accumulating the output. This
  3392. accumulator-passing style plays an important role in the way that we
  3393. generate high-quality code for conditional expressions in
  3394. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3395. continuation because it contains the generated code that should come
  3396. after the current assignment. This code organization is also related
  3397. to continuation-passing style, except that \code{cont} is not what
  3398. happens next during compilation but is what happens next in the
  3399. generated code.
  3400. \begin{exercise}\normalfont\normalsize
  3401. %
  3402. Implement the \code{explicate\_control} function in
  3403. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3404. exercise the code in \code{explicate\_control}.
  3405. %
  3406. In the \code{run-tests.rkt} script, add the following entry to the
  3407. list of \code{passes} and then run the script to test your compiler.
  3408. \begin{lstlisting}
  3409. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3410. \end{lstlisting}
  3411. \end{exercise}
  3412. \fi}
  3413. \section{Select Instructions}
  3414. \label{sec:select-Lvar}
  3415. \index{subject}{select instructions}
  3416. In the \code{select\_instructions} pass we begin the work of
  3417. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3418. language of this pass, \LangXVar{}, is a variant of x86 that still
  3419. uses variables, so we add an AST node of the form $\XVAR{\itm{var}}$
  3420. to the \Arg{} nonterminal of the \LangXInt{} abstract syntax
  3421. (figure~\ref{fig:x86-int-ast})\index{subject}{x86var@\LangXVar{}}.
  3422. \racket{We recommend implementing the \code{select\_instructions} with
  3423. three auxiliary functions, one for each of the nonterminals of
  3424. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.} \python{We recommend
  3425. implementing an auxiliary function named \code{select\_stmt} for the
  3426. $\Stmt$ nonterminal.}
  3427. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3428. same and integer constants change to immediates; that is, $\INT{n}$
  3429. changes to $\IMM{n}$.}
  3430. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3431. arithmetic operations. For example, consider the following addition
  3432. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3433. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3434. \key{addq} instruction in x86, but it performs an in-place update.
  3435. %
  3436. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3437. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3438. \begin{transformation}
  3439. {\if\edition\racketEd
  3440. \begin{lstlisting}
  3441. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3442. \end{lstlisting}
  3443. \fi}
  3444. {\if\edition\pythonEd\pythonColor
  3445. \begin{lstlisting}
  3446. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3447. \end{lstlisting}
  3448. \fi}
  3449. \compilesto
  3450. \begin{lstlisting}
  3451. movq |$\Arg_1$|, %rax
  3452. addq |$\Arg_2$|, %rax
  3453. movq %rax, |$\itm{var}$|
  3454. \end{lstlisting}
  3455. \end{transformation}
  3456. %
  3457. However, with some care we can generate shorter sequences of
  3458. instructions. Suppose that one or more of the arguments of the
  3459. addition is the same variable as the left-hand side of the assignment.
  3460. Then the assignment statement can be translated into a single
  3461. \key{addq} instruction, as follows.
  3462. \begin{transformation}
  3463. {\if\edition\racketEd
  3464. \begin{lstlisting}
  3465. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3466. \end{lstlisting}
  3467. \fi}
  3468. {\if\edition\pythonEd\pythonColor
  3469. \begin{lstlisting}
  3470. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3471. \end{lstlisting}
  3472. \fi}
  3473. \compilesto
  3474. \begin{lstlisting}
  3475. addq |$\Arg_1$|, |$\itm{var}$|
  3476. \end{lstlisting}
  3477. \end{transformation}
  3478. %
  3479. On the other hand, if $\Atm_2$ is not the same variable as the
  3480. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3481. and then add $\Arg_2$ to \itm{var}.
  3482. %
  3483. \begin{transformation}
  3484. {\if\edition\racketEd
  3485. \begin{lstlisting}
  3486. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3487. \end{lstlisting}
  3488. \fi}
  3489. {\if\edition\pythonEd\pythonColor
  3490. \begin{lstlisting}
  3491. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3492. \end{lstlisting}
  3493. \fi}
  3494. \compilesto
  3495. \begin{lstlisting}
  3496. movq |$\Arg_1$|, |$\itm{var}$|
  3497. addq |$\Arg_2$|, |$\itm{var}$|
  3498. \end{lstlisting}
  3499. \end{transformation}
  3500. The \READOP{} operation does not have a direct counterpart in x86
  3501. assembly, so we provide this functionality with the function
  3502. \code{read\_int} in the file \code{runtime.c}, written in
  3503. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3504. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3505. system}, or simply the \emph{runtime} for short. When compiling your
  3506. generated x86 assembly code, you need to compile \code{runtime.c} to
  3507. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3508. \code{-c}) and link it into the executable. For our purposes of code
  3509. generation, all you need to do is translate an assignment of
  3510. \READOP{} into a call to the \code{read\_int} function followed by a
  3511. move from \code{rax} to the left-hand side variable. (The
  3512. return value of a function is placed in \code{rax}.)
  3513. \begin{transformation}
  3514. {\if\edition\racketEd
  3515. \begin{lstlisting}
  3516. |$\itm{var}$| = (read);
  3517. \end{lstlisting}
  3518. \fi}
  3519. {\if\edition\pythonEd\pythonColor
  3520. \begin{lstlisting}
  3521. |$\itm{var}$| = input_int();
  3522. \end{lstlisting}
  3523. \fi}
  3524. \compilesto
  3525. \begin{lstlisting}
  3526. callq read_int
  3527. movq %rax, |$\itm{var}$|
  3528. \end{lstlisting}
  3529. \end{transformation}
  3530. {\if\edition\pythonEd\pythonColor
  3531. %
  3532. Similarly, we translate the \code{print} operation, shown below, into
  3533. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3534. In x86, the first six arguments to functions are passed in registers,
  3535. with the first argument passed in register \code{rdi}. So we move the
  3536. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3537. \code{callq} instruction.
  3538. \begin{transformation}
  3539. \begin{lstlisting}
  3540. print(|$\Atm$|)
  3541. \end{lstlisting}
  3542. \compilesto
  3543. \begin{lstlisting}
  3544. movq |$\Arg$|, %rdi
  3545. callq print_int
  3546. \end{lstlisting}
  3547. \end{transformation}
  3548. %
  3549. \fi}
  3550. {\if\edition\racketEd
  3551. %
  3552. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3553. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3554. assignment to the \key{rax} register followed by a jump to
  3555. the label \key{conclusion}. Later, in Section~\ref{sec:print-x86},
  3556. we discuss the generation of the \key{conclusion} block.
  3557. In the meantime, the interpreter for \LangXVar{} recognizes a jump
  3558. to \key{conclusion} as the end of the program.
  3559. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3560. recursively and then append the resulting instructions.
  3561. %
  3562. \fi}
  3563. {\if\edition\pythonEd\pythonColor
  3564. We recommend that you use the function \code{utils.label\_name} to
  3565. transform strings into labels, for example, in
  3566. the target of the \code{callq} instruction. This practice makes your
  3567. compiler portable across Linux and Mac OS X, which requires an underscore
  3568. prefixed to all labels.
  3569. \fi}
  3570. \begin{exercise}
  3571. \normalfont\normalsize
  3572. {\if\edition\racketEd
  3573. Implement the \code{select\_instructions} pass in
  3574. \code{compiler.rkt}. Create three new example programs that are
  3575. designed to exercise all the interesting cases in this pass.
  3576. %
  3577. In the \code{run-tests.rkt} script, add the following entry to the
  3578. list of \code{passes} and then run the script to test your compiler.
  3579. \begin{lstlisting}
  3580. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3581. \end{lstlisting}
  3582. \fi}
  3583. {\if\edition\pythonEd\pythonColor
  3584. Implement the \key{select\_instructions} pass in
  3585. \code{compiler.py}. Create three new example programs that are
  3586. designed to exercise all the interesting cases in this pass.
  3587. Run the \code{run-tests.py} script to check
  3588. whether the output programs produce the same result as the input
  3589. programs.
  3590. \fi}
  3591. \end{exercise}
  3592. \section{Assign Homes}
  3593. \label{sec:assign-Lvar}
  3594. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3595. \LangXVar{} programs that no longer use program variables. Thus, the
  3596. \code{assign\_homes} pass is responsible for placing all the program
  3597. variables in registers or on the stack. For runtime efficiency, it is
  3598. better to place variables in registers, but because there are only
  3599. sixteen registers, some programs must necessarily resort to placing
  3600. some variables on the stack. In this chapter we focus on the mechanics
  3601. of placing variables on the stack. We study an algorithm for placing
  3602. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3603. Consider again the following \LangVar{} program from
  3604. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3605. % var_test_20.rkt
  3606. \begin{minipage}{0.96\textwidth}
  3607. {\if\edition\racketEd
  3608. \begin{lstlisting}
  3609. (let ([a 42])
  3610. (let ([b a])
  3611. b))
  3612. \end{lstlisting}
  3613. \fi}
  3614. {\if\edition\pythonEd\pythonColor
  3615. \begin{lstlisting}
  3616. a = 42
  3617. b = a
  3618. print(b)
  3619. \end{lstlisting}
  3620. \fi}
  3621. \end{minipage}\\
  3622. %
  3623. The output of \code{select\_instructions} is shown next, on the left,
  3624. and the output of \code{assign\_homes} is on the right. In this
  3625. example, we assign variable \code{a} to stack location
  3626. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3627. \begin{transformation}
  3628. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3629. movq $42, a
  3630. movq a, b
  3631. movq b, %rax
  3632. \end{lstlisting}
  3633. \compilesto
  3634. %stack-space: 16
  3635. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3636. movq $42, -8(%rbp)
  3637. movq -8(%rbp), -16(%rbp)
  3638. movq -16(%rbp), %rax
  3639. \end{lstlisting}
  3640. \end{transformation}
  3641. \racket{
  3642. The \code{assign\_homes} pass should replace all variables
  3643. with stack locations.
  3644. The list of variables can be obtained from
  3645. the \code{locals-types} entry in the $\itm{info}$ of the
  3646. \code{X86Program} node. The \code{locals-types} entry is an alist
  3647. mapping all the variables in the program to their types
  3648. (for now, just \code{Integer}).
  3649. As an aside, the \code{locals-types} entry is
  3650. computed by \code{type-check-Cvar} in the support code, which
  3651. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3652. which you should propagate to the \code{X86Program} node.}
  3653. %
  3654. \python{The \code{assign\_homes} pass should replace all uses of
  3655. variables with stack locations.}
  3656. %
  3657. In the process of assigning variables to stack locations, it is
  3658. convenient for you to compute and store the size of the frame (in
  3659. bytes) in
  3660. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3661. %
  3662. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3663. %
  3664. which is needed later to generate the conclusion of the \code{main}
  3665. procedure. The x86-64 standard requires the frame size to be a
  3666. multiple of 16 bytes.\index{subject}{frame}
  3667. % TODO: store the number of variables instead? -Jeremy
  3668. \begin{exercise}\normalfont\normalsize
  3669. Implement the \code{assign\_homes} pass in
  3670. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3671. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3672. grammar. We recommend that the auxiliary functions take an extra
  3673. parameter that maps variable names to homes (stack locations for now).
  3674. %
  3675. {\if\edition\racketEd
  3676. In the \code{run-tests.rkt} script, add the following entry to the
  3677. list of \code{passes} and then run the script to test your compiler.
  3678. \begin{lstlisting}
  3679. (list "assign homes" assign-homes interp_x86-0)
  3680. \end{lstlisting}
  3681. \fi}
  3682. {\if\edition\pythonEd\pythonColor
  3683. Run the \code{run-tests.py} script to check
  3684. whether the output programs produce the same result as the input
  3685. programs.
  3686. \fi}
  3687. \end{exercise}
  3688. \section{Patch Instructions}
  3689. \label{sec:patch-s0}
  3690. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3691. \LangXInt{} by making sure that each instruction adheres to the
  3692. restriction that at most one argument of an instruction may be a
  3693. memory reference.
  3694. We return to the following example.\\
  3695. \begin{minipage}{0.5\textwidth}
  3696. % var_test_20.rkt
  3697. {\if\edition\racketEd
  3698. \begin{lstlisting}
  3699. (let ([a 42])
  3700. (let ([b a])
  3701. b))
  3702. \end{lstlisting}
  3703. \fi}
  3704. {\if\edition\pythonEd\pythonColor
  3705. \begin{lstlisting}
  3706. a = 42
  3707. b = a
  3708. print(b)
  3709. \end{lstlisting}
  3710. \fi}
  3711. \end{minipage}\\
  3712. The \code{assign\_homes} pass produces the following translation. \\
  3713. \begin{minipage}{0.5\textwidth}
  3714. {\if\edition\racketEd
  3715. \begin{lstlisting}
  3716. movq $42, -8(%rbp)
  3717. movq -8(%rbp), -16(%rbp)
  3718. movq -16(%rbp), %rax
  3719. \end{lstlisting}
  3720. \fi}
  3721. {\if\edition\pythonEd\pythonColor
  3722. \begin{lstlisting}
  3723. movq $42, -8(%rbp)
  3724. movq -8(%rbp), -16(%rbp)
  3725. movq -16(%rbp), %rdi
  3726. callq print_int
  3727. \end{lstlisting}
  3728. \fi}
  3729. \end{minipage}\\
  3730. The second \key{movq} instruction is problematic because both
  3731. arguments are stack locations. We suggest fixing this problem by
  3732. moving from the source location to the register \key{rax} and then
  3733. from \key{rax} to the destination location, as follows.
  3734. \begin{lstlisting}
  3735. movq -8(%rbp), %rax
  3736. movq %rax, -16(%rbp)
  3737. \end{lstlisting}
  3738. There is a similar corner case that also needs to be dealt with. If
  3739. one argument is an immediate integer larger than $2^{16}$ and the
  3740. other is a memory reference, then the instruction is invalid. One can
  3741. fix this, for example, by first moving the immediate integer into
  3742. \key{rax} and then using \key{rax} in place of the integer.
  3743. \begin{exercise}
  3744. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3745. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3746. Create three new example programs that are
  3747. designed to exercise all the interesting cases in this pass.
  3748. %
  3749. {\if\edition\racketEd
  3750. In the \code{run-tests.rkt} script, add the following entry to the
  3751. list of \code{passes} and then run the script to test your compiler.
  3752. \begin{lstlisting}
  3753. (list "patch instructions" patch_instructions interp_x86-0)
  3754. \end{lstlisting}
  3755. \fi}
  3756. {\if\edition\pythonEd\pythonColor
  3757. Run the \code{run-tests.py} script to check
  3758. whether the output programs produce the same result as the input
  3759. programs.
  3760. \fi}
  3761. \end{exercise}
  3762. \section{Generate Prelude and Conclusion}
  3763. \label{sec:print-x86}
  3764. \index{subject}{prelude}\index{subject}{conclusion}
  3765. The last step of the compiler from \LangVar{} to x86 is to generate
  3766. the \code{main} function with a prelude and conclusion wrapped around
  3767. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3768. discussed in section~\ref{sec:x86}.
  3769. When running on Mac OS X, your compiler should prefix an underscore to
  3770. all labels (for example, changing \key{main} to \key{\_main}).
  3771. %
  3772. \racket{The Racket call \code{(system-type 'os)} is useful for
  3773. determining which operating system the compiler is running on. It
  3774. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3775. %
  3776. \python{The Python \code{platform.system}
  3777. function returns \code{\textquotesingle Linux\textquotesingle},
  3778. \code{\textquotesingle Windows\textquotesingle}, or
  3779. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3780. \begin{exercise}\normalfont\normalsize
  3781. %
  3782. Implement the \key{prelude\_and\_conclusion} pass in
  3783. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3784. %
  3785. {\if\edition\racketEd
  3786. In the \code{run-tests.rkt} script, add the following entry to the
  3787. list of \code{passes} and then run the script to test your compiler.
  3788. \begin{lstlisting}
  3789. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3790. \end{lstlisting}
  3791. %
  3792. Uncomment the call to the \key{compiler-tests} function
  3793. (appendix~\ref{appendix:utilities}), which tests your complete
  3794. compiler by executing the generated x86 code. It translates the x86
  3795. AST that you produce into a string by invoking the \code{print-x86}
  3796. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3797. the provided \key{runtime.c} file to \key{runtime.o} using
  3798. \key{gcc}. Run the script to test your compiler.
  3799. %
  3800. \fi}
  3801. {\if\edition\pythonEd\pythonColor
  3802. %
  3803. Run the \code{run-tests.py} script to check whether the output
  3804. programs produce the same result as the input programs. That script
  3805. translates the x86 AST that you produce into a string by invoking the
  3806. \code{repr} method that is implemented by the x86 AST classes in
  3807. \code{x86\_ast.py}.
  3808. %
  3809. \fi}
  3810. \end{exercise}
  3811. \section{Challenge: Partial Evaluator for \LangVar{}}
  3812. \label{sec:pe-Lvar}
  3813. \index{subject}{partialevaluation@partial evaluation}
  3814. This section describes two optional challenge exercises that involve
  3815. adapting and improving the partial evaluator for \LangInt{} that was
  3816. introduced in section~\ref{sec:partial-evaluation}.
  3817. \begin{exercise}\label{ex:pe-Lvar}
  3818. \normalfont\normalsize
  3819. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3820. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3821. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3822. %
  3823. \racket{\key{let} binding}\python{assignment}
  3824. %
  3825. to the \LangInt{} language, so you will need to add cases for them in
  3826. the \code{pe\_exp}
  3827. %
  3828. \racket{function.}
  3829. %
  3830. \python{and \code{pe\_stmt} functions.}
  3831. %
  3832. Once complete, add the partial evaluation pass to the front of your
  3833. compiler.
  3834. \python{In particular, add a method named \code{partial\_eval} to
  3835. the \code{Compiler} class in \code{compiler.py}.}
  3836. Check that your compiler still passes all the
  3837. tests.
  3838. \end{exercise}
  3839. \begin{exercise}
  3840. \normalfont\normalsize
  3841. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3842. \code{pe\_add} auxiliary functions with functions that know more about
  3843. arithmetic. For example, your partial evaluator should translate
  3844. {\if\edition\racketEd
  3845. \[
  3846. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3847. \code{(+ 2 (read))}
  3848. \]
  3849. \fi}
  3850. {\if\edition\pythonEd\pythonColor
  3851. \[
  3852. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3853. \code{2 + input\_int()}
  3854. \]
  3855. \fi}
  3856. %
  3857. To accomplish this, the \code{pe\_exp} function should produce output
  3858. in the form of the $\itm{residual}$ nonterminal of the following
  3859. grammar. The idea is that when processing an addition expression, we
  3860. can always produce one of the following: (1) an integer constant, (2)
  3861. an addition expression with an integer constant on the left-hand side
  3862. but not the right-hand side, or (3) an addition expression in which
  3863. neither subexpression is a constant.
  3864. %
  3865. {\if\edition\racketEd
  3866. \[
  3867. \begin{array}{lcl}
  3868. \itm{inert} &::=& \Var
  3869. \MID \LP\key{read}\RP
  3870. \MID \LP\key{-} ~\Var\RP
  3871. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3872. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3873. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3874. \itm{residual} &::=& \Int
  3875. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3876. \MID \itm{inert}
  3877. \end{array}
  3878. \]
  3879. \fi}
  3880. {\if\edition\pythonEd\pythonColor
  3881. \[
  3882. \begin{array}{lcl}
  3883. \itm{inert} &::=& \Var
  3884. \MID \key{input\_int}\LP\RP
  3885. \MID \key{-} \Var
  3886. \MID \key{-} \key{input\_int}\LP\RP
  3887. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3888. \itm{residual} &::=& \Int
  3889. \MID \Int ~ \key{+} ~ \itm{inert}
  3890. \MID \itm{inert}
  3891. \end{array}
  3892. \]
  3893. \fi}
  3894. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3895. inputs are $\itm{residual}$ expressions and they should return
  3896. $\itm{residual}$ expressions. Once the improvements are complete,
  3897. make sure that your compiler still passes all the tests. After
  3898. all, fast code is useless if it produces incorrect results!
  3899. \end{exercise}
  3900. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3901. {\if\edition\pythonEd\pythonColor
  3902. \chapter{Parsing}
  3903. \label{ch:parsing}
  3904. \setcounter{footnote}{0}
  3905. \index{subject}{parsing}
  3906. In this chapter we learn how to use the Lark parser
  3907. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3908. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3909. You are then asked to create a parser for \LangVar{} using Lark.
  3910. We also describe the parsing algorithms used inside Lark, studying the
  3911. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3912. A parser framework such as Lark takes in a specification of the
  3913. concrete syntax and an input program and produces a parse tree. Even
  3914. though a parser framework does most of the work for us, using one
  3915. properly requires some knowledge. In particular, we must learn about
  3916. its specification languages and we must learn how to deal with
  3917. ambiguity in our language specifications. Also, some algorithms, such
  3918. as LALR(1), place restrictions on the grammars they can handle, in
  3919. which case knowing the algorithm helps with trying to decipher the
  3920. error messages.
  3921. The process of parsing is traditionally subdivided into two phases:
  3922. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3923. analysis} (also called parsing). The lexical analysis phase
  3924. translates the sequence of characters into a sequence of
  3925. \emph{tokens}, that is, words consisting of several characters. The
  3926. parsing phase organizes the tokens into a \emph{parse tree} that
  3927. captures how the tokens were matched by rules in the grammar of the
  3928. language. The reason for the subdivision into two phases is to enable
  3929. the use of a faster but less powerful algorithm for lexical analysis
  3930. and the use of a slower but more powerful algorithm for parsing.
  3931. %
  3932. %% Likewise, parser generators typical come in pairs, with separate
  3933. %% generators for the lexical analyzer (or lexer for short) and for the
  3934. %% parser. A particularly influential pair of generators were
  3935. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3936. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3937. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3938. %% Compiler Compiler.
  3939. %
  3940. The Lark parser framework that we use in this chapter includes both
  3941. lexical analyzers and parsers. The next section discusses lexical
  3942. analysis, and the remainder of the chapter discusses parsing.
  3943. \section{Lexical Analysis and Regular Expressions}
  3944. \label{sec:lex}
  3945. The lexical analyzers produced by Lark turn a sequence of characters
  3946. (a string) into a sequence of token objects. For example, a Lark
  3947. generated lexer for \LangInt{} converts the string
  3948. \begin{lstlisting}
  3949. 'print(1 + 3)'
  3950. \end{lstlisting}
  3951. \noindent into the following sequence of token objects:
  3952. \begin{center}
  3953. \begin{minipage}{0.95\textwidth}
  3954. \begin{lstlisting}
  3955. Token('PRINT', 'print')
  3956. Token('LPAR', '(')
  3957. Token('INT', '1')
  3958. Token('PLUS', '+')
  3959. Token('INT', '3')
  3960. Token('RPAR', ')')
  3961. Token('NEWLINE', '\n')
  3962. \end{lstlisting}
  3963. \end{minipage}
  3964. \end{center}
  3965. Each token includes a field for its \code{type}, such as \skey{INT},
  3966. and a field for its \code{value}, such as \skey{1}.
  3967. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3968. specification language for Lark's lexer is one regular expression for
  3969. each type of token. The term \emph{regular} comes from the term
  3970. \emph{regular languages}, which are the languages that can be
  3971. recognized by a finite state machine. A \emph{regular expression} is a
  3972. pattern formed of the following core elements:\index{subject}{regular
  3973. expression}\footnote{Regular expressions traditionally include the
  3974. empty regular expression that matches any zero-length part of a
  3975. string, but Lark does not support the empty regular expression.}
  3976. \begin{itemize}
  3977. \item A single character $c$ is a regular expression, and it matches
  3978. only itself. For example, the regular expression \code{a} matches
  3979. only the string \skey{a}.
  3980. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3981. R_2$ form a regular expression that matches any string that matches
  3982. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3983. matches the string \skey{a} and the string \skey{c}.
  3984. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3985. expression that matches any string that can be formed by
  3986. concatenating two strings, where the first string matches $R_1$ and
  3987. the second string matches $R_2$. For example, the regular expression
  3988. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3989. (Parentheses can be used to control the grouping of operators within
  3990. a regular expression.)
  3991. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3992. Kleene closure) is a regular expression that matches any string that
  3993. can be formed by concatenating zero or more strings that each match
  3994. the regular expression $R$. For example, the regular expression
  3995. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3996. \skey{abc}.
  3997. \end{itemize}
  3998. For our convenience, Lark also accepts the following extended set of
  3999. regular expressions that are automatically translated into the core
  4000. regular expressions.
  4001. \begin{itemize}
  4002. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  4003. c_n]$ is a regular expression that matches any one of the
  4004. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  4005. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  4006. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  4007. a regular expression that matches any character between $c_1$ and
  4008. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  4009. letter in the alphabet.
  4010. \item A regular expression followed by the plus symbol $R\ttm{+}$
  4011. is a regular expression that matches any string that can
  4012. be formed by concatenating one or more strings that each match $R$.
  4013. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  4014. matches \skey{b} and \skey{bzca}.
  4015. \item A regular expression followed by a question mark $R\ttm{?}$
  4016. is a regular expression that matches any string that either
  4017. matches $R$ or is the empty string.
  4018. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  4019. \end{itemize}
  4020. In a Lark grammar file, each kind of token is specified by a
  4021. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4022. that consists of the name of the terminal followed by a colon followed
  4023. by a sequence of literals. The literals include strings such as
  4024. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4025. terminal names, and literals composed using the regular expression
  4026. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4027. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4028. \begin{center}
  4029. \begin{minipage}{0.95\textwidth}
  4030. \begin{lstlisting}
  4031. DIGIT: /[0-9]/
  4032. INT: "-"? DIGIT+
  4033. NEWLINE: (/\r/? /\n/)+
  4034. \end{lstlisting}
  4035. \end{minipage}
  4036. \end{center}
  4037. \section{Grammars and Parse Trees}
  4038. \label{sec:CFG}
  4039. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4040. specify the abstract syntax of a language. We now take a closer look
  4041. at using grammar rules to specify the concrete syntax. Recall that
  4042. each rule has a left-hand side and a right-hand side, where the
  4043. left-hand side is a nonterminal and the right-hand side is a pattern
  4044. that defines what can be parsed as that nonterminal. For concrete
  4045. syntax, each right-hand side expresses a pattern for a string instead
  4046. of a pattern for an abstract syntax tree. In particular, each
  4047. right-hand side is a sequence of
  4048. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4049. terminal or a nonterminal. The nonterminals play the same role as in
  4050. the abstract syntax, defining categories of syntax. The nonterminals
  4051. of a grammar include the tokens defined in the lexer and all the
  4052. nonterminals defined by the grammar rules.
  4053. As an example, let us take a closer look at the concrete syntax of the
  4054. \LangInt{} language, repeated here.
  4055. \[
  4056. \begin{array}{l}
  4057. \LintGrammarPython \\
  4058. \begin{array}{rcl}
  4059. \LangInt{} &::=& \Stmt^{*}
  4060. \end{array}
  4061. \end{array}
  4062. \]
  4063. The Lark syntax for grammar rules differs slightly from the variant of
  4064. BNF that we use in this book. In particular, the notation $::=$ is
  4065. replaced by a single colon, and the use of typewriter font for string
  4066. literals is replaced by quotation marks. The following grammar serves
  4067. as a first draft of a Lark grammar for \LangInt{}.
  4068. \begin{center}
  4069. \begin{minipage}{0.95\textwidth}
  4070. \begin{lstlisting}[escapechar=$]
  4071. exp: INT
  4072. | "input_int" "(" ")"
  4073. | "-" exp
  4074. | exp "+" exp
  4075. | exp "-" exp
  4076. | "(" exp ")"
  4077. stmt_list:
  4078. | stmt NEWLINE stmt_list
  4079. lang_int: stmt_list
  4080. \end{lstlisting}
  4081. \end{minipage}
  4082. \end{center}
  4083. Let us begin by discussing the rule \code{exp: INT}, which says that
  4084. if the lexer matches a string to \code{INT}, then the parser also
  4085. categorizes the string as an \code{exp}. Recall that in
  4086. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4087. nonterminal with a sentence in English. Here we specify \code{INT}
  4088. more formally using a type of token \code{INT} and its regular
  4089. expression \code{"-"? DIGIT+}.
  4090. The rule \code{exp: exp "+" exp} says that any string that matches
  4091. \code{exp}, followed by the \code{+} character, followed by another
  4092. string that matches \code{exp}, is itself an \code{exp}. For example,
  4093. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4094. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4095. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4096. \code{exp}. We can visualize the application of grammar rules to parse
  4097. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4098. internal node in the tree is an application of a grammar rule and is
  4099. labeled with its left-hand side nonterminal. Each leaf node is a
  4100. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4101. shown in figure~\ref{fig:simple-parse-tree}.
  4102. \begin{figure}[tbp]
  4103. \begin{tcolorbox}[colback=white]
  4104. \centering
  4105. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4106. \end{tcolorbox}
  4107. \caption{The parse tree for \lstinline{'1+3'}.}
  4108. \label{fig:simple-parse-tree}
  4109. \end{figure}
  4110. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4111. following parse tree as represented by \code{Tree} and \code{Token}
  4112. objects.
  4113. \begin{lstlisting}
  4114. Tree('lang_int',
  4115. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4116. Tree('exp', [Token('INT', '3')])])]),
  4117. Token('NEWLINE', '\n')])
  4118. \end{lstlisting}
  4119. The nodes that come from the lexer are \code{Token} objects, whereas
  4120. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4121. object has a \code{data} field containing the name of the nonterminal
  4122. for the grammar rule that was applied. Each \code{Tree} object also
  4123. has a \code{children} field that is a list containing trees and/or
  4124. tokens. Note that Lark does not produce nodes for string literals in
  4125. the grammar. For example, the \code{Tree} node for the addition
  4126. expression has only two children for the two integers but is missing
  4127. its middle child for the \code{"+"} terminal. This would be
  4128. problematic except that Lark provides a mechanism for customizing the
  4129. \code{data} field of each \code{Tree} node on the basis of which rule was
  4130. applied. Next to each alternative in a grammar rule, write \code{->}
  4131. followed by a string that you want to appear in the \code{data}
  4132. field. The following is a second draft of a Lark grammar for
  4133. \LangInt{}, this time with more specific labels on the \code{Tree}
  4134. nodes.
  4135. \begin{center}
  4136. \begin{minipage}{0.95\textwidth}
  4137. \begin{lstlisting}[escapechar=$]
  4138. exp: INT -> int
  4139. | "input_int" "(" ")" -> input_int
  4140. | "-" exp -> usub
  4141. | exp "+" exp -> add
  4142. | exp "-" exp -> sub
  4143. | "(" exp ")" -> paren
  4144. stmt: "print" "(" exp ")" -> print
  4145. | exp -> expr
  4146. stmt_list: -> empty_stmt
  4147. | stmt NEWLINE stmt_list -> add_stmt
  4148. lang_int: stmt_list -> module
  4149. \end{lstlisting}
  4150. \end{minipage}
  4151. \end{center}
  4152. Here is the resulting parse tree.
  4153. \begin{lstlisting}
  4154. Tree('module',
  4155. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4156. Tree('int', [Token('INT', '3')])])]),
  4157. Token('NEWLINE', '\n')])
  4158. \end{lstlisting}
  4159. \section{Ambiguous Grammars}
  4160. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4161. can be parsed in more than one way. For example, consider the string
  4162. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4163. our draft grammar, resulting in the two parse trees shown in
  4164. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4165. interpreting the second parse tree would yield \code{-4} even through
  4166. the correct answer is \code{2}.
  4167. \begin{figure}[tbp]
  4168. \begin{tcolorbox}[colback=white]
  4169. \centering
  4170. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4171. \end{tcolorbox}
  4172. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4173. \label{fig:ambig-parse-tree}
  4174. \end{figure}
  4175. To deal with this problem we can change the grammar by categorizing
  4176. the syntax in a more fine-grained fashion. In this case we want to
  4177. disallow the application of the rule \code{exp: exp "-" exp} when the
  4178. child on the right is an addition. To do this we can replace the
  4179. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4180. the expressions except for addition, as in the following.
  4181. \begin{center}
  4182. \begin{minipage}{0.95\textwidth}
  4183. \begin{lstlisting}[escapechar=$]
  4184. exp: exp "-" exp_no_add -> sub
  4185. | exp "+" exp -> add
  4186. | exp_no_add
  4187. exp_no_add: INT -> int
  4188. | "input_int" "(" ")" -> input_int
  4189. | "-" exp -> usub
  4190. | exp "-" exp_no_add -> sub
  4191. | "(" exp ")" -> paren
  4192. \end{lstlisting}
  4193. \end{minipage}
  4194. \end{center}
  4195. However, there remains some ambiguity in the grammar. For example, the
  4196. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4197. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4198. (incorrect). That is, subtraction is left associative. Likewise,
  4199. addition in Python is left associative. We also need to consider the
  4200. interaction of unary subtraction with both addition and
  4201. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4202. has higher \emph{precedence}\index{subject}{precedence} than addition
  4203. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4204. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4205. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4206. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4207. all the other expressions, and it uses \code{exp\_hi} for the second
  4208. child in the rules for addition and subtraction. Furthermore, unary
  4209. subtraction uses \code{exp\_hi} for its child.
  4210. For languages with more operators and more precedence levels, one must
  4211. refine the \code{exp} nonterminal into several nonterminals, one for
  4212. each precedence level.
  4213. \begin{figure}[tbp]
  4214. \begin{tcolorbox}[colback=white]
  4215. \centering
  4216. \begin{lstlisting}[escapechar=$]
  4217. exp: exp "+" exp_hi -> add
  4218. | exp "-" exp_hi -> sub
  4219. | exp_hi
  4220. exp_hi: INT -> int
  4221. | "input_int" "(" ")" -> input_int
  4222. | "-" exp_hi -> usub
  4223. | "(" exp ")" -> paren
  4224. stmt: "print" "(" exp ")" -> print
  4225. | exp -> expr
  4226. stmt_list: -> empty_stmt
  4227. | stmt NEWLINE stmt_list -> add_stmt
  4228. lang_int: stmt_list -> module
  4229. \end{lstlisting}
  4230. \end{tcolorbox}
  4231. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4232. \label{fig:Lint-lark-grammar}
  4233. \end{figure}
  4234. \section{From Parse Trees to Abstract Syntax Trees}
  4235. As we have seen, the output of a Lark parser is a parse tree, that is,
  4236. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4237. step is to convert the parse tree to an abstract syntax tree. This can
  4238. be accomplished with a recursive function that inspects the
  4239. \code{data} field of each node and then constructs the corresponding
  4240. AST node, using recursion to handle its children. The following is an
  4241. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4242. \begin{center}
  4243. \begin{minipage}{0.95\textwidth}
  4244. \begin{lstlisting}
  4245. def parse_tree_to_ast(e):
  4246. if e.data == 'int':
  4247. return Constant(int(e.children[0].value))
  4248. elif e.data == 'input_int':
  4249. return Call(Name('input_int'), [])
  4250. elif e.data == 'add':
  4251. e1, e2 = e.children
  4252. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4253. ...
  4254. else:
  4255. raise Exception('unhandled parse tree', e)
  4256. \end{lstlisting}
  4257. \end{minipage}
  4258. \end{center}
  4259. \begin{exercise}
  4260. \normalfont\normalsize
  4261. %
  4262. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4263. default parsing algorithm (Earley) with the \code{ambiguity} option
  4264. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4265. output will include multiple parse trees that will indicate to you
  4266. that there is a problem with your grammar. Your parser should ignore
  4267. white space, so we recommend using Lark's \code{\%ignore} directive
  4268. as follows.
  4269. \begin{lstlisting}
  4270. %import common.WS_INLINE
  4271. %ignore WS_INLINE
  4272. \end{lstlisting}
  4273. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4274. Lark parser instead of using the \code{parse} function from
  4275. the \code{ast} module. Test your compiler on all the \LangVar{}
  4276. programs that you have created, and create four additional programs
  4277. that test for ambiguities in your grammar.
  4278. \end{exercise}
  4279. \section{Earley's Algorithm}
  4280. \label{sec:earley}
  4281. In this section we discuss the parsing algorithm of
  4282. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4283. algorithm is powerful in that it can handle any context-free grammar,
  4284. which makes it easy to use, but it is not a particularly
  4285. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4286. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4287. the number of tokens in the input
  4288. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4289. learn about the LALR(1) algorithm, which is more efficient but cannot
  4290. handle all context-free grammars.
  4291. Earley's algorithm can be viewed as an interpreter; it treats the
  4292. grammar as the program being interpreted, and it treats the concrete
  4293. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4294. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4295. keep track of its progress and to store its results. The chart is an
  4296. array with one slot for each position in the input string, where
  4297. position $0$ is before the first character and position $n$ is
  4298. immediately after the last character. So, the array has length $n+1$
  4299. for an input string of length $n$. Each slot in the chart contains a
  4300. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4301. with a period indicating how much of its right-hand side has already
  4302. been parsed. For example, the dotted rule
  4303. \begin{lstlisting}
  4304. exp: exp "+" . exp_hi
  4305. \end{lstlisting}
  4306. represents a partial parse that has matched an \code{exp} followed by
  4307. \code{+} but has not yet parsed an \code{exp} to the right of
  4308. \code{+}.
  4309. %
  4310. Earley's algorithm starts with an initialization phase and then
  4311. repeats three actions---prediction, scanning, and completion---for as
  4312. long as opportunities arise. We demonstrate Earley's algorithm on a
  4313. running example, parsing the following program:
  4314. \begin{lstlisting}
  4315. print(1 + 3)
  4316. \end{lstlisting}
  4317. The algorithm's initialization phase creates dotted rules for all the
  4318. grammar rules whose left-hand side is the start symbol and places them
  4319. in slot $0$ of the chart. We also record the starting position of the
  4320. dotted rule in parentheses on the right. For example, given the
  4321. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4322. \begin{lstlisting}
  4323. lang_int: . stmt_list (0)
  4324. \end{lstlisting}
  4325. in slot $0$ of the chart. The algorithm then proceeds with
  4326. \emph{prediction} actions in which it adds more dotted rules to the
  4327. chart based on the nonterminals that come immediately after a period. In
  4328. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4329. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4330. period at the beginning of their right-hand sides, as follows:
  4331. \begin{lstlisting}
  4332. stmt_list: . (0)
  4333. stmt_list: . stmt NEWLINE stmt_list (0)
  4334. \end{lstlisting}
  4335. We continue to perform prediction actions as more opportunities
  4336. arise. For example, the \code{stmt} nonterminal now appears after a
  4337. period, so we add all the rules for \code{stmt}.
  4338. \begin{lstlisting}
  4339. stmt: . "print" "(" exp ")" (0)
  4340. stmt: . exp (0)
  4341. \end{lstlisting}
  4342. This reveals yet more opportunities for prediction, so we add the grammar
  4343. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4344. \begin{lstlisting}[escapechar=$]
  4345. exp: . exp "+" exp_hi (0)
  4346. exp: . exp "-" exp_hi (0)
  4347. exp: . exp_hi (0)
  4348. exp_hi: . INT (0)
  4349. exp_hi: . "input_int" "(" ")" (0)
  4350. exp_hi: . "-" exp_hi (0)
  4351. exp_hi: . "(" exp ")" (0)
  4352. \end{lstlisting}
  4353. We have exhausted the opportunities for prediction, so the algorithm
  4354. proceeds to \emph{scanning}, in which we inspect the next input token
  4355. and look for a dotted rule at the current position that has a matching
  4356. terminal immediately following the period. In our running example, the
  4357. first input token is \code{"print"}, so we identify the rule in slot
  4358. $0$ of the chart where \code{"print"} follows the period:
  4359. \begin{lstlisting}
  4360. stmt: . "print" "(" exp ")" (0)
  4361. \end{lstlisting}
  4362. We advance the period past \code{"print"} and add the resulting rule
  4363. to slot $1$:
  4364. \begin{lstlisting}
  4365. stmt: "print" . "(" exp ")" (0)
  4366. \end{lstlisting}
  4367. If the new dotted rule had a nonterminal after the period, we would
  4368. need to carry out a prediction action, adding more dotted rules to
  4369. slot $1$. That is not the case, so we continue scanning. The next
  4370. input token is \code{"("}, so we add the following to slot $2$ of the
  4371. chart.
  4372. \begin{lstlisting}
  4373. stmt: "print" "(" . exp ")" (0)
  4374. \end{lstlisting}
  4375. Now we have a nonterminal after the period, so we carry out several
  4376. prediction actions, adding dotted rules for \code{exp} and
  4377. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4378. starting position $2$.
  4379. \begin{lstlisting}[escapechar=$]
  4380. exp: . exp "+" exp_hi (2)
  4381. exp: . exp "-" exp_hi (2)
  4382. exp: . exp_hi (2)
  4383. exp_hi: . INT (2)
  4384. exp_hi: . "input_int" "(" ")" (2)
  4385. exp_hi: . "-" exp_hi (2)
  4386. exp_hi: . "(" exp ")" (2)
  4387. \end{lstlisting}
  4388. With this prediction complete, we return to scanning, noting that the
  4389. next input token is \code{"1"}, which the lexer parses as an
  4390. \code{INT}. There is a matching rule in slot $2$:
  4391. \begin{lstlisting}
  4392. exp_hi: . INT (2)
  4393. \end{lstlisting}
  4394. so we advance the period and put the following rule into slot $3$.
  4395. \begin{lstlisting}
  4396. exp_hi: INT . (2)
  4397. \end{lstlisting}
  4398. This brings us to \emph{completion} actions. When the period reaches
  4399. the end of a dotted rule, we recognize that the substring
  4400. has matched the nonterminal on the left-hand side of the rule, in this case
  4401. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4402. rules into slot $2$ (the starting position for the finished rule) if
  4403. the period is immediately followed by \code{exp\_hi}. So we identify
  4404. \begin{lstlisting}
  4405. exp: . exp_hi (2)
  4406. \end{lstlisting}
  4407. and add the following dotted rule to slot $3$
  4408. \begin{lstlisting}
  4409. exp: exp_hi . (2)
  4410. \end{lstlisting}
  4411. This triggers another completion step for the nonterminal \code{exp},
  4412. adding two more dotted rules to slot $3$.
  4413. \begin{lstlisting}[escapechar=$]
  4414. exp: exp . "+" exp_hi (2)
  4415. exp: exp . "-" exp_hi (2)
  4416. \end{lstlisting}
  4417. Returning to scanning, the next input token is \code{"+"}, so
  4418. we add the following to slot $4$.
  4419. \begin{lstlisting}[escapechar=$]
  4420. exp: exp "+" . exp_hi (2)
  4421. \end{lstlisting}
  4422. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4423. the following dotted rules to slot $4$ of the chart.
  4424. \begin{lstlisting}[escapechar=$]
  4425. exp_hi: . INT (4)
  4426. exp_hi: . "input_int" "(" ")" (4)
  4427. exp_hi: . "-" exp_hi (4)
  4428. exp_hi: . "(" exp ")" (4)
  4429. \end{lstlisting}
  4430. The next input token is \code{"3"} which the lexer categorized as an
  4431. \code{INT}, so we advance the period past \code{INT} for the rules in
  4432. slot $4$, of which there is just one, and put the following into slot $5$.
  4433. \begin{lstlisting}[escapechar=$]
  4434. exp_hi: INT . (4)
  4435. \end{lstlisting}
  4436. The period at the end of the rule triggers a completion action for the
  4437. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4438. So we advance the period and put the following into slot $5$.
  4439. \begin{lstlisting}[escapechar=$]
  4440. exp: exp "+" exp_hi . (2)
  4441. \end{lstlisting}
  4442. This triggers another completion action for the rules in slot $2$ that
  4443. have a period before \code{exp}.
  4444. \begin{lstlisting}[escapechar=$]
  4445. stmt: "print" "(" exp . ")" (0)
  4446. exp: exp . "+" exp_hi (2)
  4447. exp: exp . "-" exp_hi (2)
  4448. \end{lstlisting}
  4449. We scan the next input token \code{")"}, placing the following dotted
  4450. rule into slot $6$.
  4451. \begin{lstlisting}[escapechar=$]
  4452. stmt: "print" "(" exp ")" . (0)
  4453. \end{lstlisting}
  4454. This triggers the completion of \code{stmt} in slot $0$
  4455. \begin{lstlisting}
  4456. stmt_list: stmt . NEWLINE stmt_list (0)
  4457. \end{lstlisting}
  4458. The last input token is a \code{NEWLINE}, so we advance the period
  4459. and place the new dotted rule into slot $7$.
  4460. \begin{lstlisting}
  4461. stmt_list: stmt NEWLINE . stmt_list (0)
  4462. \end{lstlisting}
  4463. We are close to the end of parsing the input!
  4464. The period is before the \code{stmt\_list} nonterminal, so we
  4465. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4466. \begin{lstlisting}
  4467. stmt_list: . (7)
  4468. stmt_list: . stmt NEWLINE stmt_list (7)
  4469. stmt: . "print" "(" exp ")" (7)
  4470. stmt: . exp (7)
  4471. \end{lstlisting}
  4472. There is immediately an opportunity for completion of \code{stmt\_list},
  4473. so we add the following to slot $7$.
  4474. \begin{lstlisting}
  4475. stmt_list: stmt NEWLINE stmt_list . (0)
  4476. \end{lstlisting}
  4477. This triggers another completion action for \code{stmt\_list} in slot $0$
  4478. \begin{lstlisting}
  4479. lang_int: stmt_list . (0)
  4480. \end{lstlisting}
  4481. which in turn completes \code{lang\_int}, the start symbol of the
  4482. grammar, so the parsing of the input is complete.
  4483. For reference, we give a general description of Earley's
  4484. algorithm.
  4485. \begin{enumerate}
  4486. \item The algorithm begins by initializing slot $0$ of the chart with the
  4487. grammar rule for the start symbol, placing a period at the beginning
  4488. of the right-hand side, and recording its starting position as $0$.
  4489. \item The algorithm repeatedly applies the following three kinds of
  4490. actions for as long as there are opportunities to do so.
  4491. \begin{itemize}
  4492. \item Prediction: If there is a rule in slot $k$ whose period comes
  4493. before a nonterminal, add the rules for that nonterminal into slot
  4494. $k$, placing a period at the beginning of their right-hand sides
  4495. and recording their starting position as $k$.
  4496. \item Scanning: If the token at position $k$ of the input string
  4497. matches the symbol after the period in a dotted rule in slot $k$
  4498. of the chart, advance the period in the dotted rule, adding
  4499. the result to slot $k+1$.
  4500. \item Completion: If a dotted rule in slot $k$ has a period at the
  4501. end, inspect the rules in the slot corresponding to the starting
  4502. position of the completed rule. If any of those rules have a
  4503. nonterminal following their period that matches the left-hand side
  4504. of the completed rule, then advance their period, placing the new
  4505. dotted rule in slot $k$.
  4506. \end{itemize}
  4507. While repeating these three actions, take care never to add
  4508. duplicate dotted rules to the chart.
  4509. \end{enumerate}
  4510. We have described how Earley's algorithm recognizes that an input
  4511. string matches a grammar, but we have not described how it builds a
  4512. parse tree. The basic idea is simple, but building parse trees in an
  4513. efficient way is more complex, requiring a data structure called a
  4514. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4515. to attach a partial parse tree to every dotted rule in the chart.
  4516. Initially, the node associated with a dotted rule has no
  4517. children. As the period moves to the right, the nodes from the
  4518. subparses are added as children to the node.
  4519. As mentioned at the beginning of this section, Earley's algorithm is
  4520. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4521. files that contain thousands of tokens in a reasonable amount of time,
  4522. but not millions.
  4523. %
  4524. In the next section we discuss the LALR(1) parsing algorithm, which is
  4525. efficient enough to use with even the largest of input files.
  4526. \section{The LALR(1) Algorithm}
  4527. \label{sec:lalr}
  4528. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4529. two-phase approach in which it first compiles the grammar into a state
  4530. machine and then runs the state machine to parse an input string. The
  4531. second phase has time complexity $O(n)$ where $n$ is the number of
  4532. tokens in the input, so LALR(1) is the best one could hope for with
  4533. respect to efficiency.
  4534. %
  4535. A particularly influential implementation of LALR(1) is the
  4536. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4537. \texttt{yacc} stands for ``yet another compiler compiler.''
  4538. %
  4539. The LALR(1) state machine uses a stack to record its progress in
  4540. parsing the input string. Each element of the stack is a pair: a
  4541. state number and a grammar symbol (a terminal or a nonterminal). The
  4542. symbol characterizes the input that has been parsed so far, and the
  4543. state number is used to remember how to proceed once the next
  4544. symbol's worth of input has been parsed. Each state in the machine
  4545. represents where the parser stands in the parsing process with respect
  4546. to certain grammar rules. In particular, each state is associated with
  4547. a set of dotted rules.
  4548. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4549. (also called parse table) for the following simple but ambiguous
  4550. grammar:
  4551. \begin{lstlisting}[escapechar=$]
  4552. exp: INT
  4553. | exp "+" exp
  4554. stmt: "print" exp
  4555. start: stmt
  4556. \end{lstlisting}
  4557. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4558. read in a \lstinline{"print"} token, so the top of the stack is
  4559. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4560. the input according to grammar rule 1, which is signified by showing
  4561. rule 1 with a period after the \code{"print"} token and before the
  4562. \code{exp} nonterminal. There are two rules that could apply next,
  4563. rules 2 and 3, so state 1 also shows those rules with a period at
  4564. the beginning of their right-hand sides. The edges between states
  4565. indicate which transitions the machine should make depending on the
  4566. next input token. So, for example, if the next input token is
  4567. \code{INT} then the parser will push \code{INT} and the target state 4
  4568. on the stack and transition to state 4. Suppose that we are now at the end
  4569. of the input. State 4 says that we should reduce by rule 3, so we pop
  4570. from the stack the same number of items as the number of symbols in
  4571. the right-hand side of the rule, in this case just one. We then
  4572. momentarily jump to the state at the top of the stack (state 1) and
  4573. then follow the goto edge that corresponds to the left-hand side of
  4574. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4575. state 3. (A slightly longer example parse is shown in
  4576. figure~\ref{fig:shift-reduce}.)
  4577. \begin{figure}[tbp]
  4578. \centering
  4579. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4580. \caption{An LALR(1) parse table and a trace of an example run.}
  4581. \label{fig:shift-reduce}
  4582. \end{figure}
  4583. In general, the algorithm works as follows. First, set the current state to
  4584. state $0$. Then repeat the following, looking at the next input token.
  4585. \begin{itemize}
  4586. \item If there there is a shift edge for the input token in the
  4587. current state, push the edge's target state and the input token onto
  4588. the stack and proceed to the edge's target state.
  4589. \item If there is a reduce action for the input token in the current
  4590. state, pop $k$ elements from the stack, where $k$ is the number of
  4591. symbols in the right-hand side of the rule being reduced. Jump to
  4592. the state at the top of the stack and then follow the goto edge for
  4593. the nonterminal that matches the left-hand side of the rule that we
  4594. are reducing by. Push the edge's target state and the nonterminal on the
  4595. stack.
  4596. \end{itemize}
  4597. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4598. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4599. algorithm does not know which action to take in this case. When a
  4600. state has both a shift and a reduce action for the same token, we say
  4601. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4602. will arise, for example, in trying to parse the input
  4603. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4604. the parser will be in state 6 and will not know whether to
  4605. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4606. to proceed by shifting the next \lstinline{+} from the input.
  4607. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4608. arises when there are two reduce actions in a state for the same
  4609. token. To understand which grammars give rise to shift/reduce and
  4610. reduce/reduce conflicts, it helps to know how the parse table is
  4611. generated from the grammar, which we discuss next.
  4612. The parse table is generated one state at a time. State 0 represents
  4613. the start of the parser. We add the grammar rule for the start symbol
  4614. to this state with a period at the beginning of the right-hand side,
  4615. similarly to the initialization phase of the Earley parser. If the
  4616. period appears immediately before another nonterminal, we add all the
  4617. rules with that nonterminal on the left-hand side. Again, we place a
  4618. period at the beginning of the right-hand side of each new
  4619. rule. This process, called \emph{state closure}, is continued
  4620. until there are no more rules to add (similarly to the prediction
  4621. actions of an Earley parser). We then examine each dotted rule in the
  4622. current state $I$. Suppose that a dotted rule has the form $A ::=
  4623. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4624. are sequences of symbols. We create a new state and call it $J$. If $X$
  4625. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4626. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4627. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4628. state $J$. We start by adding all dotted rules from state $I$ that
  4629. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4630. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4631. the period moved past the $X$. (This is analogous to completion in
  4632. Earley's algorithm.) We then perform state closure on $J$. This
  4633. process repeats until there are no more states or edges to add.
  4634. We then mark states as accepting states if they have a dotted rule
  4635. that is the start rule with a period at the end. Also, to add
  4636. the reduce actions, we look for any state containing a dotted rule
  4637. with a period at the end. Let $n$ be the rule number for this dotted
  4638. rule. We then put a reduce $n$ action into that state for every token
  4639. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4640. dotted rule with a period at the end. We therefore put a reduce by
  4641. rule 3 action into state 4 for every
  4642. token.
  4643. When inserting reduce actions, take care to spot any shift/reduce or
  4644. reduce/reduce conflicts. If there are any, abort the construction of
  4645. the parse table.
  4646. \begin{exercise}
  4647. \normalfont\normalsize
  4648. %
  4649. Working on paper, walk through the parse table generation process for
  4650. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4651. your results against the parse table shown in
  4652. figure~\ref{fig:shift-reduce}.
  4653. \end{exercise}
  4654. \begin{exercise}
  4655. \normalfont\normalsize
  4656. %
  4657. Change the parser in your compiler for \LangVar{} to set the
  4658. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4659. all the \LangVar{} programs that you have created. In doing so, Lark
  4660. may signal an error due to shift/reduce or reduce/reduce conflicts
  4661. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4662. remove those conflicts.
  4663. \end{exercise}
  4664. \section{Further Reading}
  4665. In this chapter we have just scratched the surface of the field of
  4666. parsing, with the study of a very general but less efficient algorithm
  4667. (Earley) and with a more limited but highly efficient algorithm
  4668. (LALR). There are many more algorithms and classes of grammars that
  4669. fall between these two ends of the spectrum. We recommend to the reader
  4670. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4671. Regarding lexical analysis, we have described the specification
  4672. language, which are the regular expressions, but not the algorithms
  4673. for recognizing them. In short, regular expressions can be translated
  4674. to nondeterministic finite automata, which in turn are translated to
  4675. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4676. all the details on lexical analysis.
  4677. \fi}
  4678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4679. \chapter{Register Allocation}
  4680. \label{ch:register-allocation-Lvar}
  4681. \setcounter{footnote}{0}
  4682. \index{subject}{register allocation}
  4683. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4684. storing variables on the procedure call stack. The CPU may require tens
  4685. to hundreds of cycles to access a location on the stack, whereas
  4686. accessing a register takes only a single cycle. In this chapter we
  4687. improve the efficiency of our generated code by storing some variables
  4688. in registers. The goal of register allocation is to fit as many
  4689. variables into registers as possible. Some programs have more
  4690. variables than registers, so we cannot always map each variable to a
  4691. different register. Fortunately, it is common for different variables
  4692. to be in use during different periods of time during program
  4693. execution, and in those cases we can map multiple variables to the
  4694. same register.
  4695. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4696. example. The source program is on the left and the output of
  4697. instruction selection\index{subject}{instruction selection}
  4698. is on the right. The program is almost
  4699. completely in the x86 assembly language, but it still uses variables.
  4700. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4701. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4702. the other hand, is used only after this point, so \code{x} and
  4703. \code{z} could share the same register.
  4704. \begin{figure}
  4705. \begin{tcolorbox}[colback=white]
  4706. \begin{minipage}{0.45\textwidth}
  4707. Example \LangVar{} program:
  4708. % var_test_28.rkt
  4709. {\if\edition\racketEd
  4710. \begin{lstlisting}
  4711. (let ([v 1])
  4712. (let ([w 42])
  4713. (let ([x (+ v 7)])
  4714. (let ([y x])
  4715. (let ([z (+ x w)])
  4716. (+ z (- y)))))))
  4717. \end{lstlisting}
  4718. \fi}
  4719. {\if\edition\pythonEd\pythonColor
  4720. \begin{lstlisting}
  4721. v = 1
  4722. w = 42
  4723. x = v + 7
  4724. y = x
  4725. z = x + w
  4726. print(z + (- y))
  4727. \end{lstlisting}
  4728. \fi}
  4729. \end{minipage}
  4730. \begin{minipage}{0.45\textwidth}
  4731. After instruction selection:
  4732. {\if\edition\racketEd
  4733. \begin{lstlisting}
  4734. locals-types:
  4735. x : Integer, y : Integer,
  4736. z : Integer, t : Integer,
  4737. v : Integer, w : Integer
  4738. start:
  4739. movq $1, v
  4740. movq $42, w
  4741. movq v, x
  4742. addq $7, x
  4743. movq x, y
  4744. movq x, z
  4745. addq w, z
  4746. movq y, t
  4747. negq t
  4748. movq z, %rax
  4749. addq t, %rax
  4750. jmp conclusion
  4751. \end{lstlisting}
  4752. \fi}
  4753. {\if\edition\pythonEd\pythonColor
  4754. \begin{lstlisting}
  4755. movq $1, v
  4756. movq $42, w
  4757. movq v, x
  4758. addq $7, x
  4759. movq x, y
  4760. movq x, z
  4761. addq w, z
  4762. movq y, tmp_0
  4763. negq tmp_0
  4764. movq z, tmp_1
  4765. addq tmp_0, tmp_1
  4766. movq tmp_1, %rdi
  4767. callq print_int
  4768. \end{lstlisting}
  4769. \fi}
  4770. \end{minipage}
  4771. \end{tcolorbox}
  4772. \caption{A running example for register allocation.}
  4773. \label{fig:reg-eg}
  4774. \end{figure}
  4775. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4776. compute where a variable is in use. Once we have that information, we
  4777. compute which variables are in use at the same time, that is, which ones
  4778. \emph{interfere}\index{subject}{interfere} with each other, and
  4779. represent this relation as an undirected graph whose vertices are
  4780. variables and edges indicate when two variables interfere
  4781. (section~\ref{sec:build-interference}). We then model register
  4782. allocation as a graph coloring problem
  4783. (section~\ref{sec:graph-coloring}).
  4784. If we run out of registers despite these efforts, we place the
  4785. remaining variables on the stack, similarly to how we handled
  4786. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4787. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4788. location. The decision to spill a variable is handled as part of the
  4789. graph coloring process.
  4790. We make the simplifying assumption that each variable is assigned to
  4791. one location (a register or stack address). A more sophisticated
  4792. approach is to assign a variable to one or more locations in different
  4793. regions of the program. For example, if a variable is used many times
  4794. in short sequence and then used again only after many other
  4795. instructions, it could be more efficient to assign the variable to a
  4796. register during the initial sequence and then move it to the stack for
  4797. the rest of its lifetime. We refer the interested reader to
  4798. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4799. approach.
  4800. % discuss prioritizing variables based on how much they are used.
  4801. \section{Registers and Calling Conventions}
  4802. \label{sec:calling-conventions}
  4803. \index{subject}{calling conventions}
  4804. As we perform register allocation, we must be aware of the
  4805. \emph{calling conventions} \index{subject}{calling conventions} that
  4806. govern how function calls are performed in x86.
  4807. %
  4808. Even though \LangVar{} does not include programmer-defined functions,
  4809. our generated code includes a \code{main} function that is called by
  4810. the operating system and our generated code contains calls to the
  4811. \code{read\_int} function.
  4812. Function calls require coordination between two pieces of code that
  4813. may be written by different programmers or generated by different
  4814. compilers. Here we follow the System V calling conventions that are
  4815. used by the GNU C compiler on Linux and
  4816. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4817. %
  4818. The calling conventions include rules about how functions share the
  4819. use of registers. In particular, the caller is responsible for freeing
  4820. some registers prior to the function call for use by the callee.
  4821. These are called the \emph{caller-saved registers}
  4822. \index{subject}{caller-saved registers}
  4823. and they are
  4824. \begin{lstlisting}
  4825. rax rcx rdx rsi rdi r8 r9 r10 r11
  4826. \end{lstlisting}
  4827. On the other hand, the callee is responsible for preserving the values
  4828. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4829. which are
  4830. \begin{lstlisting}
  4831. rsp rbp rbx r12 r13 r14 r15
  4832. \end{lstlisting}
  4833. We can think about this caller/callee convention from two points of
  4834. view, the caller view and the callee view, as follows:
  4835. \begin{itemize}
  4836. \item The caller should assume that all the caller-saved registers get
  4837. overwritten with arbitrary values by the callee. On the other hand,
  4838. the caller can safely assume that all the callee-saved registers
  4839. retain their original values.
  4840. \item The callee can freely use any of the caller-saved registers.
  4841. However, if the callee wants to use a callee-saved register, the
  4842. callee must arrange to put the original value back in the register
  4843. prior to returning to the caller. This can be accomplished by saving
  4844. the value to the stack in the prelude of the function and restoring
  4845. the value in the conclusion of the function.
  4846. \end{itemize}
  4847. In x86, registers are also used for passing arguments to a function
  4848. and for the return value. In particular, the first six arguments of a
  4849. function are passed in the following six registers, in this order.
  4850. \begin{lstlisting}
  4851. rdi rsi rdx rcx r8 r9
  4852. \end{lstlisting}
  4853. We refer to these six registers are the argument-passing registers
  4854. \index{subject}{argument-passing registers}.
  4855. If there are more than six arguments, the convention is to use space
  4856. on the frame of the caller for the rest of the arguments. In
  4857. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4858. argument and the rest of the arguments, which simplifies the treatment
  4859. of efficient tail calls.
  4860. %
  4861. \racket{For now, the only function we care about is \code{read\_int},
  4862. which takes zero arguments.}
  4863. %
  4864. \python{For now, the only functions we care about are \code{read\_int}
  4865. and \code{print\_int}, which take zero and one argument, respectively.}
  4866. %
  4867. The register \code{rax} is used for the return value of a function.
  4868. The next question is how these calling conventions impact register
  4869. allocation. Consider the \LangVar{} program presented in
  4870. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4871. example from the caller point of view and then from the callee point
  4872. of view. We refer to a variable that is in use during a function call
  4873. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4874. The program makes two calls to \READOP{}. The variable \code{x} is
  4875. call-live because it is in use during the second call to \READOP{}; we
  4876. must ensure that the value in \code{x} does not get overwritten during
  4877. the call to \READOP{}. One obvious approach is to save all the values
  4878. that reside in caller-saved registers to the stack prior to each
  4879. function call and to restore them after each call. That way, if the
  4880. register allocator chooses to assign \code{x} to a caller-saved
  4881. register, its value will be preserved across the call to \READOP{}.
  4882. However, saving and restoring to the stack is relatively slow. If
  4883. \code{x} is not used many times, it may be better to assign \code{x}
  4884. to a stack location in the first place. Or better yet, if we can
  4885. arrange for \code{x} to be placed in a callee-saved register, then it
  4886. won't need to be saved and restored during function calls.
  4887. We recommend an approach that captures these issues in the
  4888. interference graph, without complicating the graph coloring algorithm.
  4889. During liveness analysis we know which variables are call-live because
  4890. we compute which variables are in use at every instruction
  4891. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4892. interference graph (section~\ref{sec:build-interference}), we can
  4893. place an edge in the interference graph between each call-live
  4894. variable and the caller-saved registers. This will prevent the graph
  4895. coloring algorithm from assigning call-live variables to caller-saved
  4896. registers.
  4897. On the other hand, for variables that are not call-live, we prefer
  4898. placing them in caller-saved registers to leave more room for
  4899. call-live variables in the callee-saved registers. This can also be
  4900. implemented without complicating the graph coloring algorithm. We
  4901. recommend that the graph coloring algorithm assign variables to
  4902. natural numbers, choosing the lowest number for which there is no
  4903. interference. After the coloring is complete, we map the numbers to
  4904. registers and stack locations: mapping the lowest numbers to
  4905. caller-saved registers, the next lowest to callee-saved registers, and
  4906. the largest numbers to stack locations. This ordering gives preference
  4907. to registers over stack locations and to caller-saved registers over
  4908. callee-saved registers.
  4909. Returning to the example in
  4910. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4911. generated x86 code on the right-hand side. Variable \code{x} is
  4912. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4913. in a safe place during the second call to \code{read\_int}. Next,
  4914. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4915. because \code{y} is not a call-live variable.
  4916. We have completed the analysis from the caller point of view, so now
  4917. we switch to the callee point of view, focusing on the prelude and
  4918. conclusion of the \code{main} function. As usual, the prelude begins
  4919. with saving the \code{rbp} register to the stack and setting the
  4920. \code{rbp} to the current stack pointer. We now know why it is
  4921. necessary to save the \code{rbp}: it is a callee-saved register. The
  4922. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4923. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4924. (\code{x}). The other callee-saved registers are not saved in the
  4925. prelude because they are not used. The prelude subtracts 8 bytes from
  4926. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4927. conclusion, we see that \code{rbx} is restored from the stack with a
  4928. \code{popq} instruction.
  4929. \index{subject}{prelude}\index{subject}{conclusion}
  4930. \begin{figure}[tp]
  4931. \begin{tcolorbox}[colback=white]
  4932. \begin{minipage}{0.45\textwidth}
  4933. Example \LangVar{} program:
  4934. %var_test_14.rkt
  4935. {\if\edition\racketEd
  4936. \begin{lstlisting}
  4937. (let ([x (read)])
  4938. (let ([y (read)])
  4939. (+ (+ x y) 42)))
  4940. \end{lstlisting}
  4941. \fi}
  4942. {\if\edition\pythonEd\pythonColor
  4943. \begin{lstlisting}
  4944. x = input_int()
  4945. y = input_int()
  4946. print((x + y) + 42)
  4947. \end{lstlisting}
  4948. \fi}
  4949. \end{minipage}
  4950. \begin{minipage}{0.45\textwidth}
  4951. Generated x86 assembly:
  4952. {\if\edition\racketEd
  4953. \begin{lstlisting}
  4954. start:
  4955. callq read_int
  4956. movq %rax, %rbx
  4957. callq read_int
  4958. movq %rax, %rcx
  4959. addq %rcx, %rbx
  4960. movq %rbx, %rax
  4961. addq $42, %rax
  4962. jmp conclusion
  4963. .globl main
  4964. main:
  4965. pushq %rbp
  4966. movq %rsp, %rbp
  4967. pushq %rbx
  4968. subq $8, %rsp
  4969. jmp start
  4970. conclusion:
  4971. addq $8, %rsp
  4972. popq %rbx
  4973. popq %rbp
  4974. retq
  4975. \end{lstlisting}
  4976. \fi}
  4977. {\if\edition\pythonEd\pythonColor
  4978. \begin{lstlisting}
  4979. .globl main
  4980. main:
  4981. pushq %rbp
  4982. movq %rsp, %rbp
  4983. pushq %rbx
  4984. subq $8, %rsp
  4985. callq read_int
  4986. movq %rax, %rbx
  4987. callq read_int
  4988. movq %rax, %rcx
  4989. movq %rbx, %rdx
  4990. addq %rcx, %rdx
  4991. movq %rdx, %rcx
  4992. addq $42, %rcx
  4993. movq %rcx, %rdi
  4994. callq print_int
  4995. addq $8, %rsp
  4996. popq %rbx
  4997. popq %rbp
  4998. retq
  4999. \end{lstlisting}
  5000. \fi}
  5001. \end{minipage}
  5002. \end{tcolorbox}
  5003. \caption{An example with function calls.}
  5004. \label{fig:example-calling-conventions}
  5005. \end{figure}
  5006. %\clearpage
  5007. \section{Liveness Analysis}
  5008. \label{sec:liveness-analysis-Lvar}
  5009. \index{subject}{liveness analysis}
  5010. The \code{uncover\_live} \racket{pass}\python{function} performs
  5011. \emph{liveness analysis}; that is, it discovers which variables are
  5012. in use in different regions of a program.
  5013. %
  5014. A variable or register is \emph{live} at a program point if its
  5015. current value is used at some later point in the program. We refer to
  5016. variables, stack locations, and registers collectively as
  5017. \emph{locations}.
  5018. %
  5019. Consider the following code fragment in which there are two writes to
  5020. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5021. time?
  5022. \begin{center}
  5023. \begin{minipage}{0.85\textwidth}
  5024. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5025. movq $5, a
  5026. movq $30, b
  5027. movq a, c
  5028. movq $10, b
  5029. addq b, c
  5030. \end{lstlisting}
  5031. \end{minipage}
  5032. \end{center}
  5033. The answer is no, because \code{a} is live from line 1 to 3 and
  5034. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5035. line 2 is never used because it is overwritten (line 4) before the
  5036. next read (line 5).
  5037. The live locations for each instruction can be computed by traversing
  5038. the instruction sequence back to front (i.e., backward in execution
  5039. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5040. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5041. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5042. locations before instruction $I_k$. \racket{We recommend representing
  5043. these sets with the Racket \code{set} data structure described in
  5044. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5045. with the Python
  5046. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5047. data structure.}
  5048. {\if\edition\racketEd
  5049. \begin{figure}[tp]
  5050. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5051. \small
  5052. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5053. A \emph{set} is an unordered collection of elements without duplicates.
  5054. Here are some of the operations defined on sets.
  5055. \index{subject}{set}
  5056. \begin{description}
  5057. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5058. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5059. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5060. difference of the two sets.
  5061. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5062. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5063. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5064. \end{description}
  5065. \end{tcolorbox}
  5066. %\end{wrapfigure}
  5067. \caption{The \code{set} data structure.}
  5068. \label{fig:set}
  5069. \end{figure}
  5070. \fi}
  5071. % TODO: add a python version of the reference box for sets. -Jeremy
  5072. The locations that are live after an instruction are its
  5073. \emph{live-after}\index{subject}{live-after} set, and the locations
  5074. that are live before an instruction are its
  5075. \emph{live-before}\index{subject}{live-before} set. The live-after
  5076. set of an instruction is always the same as the live-before set of the
  5077. next instruction.
  5078. \begin{equation} \label{eq:live-after-before-next}
  5079. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5080. \end{equation}
  5081. To start things off, there are no live locations after the last
  5082. instruction, so
  5083. \begin{equation}\label{eq:live-last-empty}
  5084. L_{\mathsf{after}}(n) = \emptyset
  5085. \end{equation}
  5086. We then apply the following rule repeatedly, traversing the
  5087. instruction sequence back to front.
  5088. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5089. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5090. \end{equation}
  5091. where $W(k)$ are the locations written to by instruction $I_k$, and
  5092. $R(k)$ are the locations read by instruction $I_k$.
  5093. {\if\edition\racketEd
  5094. %
  5095. There is a special case for \code{jmp} instructions. The locations
  5096. that are live before a \code{jmp} should be the locations in
  5097. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5098. maintaining an alist named \code{label->live} that maps each label to
  5099. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5100. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5101. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5102. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5103. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5104. %
  5105. \fi}
  5106. Let us walk through the previous example, applying these formulas
  5107. starting with the instruction on line 5 of the code fragment. We
  5108. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5109. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5110. $\emptyset$ because it is the last instruction
  5111. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5112. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5113. variables \code{b} and \code{c}
  5114. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5115. \[
  5116. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5117. \]
  5118. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5119. the live-before set from line 5 to be the live-after set for this
  5120. instruction (formula~\eqref{eq:live-after-before-next}).
  5121. \[
  5122. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5123. \]
  5124. This move instruction writes to \code{b} and does not read from any
  5125. variables, so we have the following live-before set
  5126. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5127. \[
  5128. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5129. \]
  5130. The live-before for instruction \code{movq a, c}
  5131. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5132. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5133. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5134. variable that is not live and does not read from a variable.
  5135. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5136. because it writes to variable \code{a}.
  5137. \begin{figure}[tbp]
  5138. \centering
  5139. \begin{tcolorbox}[colback=white]
  5140. \hspace{10pt}
  5141. \begin{minipage}{0.4\textwidth}
  5142. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5143. movq $5, a
  5144. movq $30, b
  5145. movq a, c
  5146. movq $10, b
  5147. addq b, c
  5148. \end{lstlisting}
  5149. \end{minipage}
  5150. \vrule\hspace{10pt}
  5151. \begin{minipage}{0.45\textwidth}
  5152. \begin{align*}
  5153. L_{\mathsf{before}}(1)= \emptyset,
  5154. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5155. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5156. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5157. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5158. L_{\mathsf{after}}(3)= \{\ttm{c}\}\\
  5159. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5160. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5161. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5162. L_{\mathsf{after}}(5)= \emptyset
  5163. \end{align*}
  5164. \end{minipage}
  5165. \end{tcolorbox}
  5166. \caption{Example output of liveness analysis on a short example.}
  5167. \label{fig:liveness-example-0}
  5168. \end{figure}
  5169. \begin{exercise}\normalfont\normalsize
  5170. Perform liveness analysis by hand on the running example in
  5171. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5172. sets for each instruction. Compare your answers to the solution
  5173. shown in figure~\ref{fig:live-eg}.
  5174. \end{exercise}
  5175. \begin{figure}[tp]
  5176. \hspace{20pt}
  5177. \begin{minipage}{0.55\textwidth}
  5178. \begin{tcolorbox}[colback=white]
  5179. {\if\edition\racketEd
  5180. \begin{lstlisting}
  5181. |$\{\ttm{rsp}\}$|
  5182. movq $1, v
  5183. |$\{\ttm{v},\ttm{rsp}\}$|
  5184. movq $42, w
  5185. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5186. movq v, x
  5187. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5188. addq $7, x
  5189. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5190. movq x, y
  5191. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5192. movq x, z
  5193. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5194. addq w, z
  5195. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5196. movq y, t
  5197. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5198. negq t
  5199. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5200. movq z, %rax
  5201. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5202. addq t, %rax
  5203. |$\{\ttm{rax},\ttm{rsp}\}$|
  5204. jmp conclusion
  5205. \end{lstlisting}
  5206. \fi}
  5207. {\if\edition\pythonEd\pythonColor
  5208. \begin{lstlisting}
  5209. movq $1, v
  5210. |$\{\ttm{v}\}$|
  5211. movq $42, w
  5212. |$\{\ttm{w}, \ttm{v}\}$|
  5213. movq v, x
  5214. |$\{\ttm{w}, \ttm{x}\}$|
  5215. addq $7, x
  5216. |$\{\ttm{w}, \ttm{x}\}$|
  5217. movq x, y
  5218. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5219. movq x, z
  5220. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5221. addq w, z
  5222. |$\{\ttm{y}, \ttm{z}\}$|
  5223. movq y, tmp_0
  5224. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5225. negq tmp_0
  5226. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5227. movq z, tmp_1
  5228. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5229. addq tmp_0, tmp_1
  5230. |$\{\ttm{tmp\_1}\}$|
  5231. movq tmp_1, %rdi
  5232. |$\{\ttm{rdi}\}$|
  5233. callq print_int
  5234. |$\{\}$|
  5235. \end{lstlisting}
  5236. \fi}
  5237. \end{tcolorbox}
  5238. \end{minipage}
  5239. \caption{The running example annotated with live-after sets.}
  5240. \label{fig:live-eg}
  5241. \end{figure}
  5242. \begin{exercise}\normalfont\normalsize
  5243. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5244. %
  5245. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5246. field of the \code{Block} structure.}
  5247. %
  5248. \python{Return a dictionary that maps each instruction to its
  5249. live-after set.}
  5250. %
  5251. \racket{We recommend creating an auxiliary function that takes a list
  5252. of instructions and an initial live-after set (typically empty) and
  5253. returns the list of live-after sets.}
  5254. %
  5255. We recommend creating auxiliary functions to (1) compute the set
  5256. of locations that appear in an \Arg{}, (2) compute the locations read
  5257. by an instruction (the $R$ function), and (3) the locations written by
  5258. an instruction (the $W$ function). The \code{callq} instruction should
  5259. include all the caller-saved registers in its write set $W$ because
  5260. the calling convention says that those registers may be written to
  5261. during the function call. Likewise, the \code{callq} instruction
  5262. should include the appropriate argument-passing registers in its
  5263. read set $R$, depending on the arity of the function being
  5264. called. (This is why the abstract syntax for \code{callq} includes the
  5265. arity.)
  5266. \end{exercise}
  5267. %\clearpage
  5268. \section{Build the Interference Graph}
  5269. \label{sec:build-interference}
  5270. {\if\edition\racketEd
  5271. \begin{figure}[tp]
  5272. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5273. \small
  5274. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5275. A \emph{graph} is a collection of vertices and edges where each
  5276. edge connects two vertices. A graph is \emph{directed} if each
  5277. edge points from a source to a target. Otherwise the graph is
  5278. \emph{undirected}.
  5279. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5280. \begin{description}
  5281. %% We currently don't use directed graphs. We instead use
  5282. %% directed multi-graphs. -Jeremy
  5283. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5284. directed graph from a list of edges. Each edge is a list
  5285. containing the source and target vertex.
  5286. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5287. undirected graph from a list of edges. Each edge is represented by
  5288. a list containing two vertices.
  5289. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5290. inserts a vertex into the graph.
  5291. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5292. inserts an edge between the two vertices.
  5293. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5294. returns a sequence of vertices adjacent to the vertex.
  5295. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5296. returns a sequence of all vertices in the graph.
  5297. \end{description}
  5298. \end{tcolorbox}
  5299. %\end{wrapfigure}
  5300. \caption{The Racket \code{graph} package.}
  5301. \label{fig:graph}
  5302. \end{figure}
  5303. \fi}
  5304. On the basis of the liveness analysis, we know where each location is
  5305. live. However, during register allocation, we need to answer
  5306. questions of the specific form: are locations $u$ and $v$ live at the
  5307. same time? (If so, they cannot be assigned to the same register.) To
  5308. make this question more efficient to answer, we create an explicit
  5309. data structure, an \emph{interference
  5310. graph}\index{subject}{interference graph}. An interference graph is
  5311. an undirected graph that has a node for every variable and register
  5312. and has an edge between two nodes if they are
  5313. live at the same time, that is, if they interfere with each other.
  5314. %
  5315. \racket{We recommend using the Racket \code{graph} package
  5316. (figure~\ref{fig:graph}) to represent the interference graph.}
  5317. %
  5318. \python{We provide implementations of directed and undirected graph
  5319. data structures in the file \code{graph.py} of the support code.}
  5320. A straightforward way to compute the interference graph is to look at
  5321. the set of live locations between each instruction and add an edge to
  5322. the graph for every pair of variables in the same set. This approach
  5323. is less than ideal for two reasons. First, it can be expensive because
  5324. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5325. locations. Second, in the special case in which two locations hold the
  5326. same value (because one was assigned to the other), they can be live
  5327. at the same time without interfering with each other.
  5328. A better way to compute the interference graph is to focus on
  5329. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5330. must not overwrite something in a live location. So for each
  5331. instruction, we create an edge between the locations being written to
  5332. and the live locations. (However, a location never interferes with
  5333. itself.) For the \key{callq} instruction, we consider all the
  5334. caller-saved registers to have been written to, so an edge is added
  5335. between every live variable and every caller-saved register. Also, for
  5336. \key{movq} there is the special case of two variables holding the same
  5337. value. If a live variable $v$ is the same as the source of the
  5338. \key{movq}, then there is no need to add an edge between $v$ and the
  5339. destination, because they both hold the same value.
  5340. %
  5341. Hence we have the following two rules:
  5342. \begin{enumerate}
  5343. \item If instruction $I_k$ is a move instruction of the form
  5344. \key{movq} $s$\key{,} $d$, then for every $v \in
  5345. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5346. $(d,v)$.
  5347. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5348. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5349. $(d,v)$.
  5350. \end{enumerate}
  5351. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5352. these rules to each instruction. We highlight a few of the
  5353. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5354. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5355. so \code{v} interferes with \code{rsp}.}
  5356. %
  5357. \python{The first instruction is \lstinline{movq $1, v}, and the
  5358. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5359. no interference because $\ttm{v}$ is the destination of the move.}
  5360. %
  5361. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5362. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5363. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5364. %
  5365. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5366. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5367. $\ttm{x}$ interferes with \ttm{w}.}
  5368. %
  5369. \racket{The next instruction is \lstinline{movq x, y}, and the
  5370. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5371. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5372. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5373. \ttm{x} and \ttm{y} hold the same value.}
  5374. %
  5375. \python{The next instruction is \lstinline{movq x, y}, and the
  5376. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5377. applies, so \ttm{y} interferes with \ttm{w} but not
  5378. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5379. \ttm{x} and \ttm{y} hold the same value.}
  5380. %
  5381. Figure~\ref{fig:interference-results} lists the interference results
  5382. for all the instructions, and the resulting interference graph is
  5383. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5384. the interference graph in figure~\ref{fig:interfere} because there
  5385. were no interference edges involving registers and we did not wish to
  5386. clutter the graph, but in general one needs to include all the
  5387. registers in the interference graph.
  5388. \begin{figure}[tbp]
  5389. \begin{tcolorbox}[colback=white]
  5390. \begin{quote}
  5391. {\if\edition\racketEd
  5392. \begin{tabular}{ll}
  5393. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5394. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5395. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5396. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5397. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5398. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5399. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5400. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5401. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5402. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5403. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5404. \lstinline!jmp conclusion!& no interference.
  5405. \end{tabular}
  5406. \fi}
  5407. {\if\edition\pythonEd\pythonColor
  5408. \begin{tabular}{ll}
  5409. \lstinline!movq $1, v!& no interference\\
  5410. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5411. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5412. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5413. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5414. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5415. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5416. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5417. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5418. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5419. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5420. \lstinline!movq tmp_1, %rdi! & no interference \\
  5421. \lstinline!callq print_int!& no interference.
  5422. \end{tabular}
  5423. \fi}
  5424. \end{quote}
  5425. \end{tcolorbox}
  5426. \caption{Interference results for the running example.}
  5427. \label{fig:interference-results}
  5428. \end{figure}
  5429. \begin{figure}[tbp]
  5430. \begin{tcolorbox}[colback=white]
  5431. \large
  5432. {\if\edition\racketEd
  5433. \[
  5434. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5435. \node (rax) at (0,0) {$\ttm{rax}$};
  5436. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5437. \node (t1) at (0,2) {$\ttm{t}$};
  5438. \node (z) at (3,2) {$\ttm{z}$};
  5439. \node (x) at (6,2) {$\ttm{x}$};
  5440. \node (y) at (3,0) {$\ttm{y}$};
  5441. \node (w) at (6,0) {$\ttm{w}$};
  5442. \node (v) at (9,0) {$\ttm{v}$};
  5443. \draw (t1) to (rax);
  5444. \draw (t1) to (z);
  5445. \draw (z) to (y);
  5446. \draw (z) to (w);
  5447. \draw (x) to (w);
  5448. \draw (y) to (w);
  5449. \draw (v) to (w);
  5450. \draw (v) to (rsp);
  5451. \draw (w) to (rsp);
  5452. \draw (x) to (rsp);
  5453. \draw (y) to (rsp);
  5454. \path[-.,bend left=15] (z) edge node {} (rsp);
  5455. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5456. \draw (rax) to (rsp);
  5457. \end{tikzpicture}
  5458. \]
  5459. \fi}
  5460. {\if\edition\pythonEd\pythonColor
  5461. \[
  5462. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5463. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5464. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5465. \node (z) at (3,2) {$\ttm{z}$};
  5466. \node (x) at (6,2) {$\ttm{x}$};
  5467. \node (y) at (3,0) {$\ttm{y}$};
  5468. \node (w) at (6,0) {$\ttm{w}$};
  5469. \node (v) at (9,0) {$\ttm{v}$};
  5470. \draw (t0) to (t1);
  5471. \draw (t0) to (z);
  5472. \draw (z) to (y);
  5473. \draw (z) to (w);
  5474. \draw (x) to (w);
  5475. \draw (y) to (w);
  5476. \draw (v) to (w);
  5477. \end{tikzpicture}
  5478. \]
  5479. \fi}
  5480. \end{tcolorbox}
  5481. \caption{The interference graph of the example program.}
  5482. \label{fig:interfere}
  5483. \end{figure}
  5484. \begin{exercise}\normalfont\normalsize
  5485. \racket{Implement the compiler pass named \code{build\_interference} according
  5486. to the algorithm suggested here. We recommend using the Racket
  5487. \code{graph} package to create and inspect the interference graph.
  5488. The output graph of this pass should be stored in the $\itm{info}$ field of
  5489. the program, under the key \code{conflicts}.}
  5490. %
  5491. \python{Implement a function named \code{build\_interference}
  5492. according to the algorithm suggested above that
  5493. returns the interference graph.}
  5494. \end{exercise}
  5495. \section{Graph Coloring via Sudoku}
  5496. \label{sec:graph-coloring}
  5497. \index{subject}{graph coloring}
  5498. \index{subject}{sudoku}
  5499. \index{subject}{color}
  5500. We come to the main event discussed in this chapter, mapping variables
  5501. to registers and stack locations. Variables that interfere with each
  5502. other must be mapped to different locations. In terms of the
  5503. interference graph, this means that adjacent vertices must be mapped
  5504. to different locations. If we think of locations as colors, the
  5505. register allocation problem becomes the graph coloring
  5506. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5507. The reader may be more familiar with the graph coloring problem than he
  5508. or she realizes; the popular game of sudoku is an instance of the
  5509. graph coloring problem. The following describes how to build a graph
  5510. out of an initial sudoku board.
  5511. \begin{itemize}
  5512. \item There is one vertex in the graph for each sudoku square.
  5513. \item There is an edge between two vertices if the corresponding squares
  5514. are in the same row, in the same column, or in the same $3\times 3$ region.
  5515. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5516. \item On the basis of the initial assignment of numbers to squares on the
  5517. sudoku board, assign the corresponding colors to the corresponding
  5518. vertices in the graph.
  5519. \end{itemize}
  5520. If you can color the remaining vertices in the graph with the nine
  5521. colors, then you have also solved the corresponding game of sudoku.
  5522. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5523. the corresponding graph with colored vertices. Here we use a
  5524. monochrome representation of colors, mapping the sudoku number 1 to
  5525. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5526. of the vertices (the colored ones) because showing edges for all the
  5527. vertices would make the graph unreadable.
  5528. \begin{figure}[tbp]
  5529. \begin{tcolorbox}[colback=white]
  5530. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5531. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5532. \end{tcolorbox}
  5533. \caption{A sudoku game board and the corresponding colored graph.}
  5534. \label{fig:sudoku-graph}
  5535. \end{figure}
  5536. Some techniques for playing sudoku correspond to heuristics used in
  5537. graph coloring algorithms. For example, one of the basic techniques
  5538. for sudoku is called Pencil Marks. The idea is to use a process of
  5539. elimination to determine what numbers are no longer available for a
  5540. square and to write those numbers in the square (writing very
  5541. small). For example, if the number $1$ is assigned to a square, then
  5542. write the pencil mark $1$ in all the squares in the same row, column,
  5543. and region to indicate that $1$ is no longer an option for those other
  5544. squares.
  5545. %
  5546. The Pencil Marks technique corresponds to the notion of
  5547. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5548. saturation of a vertex, in sudoku terms, is the set of numbers that
  5549. are no longer available. In graph terminology, we have the following
  5550. definition:
  5551. \begin{equation*}
  5552. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5553. \text{ and } \mathrm{color}(v) = c \}
  5554. \end{equation*}
  5555. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5556. edge with $u$.
  5557. The Pencil Marks technique leads to a simple strategy for filling in
  5558. numbers: if there is a square with only one possible number left, then
  5559. choose that number! But what if there are no squares with only one
  5560. possibility left? One brute-force approach is to try them all: choose
  5561. the first one, and if that ultimately leads to a solution, great. If
  5562. not, backtrack and choose the next possibility. One good thing about
  5563. Pencil Marks is that it reduces the degree of branching in the search
  5564. tree. Nevertheless, backtracking can be terribly time consuming. One
  5565. way to reduce the amount of backtracking is to use the
  5566. most-constrained-first heuristic (aka minimum remaining
  5567. values)~\citep{Russell2003}. That is, in choosing a square, always
  5568. choose one with the fewest possibilities left (the vertex with the
  5569. highest saturation). The idea is that choosing highly constrained
  5570. squares earlier rather than later is better, because later on there may
  5571. not be any possibilities left in the highly saturated squares.
  5572. However, register allocation is easier than sudoku, because the
  5573. register allocator can fall back to assigning variables to stack
  5574. locations when the registers run out. Thus, it makes sense to replace
  5575. backtracking with greedy search: make the best choice at the time and
  5576. keep going. We still wish to minimize the number of colors needed, so
  5577. we use the most-constrained-first heuristic in the greedy search.
  5578. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5579. algorithm for register allocation based on saturation and the
  5580. most-constrained-first heuristic. It is roughly equivalent to the
  5581. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5582. sudoku, the algorithm represents colors with integers. The integers
  5583. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5584. register allocation. In particular, we recommend the following
  5585. correspondence, with $k=11$.
  5586. \begin{lstlisting}
  5587. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5588. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5589. \end{lstlisting}
  5590. The integers $k$ and larger correspond to stack locations. The
  5591. registers that are not used for register allocation, such as
  5592. \code{rax}, are assigned to negative integers. In particular, we
  5593. recommend the following correspondence.
  5594. \begin{lstlisting}
  5595. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5596. \end{lstlisting}
  5597. \begin{figure}[btp]
  5598. \begin{tcolorbox}[colback=white]
  5599. \centering
  5600. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5601. Algorithm: DSATUR
  5602. Input: A graph |$G$|
  5603. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5604. |$W \gets \mathrm{vertices}(G)$|
  5605. while |$W \neq \emptyset$| do
  5606. pick a vertex |$u$| from |$W$| with the highest saturation,
  5607. breaking ties randomly
  5608. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5609. |$\mathrm{color}[u] \gets c$|
  5610. |$W \gets W - \{u\}$|
  5611. \end{lstlisting}
  5612. \end{tcolorbox}
  5613. \caption{The saturation-based greedy graph coloring algorithm.}
  5614. \label{fig:satur-algo}
  5615. \end{figure}
  5616. {\if\edition\racketEd
  5617. With the DSATUR algorithm in hand, let us return to the running
  5618. example and consider how to color the interference graph shown in
  5619. figure~\ref{fig:interfere}.
  5620. %
  5621. We start by assigning each register node to its own color. For
  5622. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5623. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5624. (To reduce clutter in the interference graph, we elide nodes
  5625. that do not have interference edges, such as \code{rcx}.)
  5626. The variables are not yet colored, so they are annotated with a dash. We
  5627. then update the saturation for vertices that are adjacent to a
  5628. register, obtaining the following annotated graph. For example, the
  5629. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5630. \code{rax} and \code{rsp}.
  5631. \[
  5632. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5634. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5635. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5636. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5637. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5638. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5639. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5640. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5641. \draw (t1) to (rax);
  5642. \draw (t1) to (z);
  5643. \draw (z) to (y);
  5644. \draw (z) to (w);
  5645. \draw (x) to (w);
  5646. \draw (y) to (w);
  5647. \draw (v) to (w);
  5648. \draw (v) to (rsp);
  5649. \draw (w) to (rsp);
  5650. \draw (x) to (rsp);
  5651. \draw (y) to (rsp);
  5652. \path[-.,bend left=15] (z) edge node {} (rsp);
  5653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5654. \draw (rax) to (rsp);
  5655. \end{tikzpicture}
  5656. \]
  5657. The algorithm says to select a maximally saturated vertex. So, we pick
  5658. $\ttm{t}$ and color it with the first available integer, which is
  5659. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5660. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5661. \[
  5662. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5664. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5665. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5666. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5667. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5668. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5669. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5670. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5671. \draw (t1) to (rax);
  5672. \draw (t1) to (z);
  5673. \draw (z) to (y);
  5674. \draw (z) to (w);
  5675. \draw (x) to (w);
  5676. \draw (y) to (w);
  5677. \draw (v) to (w);
  5678. \draw (v) to (rsp);
  5679. \draw (w) to (rsp);
  5680. \draw (x) to (rsp);
  5681. \draw (y) to (rsp);
  5682. \path[-.,bend left=15] (z) edge node {} (rsp);
  5683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5684. \draw (rax) to (rsp);
  5685. \end{tikzpicture}
  5686. \]
  5687. We repeat the process, selecting a maximally saturated vertex,
  5688. choosing \code{z}, and coloring it with the first available number, which
  5689. is $1$. We add $1$ to the saturation for the neighboring vertices
  5690. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5691. \[
  5692. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5693. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5694. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5695. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5696. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5697. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5698. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5699. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5700. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5701. \draw (t1) to (rax);
  5702. \draw (t1) to (z);
  5703. \draw (z) to (y);
  5704. \draw (z) to (w);
  5705. \draw (x) to (w);
  5706. \draw (y) to (w);
  5707. \draw (v) to (w);
  5708. \draw (v) to (rsp);
  5709. \draw (w) to (rsp);
  5710. \draw (x) to (rsp);
  5711. \draw (y) to (rsp);
  5712. \path[-.,bend left=15] (z) edge node {} (rsp);
  5713. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5714. \draw (rax) to (rsp);
  5715. \end{tikzpicture}
  5716. \]
  5717. The most saturated vertices are now \code{w} and \code{y}. We color
  5718. \code{w} with the first available color, which is $0$.
  5719. \[
  5720. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5721. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5722. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5723. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5724. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5725. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5726. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5727. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5728. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5729. \draw (t1) to (rax);
  5730. \draw (t1) to (z);
  5731. \draw (z) to (y);
  5732. \draw (z) to (w);
  5733. \draw (x) to (w);
  5734. \draw (y) to (w);
  5735. \draw (v) to (w);
  5736. \draw (v) to (rsp);
  5737. \draw (w) to (rsp);
  5738. \draw (x) to (rsp);
  5739. \draw (y) to (rsp);
  5740. \path[-.,bend left=15] (z) edge node {} (rsp);
  5741. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5742. \draw (rax) to (rsp);
  5743. \end{tikzpicture}
  5744. \]
  5745. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5746. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5747. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5748. and \code{z}, whose colors are $0$ and $1$ respectively.
  5749. \[
  5750. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5751. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5752. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5753. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5754. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5755. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5756. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5757. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5758. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5759. \draw (t1) to (rax);
  5760. \draw (t1) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \draw (v) to (rsp);
  5767. \draw (w) to (rsp);
  5768. \draw (x) to (rsp);
  5769. \draw (y) to (rsp);
  5770. \path[-.,bend left=15] (z) edge node {} (rsp);
  5771. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5772. \draw (rax) to (rsp);
  5773. \end{tikzpicture}
  5774. \]
  5775. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5776. \[
  5777. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5778. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5779. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5780. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5781. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5782. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5783. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5784. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5785. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5786. \draw (t1) to (rax);
  5787. \draw (t1) to (z);
  5788. \draw (z) to (y);
  5789. \draw (z) to (w);
  5790. \draw (x) to (w);
  5791. \draw (y) to (w);
  5792. \draw (v) to (w);
  5793. \draw (v) to (rsp);
  5794. \draw (w) to (rsp);
  5795. \draw (x) to (rsp);
  5796. \draw (y) to (rsp);
  5797. \path[-.,bend left=15] (z) edge node {} (rsp);
  5798. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5799. \draw (rax) to (rsp);
  5800. \end{tikzpicture}
  5801. \]
  5802. In the last step of the algorithm, we color \code{x} with $1$.
  5803. \[
  5804. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5805. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5806. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5807. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5808. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5809. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5810. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5811. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5812. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5813. \draw (t1) to (rax);
  5814. \draw (t1) to (z);
  5815. \draw (z) to (y);
  5816. \draw (z) to (w);
  5817. \draw (x) to (w);
  5818. \draw (y) to (w);
  5819. \draw (v) to (w);
  5820. \draw (v) to (rsp);
  5821. \draw (w) to (rsp);
  5822. \draw (x) to (rsp);
  5823. \draw (y) to (rsp);
  5824. \path[-.,bend left=15] (z) edge node {} (rsp);
  5825. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5826. \draw (rax) to (rsp);
  5827. \end{tikzpicture}
  5828. \]
  5829. So, we obtain the following coloring:
  5830. \[
  5831. \{
  5832. \ttm{rax} \mapsto -1,
  5833. \ttm{rsp} \mapsto -2,
  5834. \ttm{t} \mapsto 0,
  5835. \ttm{z} \mapsto 1,
  5836. \ttm{x} \mapsto 1,
  5837. \ttm{y} \mapsto 2,
  5838. \ttm{w} \mapsto 0,
  5839. \ttm{v} \mapsto 1
  5840. \}
  5841. \]
  5842. \fi}
  5843. %
  5844. {\if\edition\pythonEd\pythonColor
  5845. %
  5846. With the DSATUR algorithm in hand, let us return to the running
  5847. example and consider how to color the interference graph shown in
  5848. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5849. to indicate that it has not yet been assigned a color. Each register
  5850. node (not shown) should be assigned the number that the register
  5851. corresponds to, for example, color \code{rcx} with the number \code{0}
  5852. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5853. each node; all of them start as the empty set.
  5854. %
  5855. \[
  5856. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5857. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5858. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5859. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5860. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5861. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5862. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5863. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5864. \draw (t0) to (t1);
  5865. \draw (t0) to (z);
  5866. \draw (z) to (y);
  5867. \draw (z) to (w);
  5868. \draw (x) to (w);
  5869. \draw (y) to (w);
  5870. \draw (v) to (w);
  5871. \end{tikzpicture}
  5872. \]
  5873. The algorithm says to select a maximally saturated vertex, but they
  5874. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5875. and then we color it with the first available integer, which is $0$. We mark
  5876. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5877. they interfere with $\ttm{tmp\_0}$.
  5878. \[
  5879. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5880. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5881. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5882. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5883. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5884. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5885. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5886. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5887. \draw (t0) to (t1);
  5888. \draw (t0) to (z);
  5889. \draw (z) to (y);
  5890. \draw (z) to (w);
  5891. \draw (x) to (w);
  5892. \draw (y) to (w);
  5893. \draw (v) to (w);
  5894. \end{tikzpicture}
  5895. \]
  5896. We repeat the process. The most saturated vertices are \code{z} and
  5897. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5898. available number, which is $1$. We add $1$ to the saturation for the
  5899. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5900. \[
  5901. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5902. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5903. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5904. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5905. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5906. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5907. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5908. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5909. \draw (t0) to (t1);
  5910. \draw (t0) to (z);
  5911. \draw (z) to (y);
  5912. \draw (z) to (w);
  5913. \draw (x) to (w);
  5914. \draw (y) to (w);
  5915. \draw (v) to (w);
  5916. \end{tikzpicture}
  5917. \]
  5918. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5919. \code{y}. We color \code{w} with the first available color, which
  5920. is $0$.
  5921. \[
  5922. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5923. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5924. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5925. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5926. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5927. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5928. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5929. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5930. \draw (t0) to (t1);
  5931. \draw (t0) to (z);
  5932. \draw (z) to (y);
  5933. \draw (z) to (w);
  5934. \draw (x) to (w);
  5935. \draw (y) to (w);
  5936. \draw (v) to (w);
  5937. \end{tikzpicture}
  5938. \]
  5939. Now \code{y} is the most saturated, so we color it with $2$.
  5940. \[
  5941. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5942. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5943. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5944. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5945. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5946. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5947. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5948. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5949. \draw (t0) to (t1);
  5950. \draw (t0) to (z);
  5951. \draw (z) to (y);
  5952. \draw (z) to (w);
  5953. \draw (x) to (w);
  5954. \draw (y) to (w);
  5955. \draw (v) to (w);
  5956. \end{tikzpicture}
  5957. \]
  5958. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5959. We choose to color \code{v} with $1$.
  5960. \[
  5961. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5962. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5963. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5964. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5965. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5966. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5967. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5968. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5969. \draw (t0) to (t1);
  5970. \draw (t0) to (z);
  5971. \draw (z) to (y);
  5972. \draw (z) to (w);
  5973. \draw (x) to (w);
  5974. \draw (y) to (w);
  5975. \draw (v) to (w);
  5976. \end{tikzpicture}
  5977. \]
  5978. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5979. \[
  5980. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5981. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5982. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5983. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5984. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5985. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5986. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5987. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5988. \draw (t0) to (t1);
  5989. \draw (t0) to (z);
  5990. \draw (z) to (y);
  5991. \draw (z) to (w);
  5992. \draw (x) to (w);
  5993. \draw (y) to (w);
  5994. \draw (v) to (w);
  5995. \end{tikzpicture}
  5996. \]
  5997. So, we obtain the following coloring:
  5998. \[
  5999. \{ \ttm{tmp\_0} \mapsto 0,
  6000. \ttm{tmp\_1} \mapsto 1,
  6001. \ttm{z} \mapsto 1,
  6002. \ttm{x} \mapsto 1,
  6003. \ttm{y} \mapsto 2,
  6004. \ttm{w} \mapsto 0,
  6005. \ttm{v} \mapsto 1 \}
  6006. \]
  6007. \fi}
  6008. We recommend creating an auxiliary function named \code{color\_graph}
  6009. that takes an interference graph and a list of all the variables in
  6010. the program. This function should return a mapping of variables to
  6011. their colors (represented as natural numbers). By creating this helper
  6012. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  6013. when we add support for functions.
  6014. To prioritize the processing of highly saturated nodes inside the
  6015. \code{color\_graph} function, we recommend using the priority queue
  6016. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  6017. addition, you will need to maintain a mapping from variables to their
  6018. handles in the priority queue so that you can notify the priority
  6019. queue when their saturation changes.}
  6020. {\if\edition\racketEd
  6021. \begin{figure}[tp]
  6022. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6023. \small
  6024. \begin{tcolorbox}[title=Priority Queue]
  6025. A \emph{priority queue}\index{subject}{priority queue}
  6026. is a collection of items in which the
  6027. removal of items is governed by priority. In a \emph{min} queue,
  6028. lower priority items are removed first. An implementation is in
  6029. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6030. \begin{description}
  6031. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6032. priority queue that uses the $\itm{cmp}$ predicate to determine
  6033. whether its first argument has lower or equal priority to its
  6034. second argument.
  6035. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6036. items in the queue.
  6037. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6038. the item into the queue and returns a handle for the item in the
  6039. queue.
  6040. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6041. the lowest priority.
  6042. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6043. notifies the queue that the priority has decreased for the item
  6044. associated with the given handle.
  6045. \end{description}
  6046. \end{tcolorbox}
  6047. %\end{wrapfigure}
  6048. \caption{The priority queue data structure.}
  6049. \label{fig:priority-queue}
  6050. \end{figure}
  6051. \fi}
  6052. With the coloring complete, we finalize the assignment of variables to
  6053. registers and stack locations. We map the first $k$ colors to the $k$
  6054. registers and the rest of the colors to stack locations. Suppose for
  6055. the moment that we have just one register to use for register
  6056. allocation, \key{rcx}. Then we have the following assignment.
  6057. \[
  6058. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6059. \]
  6060. Composing this mapping with the coloring, we arrive at the following
  6061. assignment of variables to locations.
  6062. {\if\edition\racketEd
  6063. \begin{gather*}
  6064. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6065. \ttm{w} \mapsto \key{\%rcx}, \,
  6066. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6067. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6068. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6069. \ttm{t} \mapsto \key{\%rcx} \}
  6070. \end{gather*}
  6071. \fi}
  6072. {\if\edition\pythonEd\pythonColor
  6073. \begin{gather*}
  6074. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6075. \ttm{w} \mapsto \key{\%rcx}, \,
  6076. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6077. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6078. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6079. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6080. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6081. \end{gather*}
  6082. \fi}
  6083. Adapt the code from the \code{assign\_homes} pass
  6084. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6085. assigned location. Applying this assignment to our running
  6086. example shown next, on the left, yields the program on the right.
  6087. \begin{center}
  6088. {\if\edition\racketEd
  6089. \begin{minipage}{0.35\textwidth}
  6090. \begin{lstlisting}
  6091. movq $1, v
  6092. movq $42, w
  6093. movq v, x
  6094. addq $7, x
  6095. movq x, y
  6096. movq x, z
  6097. addq w, z
  6098. movq y, t
  6099. negq t
  6100. movq z, %rax
  6101. addq t, %rax
  6102. jmp conclusion
  6103. \end{lstlisting}
  6104. \end{minipage}
  6105. $\Rightarrow\qquad$
  6106. \begin{minipage}{0.45\textwidth}
  6107. \begin{lstlisting}
  6108. movq $1, -8(%rbp)
  6109. movq $42, %rcx
  6110. movq -8(%rbp), -8(%rbp)
  6111. addq $7, -8(%rbp)
  6112. movq -8(%rbp), -16(%rbp)
  6113. movq -8(%rbp), -8(%rbp)
  6114. addq %rcx, -8(%rbp)
  6115. movq -16(%rbp), %rcx
  6116. negq %rcx
  6117. movq -8(%rbp), %rax
  6118. addq %rcx, %rax
  6119. jmp conclusion
  6120. \end{lstlisting}
  6121. \end{minipage}
  6122. \fi}
  6123. {\if\edition\pythonEd\pythonColor
  6124. \begin{minipage}{0.35\textwidth}
  6125. \begin{lstlisting}
  6126. movq $1, v
  6127. movq $42, w
  6128. movq v, x
  6129. addq $7, x
  6130. movq x, y
  6131. movq x, z
  6132. addq w, z
  6133. movq y, tmp_0
  6134. negq tmp_0
  6135. movq z, tmp_1
  6136. addq tmp_0, tmp_1
  6137. movq tmp_1, %rdi
  6138. callq print_int
  6139. \end{lstlisting}
  6140. \end{minipage}
  6141. $\Rightarrow\qquad$
  6142. \begin{minipage}{0.45\textwidth}
  6143. \begin{lstlisting}
  6144. movq $1, -8(%rbp)
  6145. movq $42, %rcx
  6146. movq -8(%rbp), -8(%rbp)
  6147. addq $7, -8(%rbp)
  6148. movq -8(%rbp), -16(%rbp)
  6149. movq -8(%rbp), -8(%rbp)
  6150. addq %rcx, -8(%rbp)
  6151. movq -16(%rbp), %rcx
  6152. negq %rcx
  6153. movq -8(%rbp), -8(%rbp)
  6154. addq %rcx, -8(%rbp)
  6155. movq -8(%rbp), %rdi
  6156. callq print_int
  6157. \end{lstlisting}
  6158. \end{minipage}
  6159. \fi}
  6160. \end{center}
  6161. \begin{exercise}\normalfont\normalsize
  6162. Implement the \code{allocate\_registers} \racket{pass}\python{function}.
  6163. Create five programs that exercise all aspects of the register
  6164. allocation algorithm, including spilling variables to the stack.
  6165. %
  6166. {\if\edition\racketEd
  6167. Replace \code{assign\_homes} in the list of \code{passes} in the
  6168. \code{run-tests.rkt} script with the three new passes:
  6169. \code{uncover\_live}, \code{build\_interference}, and
  6170. \code{allocate\_registers}.
  6171. Temporarily remove the call to \code{compiler-tests}.
  6172. Run the script to test the register allocator.
  6173. \fi}
  6174. %
  6175. {\if\edition\pythonEd\pythonColor
  6176. Update the \code{assign\_homes} pass to make use of
  6177. the functions you have created to perform register allocation:
  6178. \code{uncover\_live}, \code{build\_interference}, and
  6179. \code{allocate\_registers}.
  6180. Run the \code{run-tests.py} script to check whether the
  6181. output programs produce the same result as the input programs.
  6182. Inspect the generated x86 programs to make sure that some variables
  6183. are assigned to registers.
  6184. \fi}
  6185. \end{exercise}
  6186. \section{Patch Instructions}
  6187. \label{sec:patch-instructions}
  6188. The remaining step in the compilation to x86 is to ensure that the
  6189. instructions have at most one argument that is a memory access.
  6190. %
  6191. In the running example, the instruction \code{movq -8(\%rbp),
  6192. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6193. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6194. then move \code{rax} into \code{-16(\%rbp)}.
  6195. %
  6196. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6197. problematic, but they can simply be deleted. In general, we recommend
  6198. deleting all the trivial moves whose source and destination are the
  6199. same location.
  6200. %
  6201. The following is the output of \code{patch\_instructions} on the
  6202. running example.
  6203. \begin{center}
  6204. {\if\edition\racketEd
  6205. \begin{minipage}{0.35\textwidth}
  6206. \begin{lstlisting}
  6207. movq $1, -8(%rbp)
  6208. movq $42, %rcx
  6209. movq -8(%rbp), -8(%rbp)
  6210. addq $7, -8(%rbp)
  6211. movq -8(%rbp), -16(%rbp)
  6212. movq -8(%rbp), -8(%rbp)
  6213. addq %rcx, -8(%rbp)
  6214. movq -16(%rbp), %rcx
  6215. negq %rcx
  6216. movq -8(%rbp), %rax
  6217. addq %rcx, %rax
  6218. jmp conclusion
  6219. \end{lstlisting}
  6220. \end{minipage}
  6221. $\Rightarrow\qquad$
  6222. \begin{minipage}{0.45\textwidth}
  6223. \begin{lstlisting}
  6224. movq $1, -8(%rbp)
  6225. movq $42, %rcx
  6226. addq $7, -8(%rbp)
  6227. movq -8(%rbp), %rax
  6228. movq %rax, -16(%rbp)
  6229. addq %rcx, -8(%rbp)
  6230. movq -16(%rbp), %rcx
  6231. negq %rcx
  6232. movq -8(%rbp), %rax
  6233. addq %rcx, %rax
  6234. jmp conclusion
  6235. \end{lstlisting}
  6236. \end{minipage}
  6237. \fi}
  6238. {\if\edition\pythonEd\pythonColor
  6239. \begin{minipage}{0.35\textwidth}
  6240. \begin{lstlisting}
  6241. movq $1, -8(%rbp)
  6242. movq $42, %rcx
  6243. movq -8(%rbp), -8(%rbp)
  6244. addq $7, -8(%rbp)
  6245. movq -8(%rbp), -16(%rbp)
  6246. movq -8(%rbp), -8(%rbp)
  6247. addq %rcx, -8(%rbp)
  6248. movq -16(%rbp), %rcx
  6249. negq %rcx
  6250. movq -8(%rbp), -8(%rbp)
  6251. addq %rcx, -8(%rbp)
  6252. movq -8(%rbp), %rdi
  6253. callq print_int
  6254. \end{lstlisting}
  6255. \end{minipage}
  6256. $\Rightarrow\qquad$
  6257. \begin{minipage}{0.45\textwidth}
  6258. \begin{lstlisting}
  6259. movq $1, -8(%rbp)
  6260. movq $42, %rcx
  6261. addq $7, -8(%rbp)
  6262. movq -8(%rbp), %rax
  6263. movq %rax, -16(%rbp)
  6264. addq %rcx, -8(%rbp)
  6265. movq -16(%rbp), %rcx
  6266. negq %rcx
  6267. addq %rcx, -8(%rbp)
  6268. movq -8(%rbp), %rdi
  6269. callq print_int
  6270. \end{lstlisting}
  6271. \end{minipage}
  6272. \fi}
  6273. \end{center}
  6274. \begin{exercise}\normalfont\normalsize
  6275. %
  6276. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6277. %
  6278. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6279. %in the \code{run-tests.rkt} script.
  6280. %
  6281. Run the script to test the \code{patch\_instructions} pass.
  6282. \end{exercise}
  6283. \section{Generate Prelude and Conclusion}
  6284. \label{sec:print-x86-reg-alloc}
  6285. \index{subject}{calling conventions}
  6286. \index{subject}{prelude}\index{subject}{conclusion}
  6287. Recall that this pass generates the prelude and conclusion
  6288. instructions to satisfy the x86 calling conventions
  6289. (section~\ref{sec:calling-conventions}). With the addition of the
  6290. register allocator, the callee-saved registers used by the register
  6291. allocator must be saved in the prelude and restored in the conclusion.
  6292. In the \code{allocate\_registers} pass,
  6293. %
  6294. \racket{add an entry to the \itm{info}
  6295. of \code{X86Program} named \code{used\_callee}}
  6296. %
  6297. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6298. %
  6299. that stores the set of callee-saved registers that were assigned to
  6300. variables. The \code{prelude\_and\_conclusion} pass can then access
  6301. this information to decide which callee-saved registers need to be
  6302. saved and restored.
  6303. %
  6304. When calculating the amount to adjust the \code{rsp} in the prelude,
  6305. make sure to take into account the space used for saving the
  6306. callee-saved registers. Also, remember that the frame needs to be a
  6307. multiple of 16 bytes! We recommend using the following equation for
  6308. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6309. of stack locations used by spilled variables\footnote{Sometimes two or
  6310. more spilled variables are assigned to the same stack location, so
  6311. $S$ can be less than the number of spilled variables.} and $C$ be
  6312. the number of callee-saved registers that were
  6313. allocated\index{subject}{allocate} to
  6314. variables. The $\itm{align}$ function rounds a number up to the
  6315. nearest 16 bytes.
  6316. \[
  6317. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6318. \]
  6319. The reason we subtract $8\itm{C}$ in this equation is that the
  6320. prelude uses \code{pushq} to save each of the callee-saved registers,
  6321. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6322. \racket{An overview of all the passes involved in register
  6323. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6324. {\if\edition\racketEd
  6325. \begin{figure}[tbp]
  6326. \begin{tcolorbox}[colback=white]
  6327. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6328. \node (Lvar) at (0,2) {\large \LangVar{}};
  6329. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6330. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6331. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6332. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6333. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6334. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6335. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6336. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6337. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6338. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6339. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6340. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6341. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6342. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6343. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6344. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6345. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6346. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6347. \end{tikzpicture}
  6348. \end{tcolorbox}
  6349. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6350. \label{fig:reg-alloc-passes}
  6351. \end{figure}
  6352. \fi}
  6353. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6354. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6355. use of registers and the stack, we limit the register allocator for
  6356. this example to use just two registers: \code{rcx} (color $0$) and
  6357. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6358. \code{main} function, we push \code{rbx} onto the stack because it is
  6359. a callee-saved register and it was assigned to a variable by the
  6360. register allocator. We subtract \code{8} from the \code{rsp} at the
  6361. end of the prelude to reserve space for the one spilled variable.
  6362. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6363. Moving on to the program proper, we see how the registers were
  6364. allocated.
  6365. %
  6366. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6367. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6368. %
  6369. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6370. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6371. were assigned to \code{rbx}.}
  6372. %
  6373. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6374. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6375. callee-save register \code{rbx} onto the stack. The spilled variables
  6376. must be placed lower on the stack than the saved callee-save
  6377. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6378. \code{-16(\%rbp)}.
  6379. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6380. done in the prelude. We move the stack pointer up by \code{8} bytes
  6381. (the room for spilled variables), then pop the old values of
  6382. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6383. \code{retq} to return control to the operating system.
  6384. \begin{figure}[tbp]
  6385. \begin{minipage}{0.55\textwidth}
  6386. \begin{tcolorbox}[colback=white]
  6387. % var_test_28.rkt
  6388. % (use-minimal-set-of-registers! #t)
  6389. % 0 -> rcx
  6390. % 1 -> rbx
  6391. %
  6392. % t 0 rcx
  6393. % z 1 rbx
  6394. % w 0 rcx
  6395. % y 2 rbp -16
  6396. % v 1 rbx
  6397. % x 1 rbx
  6398. {\if\edition\racketEd
  6399. \begin{lstlisting}
  6400. start:
  6401. movq $1, %rbx
  6402. movq $42, %rcx
  6403. addq $7, %rbx
  6404. movq %rbx, -16(%rbp)
  6405. addq %rcx, %rbx
  6406. movq -16(%rbp), %rcx
  6407. negq %rcx
  6408. movq %rbx, %rax
  6409. addq %rcx, %rax
  6410. jmp conclusion
  6411. .globl main
  6412. main:
  6413. pushq %rbp
  6414. movq %rsp, %rbp
  6415. pushq %rbx
  6416. subq $8, %rsp
  6417. jmp start
  6418. conclusion:
  6419. addq $8, %rsp
  6420. popq %rbx
  6421. popq %rbp
  6422. retq
  6423. \end{lstlisting}
  6424. \fi}
  6425. {\if\edition\pythonEd\pythonColor
  6426. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6427. \begin{lstlisting}
  6428. .globl main
  6429. main:
  6430. pushq %rbp
  6431. movq %rsp, %rbp
  6432. pushq %rbx
  6433. subq $8, %rsp
  6434. movq $1, %rcx
  6435. movq $42, %rbx
  6436. addq $7, %rcx
  6437. movq %rcx, -16(%rbp)
  6438. addq %rbx, -16(%rbp)
  6439. negq %rcx
  6440. movq -16(%rbp), %rbx
  6441. addq %rcx, %rbx
  6442. movq %rbx, %rdi
  6443. callq print_int
  6444. addq $8, %rsp
  6445. popq %rbx
  6446. popq %rbp
  6447. retq
  6448. \end{lstlisting}
  6449. \fi}
  6450. \end{tcolorbox}
  6451. \end{minipage}
  6452. \caption{The x86 output from the running example
  6453. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6454. and \code{rcx}.}
  6455. \label{fig:running-example-x86}
  6456. \end{figure}
  6457. \begin{exercise}\normalfont\normalsize
  6458. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6459. %
  6460. \racket{
  6461. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6462. list of passes and the call to \code{compiler-tests}.}
  6463. %
  6464. Run the script to test the complete compiler for \LangVar{} that
  6465. performs register allocation.
  6466. \end{exercise}
  6467. \section{Challenge: Move Biasing}
  6468. \label{sec:move-biasing}
  6469. \index{subject}{move biasing}
  6470. This section describes an enhancement to the register allocator,
  6471. called move biasing, for students who are looking for an extra
  6472. challenge.
  6473. {\if\edition\racketEd
  6474. To motivate the need for move biasing we return to the running example,
  6475. but this time we use all the general purpose registers. So, we have
  6476. the following mapping of color numbers to registers.
  6477. \[
  6478. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6479. \]
  6480. Using the same assignment of variables to color numbers that was
  6481. produced by the register allocator described in the last section, we
  6482. get the following program.
  6483. \begin{center}
  6484. \begin{minipage}{0.35\textwidth}
  6485. \begin{lstlisting}
  6486. movq $1, v
  6487. movq $42, w
  6488. movq v, x
  6489. addq $7, x
  6490. movq x, y
  6491. movq x, z
  6492. addq w, z
  6493. movq y, t
  6494. negq t
  6495. movq z, %rax
  6496. addq t, %rax
  6497. jmp conclusion
  6498. \end{lstlisting}
  6499. \end{minipage}
  6500. $\Rightarrow\qquad$
  6501. \begin{minipage}{0.45\textwidth}
  6502. \begin{lstlisting}
  6503. movq $1, %rdx
  6504. movq $42, %rcx
  6505. movq %rdx, %rdx
  6506. addq $7, %rdx
  6507. movq %rdx, %rsi
  6508. movq %rdx, %rdx
  6509. addq %rcx, %rdx
  6510. movq %rsi, %rcx
  6511. negq %rcx
  6512. movq %rdx, %rax
  6513. addq %rcx, %rax
  6514. jmp conclusion
  6515. \end{lstlisting}
  6516. \end{minipage}
  6517. \end{center}
  6518. In this output code there are two \key{movq} instructions that
  6519. can be removed because their source and target are the same. However,
  6520. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6521. register, we could instead remove three \key{movq} instructions. We
  6522. can accomplish this by taking into account which variables appear in
  6523. \key{movq} instructions with which other variables.
  6524. \fi}
  6525. {\if\edition\pythonEd\pythonColor
  6526. %
  6527. To motivate the need for move biasing we return to the running example
  6528. and recall that in section~\ref{sec:patch-instructions} we were able to
  6529. remove three trivial move instructions from the running
  6530. example. However, we could remove another trivial move if we were able
  6531. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6532. We say that two variables $p$ and $q$ are \emph{move
  6533. related}\index{subject}{move related} if they participate together in
  6534. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6535. \key{movq} $q$\key{,} $p$.
  6536. %
  6537. Recall that we color variables that are more saturated before coloring
  6538. variables that are less saturated, and in the case of equally
  6539. saturated variables, we choose randomly. Now we break such ties by
  6540. giving preference to variables that have an available color that is
  6541. the same as the color of a move-related variable.
  6542. %
  6543. Furthermore, when the register allocator chooses a color for a
  6544. variable, it should prefer a color that has already been used for a
  6545. move-related variable if one exists (and assuming that they do not
  6546. interfere). This preference should not override the preference for
  6547. registers over stack locations. So, this preference should be used as
  6548. a tie breaker in choosing between two registers or in choosing between
  6549. two stack locations.
  6550. We recommend representing the move relationships in a graph, similarly
  6551. to how we represented interference. The following is the \emph{move
  6552. graph} for our example.
  6553. {\if\edition\racketEd
  6554. \[
  6555. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6556. \node (rax) at (0,0) {$\ttm{rax}$};
  6557. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6558. \node (t) at (0,2) {$\ttm{t}$};
  6559. \node (z) at (3,2) {$\ttm{z}$};
  6560. \node (x) at (6,2) {$\ttm{x}$};
  6561. \node (y) at (3,0) {$\ttm{y}$};
  6562. \node (w) at (6,0) {$\ttm{w}$};
  6563. \node (v) at (9,0) {$\ttm{v}$};
  6564. \draw (v) to (x);
  6565. \draw (x) to (y);
  6566. \draw (x) to (z);
  6567. \draw (y) to (t);
  6568. \end{tikzpicture}
  6569. \]
  6570. \fi}
  6571. %
  6572. {\if\edition\pythonEd\pythonColor
  6573. \[
  6574. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6575. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6576. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6577. \node (z) at (3,2) {$\ttm{z}$};
  6578. \node (x) at (6,2) {$\ttm{x}$};
  6579. \node (y) at (3,0) {$\ttm{y}$};
  6580. \node (w) at (6,0) {$\ttm{w}$};
  6581. \node (v) at (9,0) {$\ttm{v}$};
  6582. \draw (y) to (t0);
  6583. \draw (z) to (x);
  6584. \draw (z) to (t1);
  6585. \draw (x) to (y);
  6586. \draw (x) to (v);
  6587. \end{tikzpicture}
  6588. \]
  6589. \fi}
  6590. {\if\edition\racketEd
  6591. Now we replay the graph coloring, pausing to see the coloring of
  6592. \code{y}. Recall the following configuration. The most saturated vertices
  6593. were \code{w} and \code{y}.
  6594. \[
  6595. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6596. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6597. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6598. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6599. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6600. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6601. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6602. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6603. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6604. \draw (t1) to (rax);
  6605. \draw (t1) to (z);
  6606. \draw (z) to (y);
  6607. \draw (z) to (w);
  6608. \draw (x) to (w);
  6609. \draw (y) to (w);
  6610. \draw (v) to (w);
  6611. \draw (v) to (rsp);
  6612. \draw (w) to (rsp);
  6613. \draw (x) to (rsp);
  6614. \draw (y) to (rsp);
  6615. \path[-.,bend left=15] (z) edge node {} (rsp);
  6616. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6617. \draw (rax) to (rsp);
  6618. \end{tikzpicture}
  6619. \]
  6620. %
  6621. The last time, we chose to color \code{w} with $0$. This time, we see
  6622. that \code{w} is not move-related to any vertex, but \code{y} is
  6623. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6624. the same color as \code{t}.
  6625. \[
  6626. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6627. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6628. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6629. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6630. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6631. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6632. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6633. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6634. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6635. \draw (t1) to (rax);
  6636. \draw (t1) to (z);
  6637. \draw (z) to (y);
  6638. \draw (z) to (w);
  6639. \draw (x) to (w);
  6640. \draw (y) to (w);
  6641. \draw (v) to (w);
  6642. \draw (v) to (rsp);
  6643. \draw (w) to (rsp);
  6644. \draw (x) to (rsp);
  6645. \draw (y) to (rsp);
  6646. \path[-.,bend left=15] (z) edge node {} (rsp);
  6647. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6648. \draw (rax) to (rsp);
  6649. \end{tikzpicture}
  6650. \]
  6651. Now \code{w} is the most saturated, so we color it $2$.
  6652. \[
  6653. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6654. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6655. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6656. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6657. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6658. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6659. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6660. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6661. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6662. \draw (t1) to (rax);
  6663. \draw (t1) to (z);
  6664. \draw (z) to (y);
  6665. \draw (z) to (w);
  6666. \draw (x) to (w);
  6667. \draw (y) to (w);
  6668. \draw (v) to (w);
  6669. \draw (v) to (rsp);
  6670. \draw (w) to (rsp);
  6671. \draw (x) to (rsp);
  6672. \draw (y) to (rsp);
  6673. \path[-.,bend left=15] (z) edge node {} (rsp);
  6674. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6675. \draw (rax) to (rsp);
  6676. \end{tikzpicture}
  6677. \]
  6678. At this point, vertices \code{x} and \code{v} are most saturated, but
  6679. \code{x} is move related to \code{y} and \code{z}, so we color
  6680. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6681. \[
  6682. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6683. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6684. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6685. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6686. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6687. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6688. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6689. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6690. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6691. \draw (t1) to (rax);
  6692. \draw (t) to (z);
  6693. \draw (z) to (y);
  6694. \draw (z) to (w);
  6695. \draw (x) to (w);
  6696. \draw (y) to (w);
  6697. \draw (v) to (w);
  6698. \draw (v) to (rsp);
  6699. \draw (w) to (rsp);
  6700. \draw (x) to (rsp);
  6701. \draw (y) to (rsp);
  6702. \path[-.,bend left=15] (z) edge node {} (rsp);
  6703. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6704. \draw (rax) to (rsp);
  6705. \end{tikzpicture}
  6706. \]
  6707. \fi}
  6708. %
  6709. {\if\edition\pythonEd\pythonColor
  6710. Now we replay the graph coloring, pausing before the coloring of
  6711. \code{w}. Recall the following configuration. The most saturated vertices
  6712. were \code{tmp\_1}, \code{w}, and \code{y}.
  6713. \[
  6714. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6715. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6716. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6717. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6718. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6719. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6720. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6721. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6722. \draw (t0) to (t1);
  6723. \draw (t0) to (z);
  6724. \draw (z) to (y);
  6725. \draw (z) to (w);
  6726. \draw (x) to (w);
  6727. \draw (y) to (w);
  6728. \draw (v) to (w);
  6729. \end{tikzpicture}
  6730. \]
  6731. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6732. or \code{y}. Note, however, that \code{w} is not move related to any
  6733. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6734. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6735. \code{y} and color it $0$, we can delete another move instruction.
  6736. \[
  6737. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6738. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6739. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6740. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6741. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6742. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6743. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6744. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6745. \draw (t0) to (t1);
  6746. \draw (t0) to (z);
  6747. \draw (z) to (y);
  6748. \draw (z) to (w);
  6749. \draw (x) to (w);
  6750. \draw (y) to (w);
  6751. \draw (v) to (w);
  6752. \end{tikzpicture}
  6753. \]
  6754. Now \code{w} is the most saturated, so we color it $2$.
  6755. \[
  6756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6757. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6758. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6759. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6760. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6761. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6762. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6763. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6764. \draw (t0) to (t1);
  6765. \draw (t0) to (z);
  6766. \draw (z) to (y);
  6767. \draw (z) to (w);
  6768. \draw (x) to (w);
  6769. \draw (y) to (w);
  6770. \draw (v) to (w);
  6771. \end{tikzpicture}
  6772. \]
  6773. To finish the coloring, \code{x} and \code{v} get $0$ and
  6774. \code{tmp\_1} gets $1$.
  6775. \[
  6776. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6777. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6778. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6779. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6780. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6781. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6782. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6783. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6784. \draw (t0) to (t1);
  6785. \draw (t0) to (z);
  6786. \draw (z) to (y);
  6787. \draw (z) to (w);
  6788. \draw (x) to (w);
  6789. \draw (y) to (w);
  6790. \draw (v) to (w);
  6791. \end{tikzpicture}
  6792. \]
  6793. \fi}
  6794. So, we have the following assignment of variables to registers.
  6795. {\if\edition\racketEd
  6796. \begin{gather*}
  6797. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6798. \ttm{w} \mapsto \key{\%rsi}, \,
  6799. \ttm{x} \mapsto \key{\%rcx}, \,
  6800. \ttm{y} \mapsto \key{\%rcx}, \,
  6801. \ttm{z} \mapsto \key{\%rdx}, \,
  6802. \ttm{t} \mapsto \key{\%rcx} \}
  6803. \end{gather*}
  6804. \fi}
  6805. {\if\edition\pythonEd\pythonColor
  6806. \begin{gather*}
  6807. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6808. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6809. \ttm{x} \mapsto \key{\%rcx}, \,
  6810. \ttm{y} \mapsto \key{\%rcx}, \\
  6811. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6812. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6813. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6814. \end{gather*}
  6815. \fi}
  6816. %
  6817. We apply this register assignment to the running example shown next,
  6818. on the left, to obtain the code in the middle. The
  6819. \code{patch\_instructions} then deletes the trivial moves to obtain
  6820. the code on the right.
  6821. {\if\edition\racketEd
  6822. \begin{center}
  6823. \begin{minipage}{0.2\textwidth}
  6824. \begin{lstlisting}
  6825. movq $1, v
  6826. movq $42, w
  6827. movq v, x
  6828. addq $7, x
  6829. movq x, y
  6830. movq x, z
  6831. addq w, z
  6832. movq y, t
  6833. negq t
  6834. movq z, %rax
  6835. addq t, %rax
  6836. jmp conclusion
  6837. \end{lstlisting}
  6838. \end{minipage}
  6839. $\Rightarrow\qquad$
  6840. \begin{minipage}{0.25\textwidth}
  6841. \begin{lstlisting}
  6842. movq $1, %rcx
  6843. movq $42, %rsi
  6844. movq %rcx, %rcx
  6845. addq $7, %rcx
  6846. movq %rcx, %rcx
  6847. movq %rcx, %rdx
  6848. addq %rsi, %rdx
  6849. movq %rcx, %rcx
  6850. negq %rcx
  6851. movq %rdx, %rax
  6852. addq %rcx, %rax
  6853. jmp conclusion
  6854. \end{lstlisting}
  6855. \end{minipage}
  6856. $\Rightarrow\qquad$
  6857. \begin{minipage}{0.23\textwidth}
  6858. \begin{lstlisting}
  6859. movq $1, %rcx
  6860. movq $42, %rsi
  6861. addq $7, %rcx
  6862. movq %rcx, %rdx
  6863. addq %rsi, %rdx
  6864. negq %rcx
  6865. movq %rdx, %rax
  6866. addq %rcx, %rax
  6867. jmp conclusion
  6868. \end{lstlisting}
  6869. \end{minipage}
  6870. \end{center}
  6871. \fi}
  6872. {\if\edition\pythonEd\pythonColor
  6873. \begin{center}
  6874. \begin{minipage}{0.20\textwidth}
  6875. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6876. movq $1, v
  6877. movq $42, w
  6878. movq v, x
  6879. addq $7, x
  6880. movq x, y
  6881. movq x, z
  6882. addq w, z
  6883. movq y, tmp_0
  6884. negq tmp_0
  6885. movq z, tmp_1
  6886. addq tmp_0, tmp_1
  6887. movq tmp_1, %rdi
  6888. callq _print_int
  6889. \end{lstlisting}
  6890. \end{minipage}
  6891. ${\Rightarrow\qquad}$
  6892. \begin{minipage}{0.35\textwidth}
  6893. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6894. movq $1, %rcx
  6895. movq $42, -16(%rbp)
  6896. movq %rcx, %rcx
  6897. addq $7, %rcx
  6898. movq %rcx, %rcx
  6899. movq %rcx, -8(%rbp)
  6900. addq -16(%rbp), -8(%rbp)
  6901. movq %rcx, %rcx
  6902. negq %rcx
  6903. movq -8(%rbp), -8(%rbp)
  6904. addq %rcx, -8(%rbp)
  6905. movq -8(%rbp), %rdi
  6906. callq _print_int
  6907. \end{lstlisting}
  6908. \end{minipage}
  6909. ${\Rightarrow\qquad}$
  6910. \begin{minipage}{0.20\textwidth}
  6911. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6912. movq $1, %rcx
  6913. movq $42, -16(%rbp)
  6914. addq $7, %rcx
  6915. movq %rcx, -8(%rbp)
  6916. movq -16(%rbp), %rax
  6917. addq %rax, -8(%rbp)
  6918. negq %rcx
  6919. addq %rcx, -8(%rbp)
  6920. movq -8(%rbp), %rdi
  6921. callq print_int
  6922. \end{lstlisting}
  6923. \end{minipage}
  6924. \end{center}
  6925. \fi}
  6926. \begin{exercise}\normalfont\normalsize
  6927. Change your implementation of \code{allocate\_registers} to take move
  6928. biasing into account. Create two new tests that include at least one
  6929. opportunity for move biasing, and visually inspect the output x86
  6930. programs to make sure that your move biasing is working properly. Make
  6931. sure that your compiler still passes all the tests.
  6932. \end{exercise}
  6933. %To do: another neat challenge would be to do
  6934. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6935. %% \subsection{Output of the Running Example}
  6936. %% \label{sec:reg-alloc-output}
  6937. % challenge: prioritize variables based on execution frequencies
  6938. % and the number of uses of a variable
  6939. % challenge: enhance the coloring algorithm using Chaitin's
  6940. % approach of prioritizing high-degree variables
  6941. % by removing low-degree variables (coloring them later)
  6942. % from the interference graph
  6943. \section{Further Reading}
  6944. \label{sec:register-allocation-further-reading}
  6945. Early register allocation algorithms were developed for Fortran
  6946. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6947. of graph coloring began in the late 1970s and early 1980s with the
  6948. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6949. algorithm is based on the following observation of
  6950. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6951. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6952. $v$ removed is also $k$ colorable. To see why, suppose that the
  6953. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6954. different colors, but because there are fewer than $k$ neighbors, there
  6955. will be one or more colors left over to use for coloring $v$ in $G$.
  6956. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6957. less than $k$ from the graph and recursively colors the rest of the
  6958. graph. Upon returning from the recursion, it colors $v$ with one of
  6959. the available colors and returns. \citet{Chaitin:1982vn} augments
  6960. this algorithm to handle spilling as follows. If there are no vertices
  6961. of degree lower than $k$ then pick a vertex at random, spill it,
  6962. remove it from the graph, and proceed recursively to color the rest of
  6963. the graph.
  6964. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6965. move-related and that don't interfere with each other, in a process
  6966. called \emph{coalescing}. Although coalescing decreases the number of
  6967. moves, it can make the graph more difficult to
  6968. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6969. which two variables are merged only if they have fewer than $k$
  6970. neighbors of high degree. \citet{George:1996aa} observes that
  6971. conservative coalescing is sometimes too conservative and made it more
  6972. aggressive by iterating the coalescing with the removal of low-degree
  6973. vertices.
  6974. %
  6975. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6976. also proposed \emph{biased coloring}, in which a variable is assigned to
  6977. the same color as another move-related variable if possible, as
  6978. discussed in section~\ref{sec:move-biasing}.
  6979. %
  6980. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6981. performs coalescing, graph coloring, and spill code insertion until
  6982. all variables have been assigned a location.
  6983. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6984. spilled variables that don't have to be: a high-degree variable can be
  6985. colorable if many of its neighbors are assigned the same color.
  6986. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6987. high-degree vertex is not immediately spilled. Instead the decision is
  6988. deferred until after the recursive call, when it is apparent whether
  6989. there is an available color or not. We observe that this algorithm is
  6990. equivalent to the smallest-last ordering
  6991. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6992. be registers and the rest to be stack locations.
  6993. %% biased coloring
  6994. Earlier editions of the compiler course at Indiana University
  6995. \citep{Dybvig:2010aa} were based on the algorithm of
  6996. \citet{Briggs:1994kx}.
  6997. The smallest-last ordering algorithm is one of many \emph{greedy}
  6998. coloring algorithms. A greedy coloring algorithm visits all the
  6999. vertices in a particular order and assigns each one the first
  7000. available color. An \emph{offline} greedy algorithm chooses the
  7001. ordering up front, prior to assigning colors. The algorithm of
  7002. \citet{Chaitin:1981vl} should be considered offline because the vertex
  7003. ordering does not depend on the colors assigned. Other orderings are
  7004. possible. For example, \citet{Chow:1984ys} ordered variables according
  7005. to an estimate of runtime cost.
  7006. An \emph{online} greedy coloring algorithm uses information about the
  7007. current assignment of colors to influence the order in which the
  7008. remaining vertices are colored. The saturation-based algorithm
  7009. described in this chapter is one such algorithm. We choose to use
  7010. saturation-based coloring because it is fun to introduce graph
  7011. coloring via sudoku!
  7012. A register allocator may choose to map each variable to just one
  7013. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  7014. variable to one or more locations. The latter can be achieved by
  7015. \emph{live range splitting}, where a variable is replaced by several
  7016. variables that each handle part of its live
  7017. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  7018. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  7019. %% replacement algorithm, bottom-up local
  7020. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  7021. %% Cooper: top-down (priority bassed), bottom-up
  7022. %% top-down
  7023. %% order variables by priority (estimated cost)
  7024. %% caveat: split variables into two groups:
  7025. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  7026. %% color the constrained ones first
  7027. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7028. %% cite J. Cocke for an algorithm that colors variables
  7029. %% in a high-degree first ordering
  7030. %Register Allocation via Usage Counts, Freiburghouse CACM
  7031. \citet{Palsberg:2007si} observes that many of the interference graphs
  7032. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7033. that is, every cycle with four or more edges has an edge that is not
  7034. part of the cycle but that connects two vertices on the cycle. Such
  7035. graphs can be optimally colored by the greedy algorithm with a vertex
  7036. ordering determined by maximum cardinality search.
  7037. In situations in which compile time is of utmost importance, such as
  7038. in just-in-time compilers, graph coloring algorithms can be too
  7039. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7040. be more appropriate.
  7041. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7042. {\if\edition\racketEd
  7043. \addtocontents{toc}{\newpage}
  7044. \fi}
  7045. \chapter{Booleans and Conditionals}
  7046. \label{ch:Lif}
  7047. \setcounter{footnote}{0}
  7048. The \LangVar{} language has only a single kind of value, the
  7049. integers. In this chapter we add a second kind of value, the Booleans,
  7050. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7051. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7052. are written
  7053. \TRUE{}\index{subject}{True@\TRUE{}} and
  7054. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7055. language includes several operations that involve Booleans
  7056. (\key{and}\index{subject}{and@\ANDNAME{}},
  7057. \key{or}\index{subject}{or@\ORNAME{}},
  7058. \key{not}\index{subject}{not@\NOTNAME{}},
  7059. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7060. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7061. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7062. conditional expression\index{subject}{conditional expression}%
  7063. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7064. With the addition of \key{if}, programs can have
  7065. nontrivial control flow\index{subject}{control flow}, which
  7066. %
  7067. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7068. %
  7069. \python{impacts liveness analysis and motivates a new pass named
  7070. \code{explicate\_control}.}
  7071. %
  7072. Also, because we now have two kinds of values, we need to handle
  7073. programs that apply an operation to the wrong kind of value, such as
  7074. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7075. There are two language design options for such situations. One option
  7076. is to signal an error and the other is to provide a wider
  7077. interpretation of the operation. \racket{The Racket
  7078. language}\python{Python} uses a mixture of these two options,
  7079. depending on the operation and the kind of value. For example, the
  7080. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7081. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7082. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7083. %
  7084. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7085. in Racket because \code{car} expects a pair.}
  7086. %
  7087. \python{On the other hand, \code{1[0]} results in a runtime error
  7088. in Python because an ``\code{int} object is not subscriptable.''}
  7089. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7090. design choices as \racket{Racket}\python{Python}, except that much of the
  7091. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7092. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7093. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7094. \python{MyPy} reports a compile-time error
  7095. %
  7096. \racket{because Racket expects the type of the argument to be of the form
  7097. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7098. %
  7099. \python{stating that a ``value of type \code{int} is not indexable.''}
  7100. The \LangIf{} language performs type checking during compilation just as
  7101. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7102. the alternative choice, that is, a dynamically typed language like
  7103. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7104. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7105. restrictive, for example, rejecting \racket{\code{(not
  7106. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7107. fairly simple because the focus of this book is on compilation and not
  7108. type systems, about which there are already several excellent
  7109. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7110. This chapter is organized as follows. We begin by defining the syntax
  7111. and interpreter for the \LangIf{} language
  7112. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7113. checking (aka semantic analysis\index{subject}{semantic analysis})
  7114. and define a type checker for \LangIf{}
  7115. (section~\ref{sec:type-check-Lif}).
  7116. %
  7117. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7118. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7119. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7120. %
  7121. The remaining sections of this chapter discuss how Booleans and
  7122. conditional control flow require changes to the existing compiler
  7123. passes and the addition of new ones. We introduce the \code{shrink}
  7124. pass to translate some operators into others, thereby reducing the
  7125. number of operators that need to be handled in later passes.
  7126. %
  7127. The main event of this chapter is the \code{explicate\_control} pass
  7128. that is responsible for translating \code{if}s into conditional
  7129. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7130. %
  7131. Regarding register allocation, there is the interesting question of
  7132. how to handle conditional \code{goto}s during liveness analysis.
  7133. \section{The \LangIf{} Language}
  7134. \label{sec:lang-if}
  7135. Definitions of the concrete syntax and abstract syntax of the
  7136. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7137. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7138. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7139. literals\index{subject}{literals}
  7140. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7141. \python{, and the \code{if} statement}. We expand the set of
  7142. operators to include
  7143. \begin{enumerate}
  7144. \item the logical operators \key{and}, \key{or}, and \key{not},
  7145. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7146. for comparing integers or Booleans for equality, and
  7147. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7148. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7149. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7150. comparing integers.
  7151. \end{enumerate}
  7152. \racket{We reorganize the abstract syntax for the primitive
  7153. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7154. rule for all of them. This means that the grammar no longer checks
  7155. whether the arity of an operator matches the number of
  7156. arguments. That responsibility is moved to the type checker for
  7157. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7158. \newcommand{\LifGrammarRacket}{
  7159. \begin{array}{lcl}
  7160. \Type &::=& \key{Boolean} \\
  7161. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7162. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7163. \Exp &::=& \itm{bool}
  7164. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7165. \MID (\key{not}\;\Exp) \\
  7166. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7167. \end{array}
  7168. }
  7169. \newcommand{\LifASTRacket}{
  7170. \begin{array}{lcl}
  7171. \Type &::=& \key{Boolean} \\
  7172. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7173. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7174. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7175. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7176. \end{array}
  7177. }
  7178. \newcommand{\LintOpAST}{
  7179. \begin{array}{rcl}
  7180. \Type &::=& \key{Integer} \\
  7181. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7182. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7183. \end{array}
  7184. }
  7185. \newcommand{\LifGrammarPython}{
  7186. \begin{array}{rcl}
  7187. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7188. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7189. \MID \key{not}~\Exp \\
  7190. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7191. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7192. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7193. \end{array}
  7194. }
  7195. \newcommand{\LifASTPython}{
  7196. \begin{array}{lcl}
  7197. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7198. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7199. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7200. \Exp &::=& \BOOL{\itm{bool}}
  7201. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7202. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7203. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7204. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7205. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7206. \end{array}
  7207. }
  7208. \begin{figure}[tp]
  7209. \centering
  7210. \begin{tcolorbox}[colback=white]
  7211. {\if\edition\racketEd
  7212. \[
  7213. \begin{array}{l}
  7214. \gray{\LintGrammarRacket{}} \\ \hline
  7215. \gray{\LvarGrammarRacket{}} \\ \hline
  7216. \LifGrammarRacket{} \\
  7217. \begin{array}{lcl}
  7218. \LangIfM{} &::=& \Exp
  7219. \end{array}
  7220. \end{array}
  7221. \]
  7222. \fi}
  7223. {\if\edition\pythonEd\pythonColor
  7224. \[
  7225. \begin{array}{l}
  7226. \gray{\LintGrammarPython} \\ \hline
  7227. \gray{\LvarGrammarPython} \\ \hline
  7228. \LifGrammarPython \\
  7229. \begin{array}{rcl}
  7230. \LangIfM{} &::=& \Stmt^{*}
  7231. \end{array}
  7232. \end{array}
  7233. \]
  7234. \fi}
  7235. \end{tcolorbox}
  7236. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7237. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7238. \label{fig:Lif-concrete-syntax}
  7239. \index{subject}{Lif@\LangIf{} concrete syntax}
  7240. \end{figure}
  7241. \begin{figure}[tp]
  7242. %\begin{minipage}{0.66\textwidth}
  7243. \begin{tcolorbox}[colback=white]
  7244. \centering
  7245. {\if\edition\racketEd
  7246. \[
  7247. \begin{array}{l}
  7248. \gray{\LintOpAST} \\ \hline
  7249. \gray{\LvarASTRacket{}} \\ \hline
  7250. \LifASTRacket{} \\
  7251. \begin{array}{lcl}
  7252. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7253. \end{array}
  7254. \end{array}
  7255. \]
  7256. \fi}
  7257. {\if\edition\pythonEd\pythonColor
  7258. \[
  7259. \begin{array}{l}
  7260. \gray{\LintASTPython} \\ \hline
  7261. \gray{\LvarASTPython} \\ \hline
  7262. \LifASTPython \\
  7263. \begin{array}{lcl}
  7264. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7265. \end{array}
  7266. \end{array}
  7267. \]
  7268. \fi}
  7269. \end{tcolorbox}
  7270. %\end{minipage}
  7271. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7272. \python{
  7273. \index{subject}{BoolOp@\texttt{BoolOp}}
  7274. \index{subject}{Compare@\texttt{Compare}}
  7275. \index{subject}{Lt@\texttt{Lt}}
  7276. \index{subject}{LtE@\texttt{LtE}}
  7277. \index{subject}{Gt@\texttt{Gt}}
  7278. \index{subject}{GtE@\texttt{GtE}}
  7279. }
  7280. \caption{The abstract syntax of \LangIf{}.}
  7281. \label{fig:Lif-syntax}
  7282. \index{subject}{Lif@\LangIf{} abstract syntax}
  7283. \end{figure}
  7284. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7285. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7286. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7287. evaluate to the corresponding Boolean values, behavior that is
  7288. inherited from the interpreter for \LangInt{}
  7289. (figure~\ref{fig:interp-Lint-class}).
  7290. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7291. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7292. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7293. \code{and}, \code{or}, and \code{not} behave according to propositional
  7294. logic. In addition, the \code{and} and \code{or} operations perform
  7295. \emph{short-circuit evaluation}.
  7296. %
  7297. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7298. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7299. %
  7300. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7301. evaluated if $e_1$ evaluates to \TRUE{}.
  7302. \racket{With the increase in the number of primitive operations, the
  7303. interpreter would become repetitive without some care. We refactor
  7304. the case for \code{Prim}, moving the code that differs with each
  7305. operation into the \code{interp\_op} method shown in
  7306. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7307. \code{or} operations separately because of their short-circuiting
  7308. behavior.}
  7309. \begin{figure}[tbp]
  7310. \begin{tcolorbox}[colback=white]
  7311. {\if\edition\racketEd
  7312. \begin{lstlisting}
  7313. (define interp-Lif-class
  7314. (class interp-Lvar-class
  7315. (super-new)
  7316. (define/public (interp_op op) ...)
  7317. (define/override ((interp_exp env) e)
  7318. (define recur (interp_exp env))
  7319. (match e
  7320. [(Bool b) b]
  7321. [(If cnd thn els)
  7322. (match (recur cnd)
  7323. [#t (recur thn)]
  7324. [#f (recur els)])]
  7325. [(Prim 'and (list e1 e2))
  7326. (match (recur e1)
  7327. [#t (match (recur e2) [#t #t] [#f #f])]
  7328. [#f #f])]
  7329. [(Prim 'or (list e1 e2))
  7330. (define v1 (recur e1))
  7331. (match v1
  7332. [#t #t]
  7333. [#f (match (recur e2) [#t #t] [#f #f])])]
  7334. [(Prim op args)
  7335. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7336. [else ((super interp_exp env) e)]))
  7337. ))
  7338. (define (interp_Lif p)
  7339. (send (new interp-Lif-class) interp_program p))
  7340. \end{lstlisting}
  7341. \fi}
  7342. {\if\edition\pythonEd\pythonColor
  7343. \begin{lstlisting}
  7344. class InterpLif(InterpLvar):
  7345. def interp_exp(self, e, env):
  7346. match e:
  7347. case IfExp(test, body, orelse):
  7348. if self.interp_exp(test, env):
  7349. return self.interp_exp(body, env)
  7350. else:
  7351. return self.interp_exp(orelse, env)
  7352. case UnaryOp(Not(), v):
  7353. return not self.interp_exp(v, env)
  7354. case BoolOp(And(), values):
  7355. if self.interp_exp(values[0], env):
  7356. return self.interp_exp(values[1], env)
  7357. else:
  7358. return False
  7359. case BoolOp(Or(), values):
  7360. if self.interp_exp(values[0], env):
  7361. return True
  7362. else:
  7363. return self.interp_exp(values[1], env)
  7364. case Compare(left, [cmp], [right]):
  7365. l = self.interp_exp(left, env)
  7366. r = self.interp_exp(right, env)
  7367. return self.interp_cmp(cmp)(l, r)
  7368. case _:
  7369. return super().interp_exp(e, env)
  7370. def interp_stmt(self, s, env, cont):
  7371. match s:
  7372. case If(test, body, orelse):
  7373. match self.interp_exp(test, env):
  7374. case True:
  7375. return self.interp_stmts(body + cont, env)
  7376. case False:
  7377. return self.interp_stmts(orelse + cont, env)
  7378. case _:
  7379. return super().interp_stmt(s, env, cont)
  7380. ...
  7381. \end{lstlisting}
  7382. \fi}
  7383. \end{tcolorbox}
  7384. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7385. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7386. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7387. \label{fig:interp-Lif}
  7388. \end{figure}
  7389. {\if\edition\racketEd
  7390. \begin{figure}[tbp]
  7391. \begin{tcolorbox}[colback=white]
  7392. \begin{lstlisting}
  7393. (define/public (interp_op op)
  7394. (match op
  7395. ['+ fx+]
  7396. ['- fx-]
  7397. ['read read-fixnum]
  7398. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7399. ['eq? (lambda (v1 v2)
  7400. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7401. (and (boolean? v1) (boolean? v2))
  7402. (and (vector? v1) (vector? v2)))
  7403. (eq? v1 v2)]))]
  7404. ['< (lambda (v1 v2)
  7405. (cond [(and (fixnum? v1) (fixnum? v2))
  7406. (< v1 v2)]))]
  7407. ['<= (lambda (v1 v2)
  7408. (cond [(and (fixnum? v1) (fixnum? v2))
  7409. (<= v1 v2)]))]
  7410. ['> (lambda (v1 v2)
  7411. (cond [(and (fixnum? v1) (fixnum? v2))
  7412. (> v1 v2)]))]
  7413. ['>= (lambda (v1 v2)
  7414. (cond [(and (fixnum? v1) (fixnum? v2))
  7415. (>= v1 v2)]))]
  7416. [else (error 'interp_op "unknown operator")]))
  7417. \end{lstlisting}
  7418. \end{tcolorbox}
  7419. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7420. \label{fig:interp-op-Lif}
  7421. \end{figure}
  7422. \fi}
  7423. {\if\edition\pythonEd\pythonColor
  7424. \begin{figure}
  7425. \begin{tcolorbox}[colback=white]
  7426. \begin{lstlisting}
  7427. class InterpLif(InterpLvar):
  7428. ...
  7429. def interp_cmp(self, cmp):
  7430. match cmp:
  7431. case Lt():
  7432. return lambda x, y: x < y
  7433. case LtE():
  7434. return lambda x, y: x <= y
  7435. case Gt():
  7436. return lambda x, y: x > y
  7437. case GtE():
  7438. return lambda x, y: x >= y
  7439. case Eq():
  7440. return lambda x, y: x == y
  7441. case NotEq():
  7442. return lambda x, y: x != y
  7443. \end{lstlisting}
  7444. \end{tcolorbox}
  7445. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7446. \label{fig:interp-cmp-Lif}
  7447. \end{figure}
  7448. \fi}
  7449. \section{Type Checking \LangIf{} Programs}
  7450. \label{sec:type-check-Lif}
  7451. It is helpful to think about type checking\index{subject}{type
  7452. checking} in two complementary ways. A type checker predicts the
  7453. type of value that will be produced by each expression in the program.
  7454. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7455. type checker should predict that {\if\edition\racketEd
  7456. \begin{lstlisting}
  7457. (+ 10 (- (+ 12 20)))
  7458. \end{lstlisting}
  7459. \fi}
  7460. {\if\edition\pythonEd\pythonColor
  7461. \begin{lstlisting}
  7462. 10 + -(12 + 20)
  7463. \end{lstlisting}
  7464. \fi}
  7465. \noindent produces a value of type \INTTY{}, whereas
  7466. {\if\edition\racketEd
  7467. \begin{lstlisting}
  7468. (and (not #f) #t)
  7469. \end{lstlisting}
  7470. \fi}
  7471. {\if\edition\pythonEd\pythonColor
  7472. \begin{lstlisting}
  7473. (not False) and True
  7474. \end{lstlisting}
  7475. \fi}
  7476. \noindent produces a value of type \BOOLTY{}.
  7477. A second way to think about type checking is that it enforces a set of
  7478. rules about which operators can be applied to which kinds of
  7479. values. For example, our type checker for \LangIf{} signals an error
  7480. for the following expression:
  7481. %
  7482. {\if\edition\racketEd
  7483. \begin{lstlisting}
  7484. (not (+ 10 (- (+ 12 20))))
  7485. \end{lstlisting}
  7486. \fi}
  7487. {\if\edition\pythonEd\pythonColor
  7488. \begin{lstlisting}
  7489. not (10 + -(12 + 20))
  7490. \end{lstlisting}
  7491. \fi}
  7492. \noindent The subexpression
  7493. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7494. \python{\code{(10 + -(12 + 20))}}
  7495. has type \INTTY{}, but the type checker enforces the rule that the
  7496. argument of \code{not} must be an expression of type \BOOLTY{}.
  7497. We implement type checking using classes and methods because they
  7498. provide the open recursion needed to reuse code as we extend the type
  7499. checker in subsequent chapters, analogous to the use of classes and methods
  7500. for the interpreters (section~\ref{sec:extensible-interp}).
  7501. We separate the type checker for the \LangVar{} subset into its own
  7502. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7503. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7504. from the type checker for \LangVar{}. These type checkers are in the
  7505. files
  7506. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7507. and
  7508. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7509. of the support code.
  7510. %
  7511. Each type checker is a structurally recursive function over the AST.
  7512. Given an input expression \code{e}, the type checker either signals an
  7513. error or returns \racket{an expression and its type.}\python{its type.}
  7514. %
  7515. \racket{It returns an expression because there are situations in which
  7516. we want to change or update the expression.}
  7517. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7518. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7519. constant is \INTTY{}. To handle variables, the type checker uses the
  7520. environment \code{env} to map variables to types.
  7521. %
  7522. \racket{Consider the case for \key{let}. We type check the
  7523. initializing expression to obtain its type \key{T} and then
  7524. associate type \code{T} with the variable \code{x} in the
  7525. environment used to type check the body of the \key{let}. Thus,
  7526. when the type checker encounters a use of variable \code{x}, it can
  7527. find its type in the environment.}
  7528. %
  7529. \python{Consider the case for assignment. We type check the
  7530. initializing expression to obtain its type \key{t}. If the variable
  7531. \code{id} is already in the environment because there was a
  7532. prior assignment, we check that this initializer has the same type
  7533. as the prior one. If this is the first assignment to the variable,
  7534. we associate type \code{t} with the variable \code{id} in the
  7535. environment. Thus, when the type checker encounters a use of
  7536. variable \code{x}, it can find its type in the environment.}
  7537. %
  7538. \racket{Regarding primitive operators, we recursively analyze the
  7539. arguments and then invoke \code{type\_check\_op} to check whether
  7540. the argument types are allowed.}
  7541. %
  7542. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7543. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7544. \racket{Several auxiliary methods are used in the type checker. The
  7545. method \code{operator-types} defines a dictionary that maps the
  7546. operator names to their parameter and return types. The
  7547. \code{type-equal?} method determines whether two types are equal,
  7548. which for now simply dispatches to \code{equal?} (deep
  7549. equality). The \code{check-type-equal?} method triggers an error if
  7550. the two types are not equal. The \code{type-check-op} method looks
  7551. up the operator in the \code{operator-types} dictionary and then
  7552. checks whether the argument types are equal to the parameter types.
  7553. The result is the return type of the operator.}
  7554. %
  7555. \python{The auxiliary method \code{check\_type\_equal} triggers
  7556. an error if the two types are not equal.}
  7557. \begin{figure}[tbp]
  7558. \begin{tcolorbox}[colback=white]
  7559. {\if\edition\racketEd
  7560. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7561. (define type-check-Lvar-class
  7562. (class object%
  7563. (super-new)
  7564. (define/public (operator-types)
  7565. '((+ . ((Integer Integer) . Integer))
  7566. (- . ((Integer Integer) . Integer))
  7567. (read . (() . Integer))))
  7568. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7569. (define/public (check-type-equal? t1 t2 e)
  7570. (unless (type-equal? t1 t2)
  7571. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7572. (define/public (type-check-op op arg-types e)
  7573. (match (dict-ref (operator-types) op)
  7574. [`(,param-types . ,return-type)
  7575. (for ([at arg-types] [pt param-types])
  7576. (check-type-equal? at pt e))
  7577. return-type]
  7578. [else (error 'type-check-op "unrecognized ~a" op)]))
  7579. (define/public (type-check-exp env)
  7580. (lambda (e)
  7581. (match e
  7582. [(Int n) (values (Int n) 'Integer)]
  7583. [(Var x) (values (Var x) (dict-ref env x))]
  7584. [(Let x e body)
  7585. (define-values (e^ Te) ((type-check-exp env) e))
  7586. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7587. (values (Let x e^ b) Tb)]
  7588. [(Prim op es)
  7589. (define-values (new-es ts)
  7590. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7591. (values (Prim op new-es) (type-check-op op ts e))]
  7592. [else (error 'type-check-exp "couldn't match" e)])))
  7593. (define/public (type-check-program e)
  7594. (match e
  7595. [(Program info body)
  7596. (define-values (body^ Tb) ((type-check-exp '()) body))
  7597. (check-type-equal? Tb 'Integer body)
  7598. (Program info body^)]
  7599. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7600. ))
  7601. (define (type-check-Lvar p)
  7602. (send (new type-check-Lvar-class) type-check-program p))
  7603. \end{lstlisting}
  7604. \fi}
  7605. {\if\edition\pythonEd\pythonColor
  7606. \begin{lstlisting}[escapechar=`]
  7607. class TypeCheckLvar:
  7608. def check_type_equal(self, t1, t2, e):
  7609. if t1 != t2:
  7610. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7611. raise Exception(msg)
  7612. def type_check_exp(self, e, env):
  7613. match e:
  7614. case BinOp(left, (Add() | Sub()), right):
  7615. l = self.type_check_exp(left, env)
  7616. check_type_equal(l, int, left)
  7617. r = self.type_check_exp(right, env)
  7618. check_type_equal(r, int, right)
  7619. return int
  7620. case UnaryOp(USub(), v):
  7621. t = self.type_check_exp(v, env)
  7622. check_type_equal(t, int, v)
  7623. return int
  7624. case Name(id):
  7625. return env[id]
  7626. case Constant(value) if isinstance(value, int):
  7627. return int
  7628. case Call(Name('input_int'), []):
  7629. return int
  7630. def type_check_stmts(self, ss, env):
  7631. if len(ss) == 0:
  7632. return
  7633. match ss[0]:
  7634. case Assign([Name(id)], value):
  7635. t = self.type_check_exp(value, env)
  7636. if id in env:
  7637. check_type_equal(env[id], t, value)
  7638. else:
  7639. env[id] = t
  7640. return self.type_check_stmts(ss[1:], env)
  7641. case Expr(Call(Name('print'), [arg])):
  7642. t = self.type_check_exp(arg, env)
  7643. check_type_equal(t, int, arg)
  7644. return self.type_check_stmts(ss[1:], env)
  7645. case Expr(value):
  7646. self.type_check_exp(value, env)
  7647. return self.type_check_stmts(ss[1:], env)
  7648. def type_check_P(self, p):
  7649. match p:
  7650. case Module(body):
  7651. self.type_check_stmts(body, {})
  7652. \end{lstlisting}
  7653. \fi}
  7654. \end{tcolorbox}
  7655. \caption{Type checker for the \LangVar{} language.}
  7656. \label{fig:type-check-Lvar}
  7657. \end{figure}
  7658. \begin{figure}[tbp]
  7659. \begin{tcolorbox}[colback=white]
  7660. {\if\edition\racketEd
  7661. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7662. (define type-check-Lif-class
  7663. (class type-check-Lvar-class
  7664. (super-new)
  7665. (inherit check-type-equal?)
  7666. (define/override (operator-types)
  7667. (append '((and . ((Boolean Boolean) . Boolean))
  7668. (or . ((Boolean Boolean) . Boolean))
  7669. (< . ((Integer Integer) . Boolean))
  7670. (<= . ((Integer Integer) . Boolean))
  7671. (> . ((Integer Integer) . Boolean))
  7672. (>= . ((Integer Integer) . Boolean))
  7673. (not . ((Boolean) . Boolean)))
  7674. (super operator-types)))
  7675. (define/override (type-check-exp env)
  7676. (lambda (e)
  7677. (match e
  7678. [(Bool b) (values (Bool b) 'Boolean)]
  7679. [(Prim 'eq? (list e1 e2))
  7680. (define-values (e1^ T1) ((type-check-exp env) e1))
  7681. (define-values (e2^ T2) ((type-check-exp env) e2))
  7682. (check-type-equal? T1 T2 e)
  7683. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7684. [(If cnd thn els)
  7685. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7686. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7687. (define-values (els^ Te) ((type-check-exp env) els))
  7688. (check-type-equal? Tc 'Boolean e)
  7689. (check-type-equal? Tt Te e)
  7690. (values (If cnd^ thn^ els^) Te)]
  7691. [else ((super type-check-exp env) e)])))
  7692. ))
  7693. (define (type-check-Lif p)
  7694. (send (new type-check-Lif-class) type-check-program p))
  7695. \end{lstlisting}
  7696. \fi}
  7697. {\if\edition\pythonEd\pythonColor
  7698. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7699. class TypeCheckLif(TypeCheckLvar):
  7700. def type_check_exp(self, e, env):
  7701. match e:
  7702. case Constant(value) if isinstance(value, bool):
  7703. return bool
  7704. case BinOp(left, Sub(), right):
  7705. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7706. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7707. return int
  7708. case UnaryOp(Not(), v):
  7709. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7710. return bool
  7711. case BoolOp(op, values):
  7712. left = values[0] ; right = values[1]
  7713. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7714. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7715. return bool
  7716. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7717. or isinstance(cmp, NotEq):
  7718. l = self.type_check_exp(left, env)
  7719. r = self.type_check_exp(right, env)
  7720. check_type_equal(l, r, e)
  7721. return bool
  7722. case Compare(left, [cmp], [right]):
  7723. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7724. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7725. return bool
  7726. case IfExp(test, body, orelse):
  7727. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7728. b = self.type_check_exp(body, env)
  7729. o = self.type_check_exp(orelse, env)
  7730. check_type_equal(b, o, e)
  7731. return b
  7732. case _:
  7733. return super().type_check_exp(e, env)
  7734. def type_check_stmts(self, ss, env):
  7735. if len(ss) == 0:
  7736. return
  7737. match ss[0]:
  7738. case If(test, body, orelse):
  7739. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7740. b = self.type_check_stmts(body, env)
  7741. o = self.type_check_stmts(orelse, env)
  7742. check_type_equal(b, o, ss[0])
  7743. return self.type_check_stmts(ss[1:], env)
  7744. case _:
  7745. return super().type_check_stmts(ss, env)
  7746. \end{lstlisting}
  7747. \fi}
  7748. \end{tcolorbox}
  7749. \caption{Type checker for the \LangIf{} language.}
  7750. \label{fig:type-check-Lif}
  7751. \end{figure}
  7752. The definition of the type checker for \LangIf{} is shown in
  7753. figure~\ref{fig:type-check-Lif}.
  7754. %
  7755. The type of a Boolean constant is \BOOLTY{}.
  7756. %
  7757. \racket{The \code{operator-types} function adds dictionary entries for
  7758. the new operators.}
  7759. %
  7760. \python{The logical \code{not} operator requires its argument to be a
  7761. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7762. and logical \code{or} operators.}
  7763. %
  7764. The equality operator requires the two arguments to have the same type,
  7765. and therefore we handle it separately from the other operators.
  7766. %
  7767. \python{The other comparisons (less-than, etc.) require their
  7768. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7769. %
  7770. The condition of an \code{if} must
  7771. be of \BOOLTY{} type, and the two branches must have the same type.
  7772. \begin{exercise}\normalfont\normalsize
  7773. Create ten new test programs in \LangIf{}. Half the programs should
  7774. have a type error.
  7775. \racket{For those programs, create an empty file with the
  7776. same base name and with file extension \code{.tyerr}. For example, if
  7777. the test \code{cond\_test\_14.rkt}
  7778. is expected to error, then create
  7779. an empty file named \code{cond\_test\_14.tyerr}.
  7780. This indicates to \code{interp-tests} and
  7781. \code{compiler-tests} that a type error is expected.}
  7782. %
  7783. The other half of the test programs should not have type errors.
  7784. %
  7785. \racket{In the \code{run-tests.rkt} script, change the second argument
  7786. of \code{interp-tests} and \code{compiler-tests} to
  7787. \code{type-check-Lif}, which causes the type checker to run prior to
  7788. the compiler passes. Temporarily change the \code{passes} to an
  7789. empty list and run the script, thereby checking that the new test
  7790. programs either type check or do not, as intended.}
  7791. %
  7792. Run the test script to check that these test programs type check as
  7793. expected.
  7794. \end{exercise}
  7795. \clearpage
  7796. \section{The \LangCIf{} Intermediate Language}
  7797. \label{sec:Cif}
  7798. {\if\edition\racketEd
  7799. %
  7800. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7801. comparison operators to the \Exp{} nonterminal and the literals
  7802. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7803. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7804. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7805. comparison operation and the branches are \code{goto} statements,
  7806. making it straightforward to compile \code{if} statements to x86. The
  7807. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7808. expressions. A \code{goto} statement transfers control to the $\Tail$
  7809. expression corresponding to its label.
  7810. %
  7811. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7812. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7813. defines its abstract syntax.
  7814. %
  7815. \fi}
  7816. %
  7817. {\if\edition\pythonEd\pythonColor
  7818. %
  7819. The output of \key{explicate\_control} is a language similar to the
  7820. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7821. \code{goto} statements, so we name it \LangCIf{}.
  7822. %
  7823. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7824. the arguments of operators are restricted to atomic expressions. The
  7825. \LangCIf{} language does not include \code{if} expressions, but it does
  7826. include a restricted form of \code{if} statement. The condition must be
  7827. a comparison, and the two branches may contain only \code{goto}
  7828. statements. These restrictions make it easier to translate \code{if}
  7829. statements to x86. The \LangCIf{} language also adds a \code{return}
  7830. statement to finish the program with a specified value.
  7831. %
  7832. The \key{CProgram} construct contains a dictionary mapping labels to
  7833. lists of statements that end with a \emph{tail} statement, which is
  7834. either a \code{return} statement, a \code{goto}, or an
  7835. \code{if} statement.
  7836. %
  7837. A \code{goto} transfers control to the sequence of statements
  7838. associated with its label.
  7839. %
  7840. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7841. and figure~\ref{fig:c1-syntax} shows its
  7842. abstract syntax.
  7843. %
  7844. \fi}
  7845. %
  7846. \newcommand{\CifGrammarRacket}{
  7847. \begin{array}{lcl}
  7848. \Atm &::=& \itm{bool} \\
  7849. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7850. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7851. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7852. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7853. \end{array}
  7854. }
  7855. \newcommand{\CifASTRacket}{
  7856. \begin{array}{lcl}
  7857. \Atm &::=& \BOOL{\itm{bool}} \\
  7858. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7859. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7860. \Tail &::= & \GOTO{\itm{label}} \\
  7861. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7862. \end{array}
  7863. }
  7864. \newcommand{\CifGrammarPython}{
  7865. \begin{array}{lcl}
  7866. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7867. \Exp &::= & \Atm \MID \CREAD{}
  7868. \MID \CUNIOP{\key{-}}{\Atm}
  7869. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7870. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7871. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7872. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7873. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7874. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7875. \end{array}
  7876. }
  7877. \newcommand{\CifASTPython}{
  7878. \begin{array}{lcl}
  7879. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7880. \Exp &::= & \Atm \MID \READ{}
  7881. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7882. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7883. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7884. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7885. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7886. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7887. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7888. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7889. \end{array}
  7890. }
  7891. \begin{figure}[tbp]
  7892. \begin{tcolorbox}[colback=white]
  7893. \small
  7894. {\if\edition\racketEd
  7895. \[
  7896. \begin{array}{l}
  7897. \gray{\CvarGrammarRacket} \\ \hline
  7898. \CifGrammarRacket \\
  7899. \begin{array}{lcl}
  7900. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7901. \end{array}
  7902. \end{array}
  7903. \]
  7904. \fi}
  7905. {\if\edition\pythonEd\pythonColor
  7906. \[
  7907. \begin{array}{l}
  7908. \CifGrammarPython \\
  7909. \begin{array}{lcl}
  7910. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7911. \end{array}
  7912. \end{array}
  7913. \]
  7914. \fi}
  7915. \end{tcolorbox}
  7916. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7917. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7918. \label{fig:c1-concrete-syntax}
  7919. \index{subject}{Cif@\LangCIf{} concrete syntax}
  7920. \end{figure}
  7921. \begin{figure}[tp]
  7922. \begin{tcolorbox}[colback=white]
  7923. \small
  7924. {\if\edition\racketEd
  7925. \[
  7926. \begin{array}{l}
  7927. \gray{\CvarASTRacket} \\ \hline
  7928. \CifASTRacket \\
  7929. \begin{array}{lcl}
  7930. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7931. \end{array}
  7932. \end{array}
  7933. \]
  7934. \fi}
  7935. {\if\edition\pythonEd\pythonColor
  7936. \[
  7937. \begin{array}{l}
  7938. \CifASTPython \\
  7939. \begin{array}{lcl}
  7940. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7941. \end{array}
  7942. \end{array}
  7943. \]
  7944. \fi}
  7945. \end{tcolorbox}
  7946. \racket{
  7947. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7948. }
  7949. \index{subject}{Goto@\texttt{Goto}}
  7950. \index{subject}{Return@\texttt{Return}}
  7951. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7952. (figure~\ref{fig:c0-syntax})}.}
  7953. \label{fig:c1-syntax}
  7954. \index{subject}{Cif@\LangCIf{} abstract syntax}
  7955. \end{figure}
  7956. \section{The \LangXIf{} Language}
  7957. \label{sec:x86-if}
  7958. \index{subject}{x86}
  7959. To implement Booleans, the new logical operations, the
  7960. comparison operations, and the \key{if} expression\python{ and
  7961. statement}, we delve further into the x86
  7962. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7963. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7964. subset of x86, which includes instructions for logical operations,
  7965. comparisons, and \racket{conditional} jumps.
  7966. %
  7967. \python{The abstract syntax for an \LangXIf{} program contains a
  7968. dictionary mapping labels to sequences of instructions, each of
  7969. which we refer to as a \emph{basic block}\index{subject}{basic
  7970. block}.}
  7971. As x86 does not provide direct support for Booleans, we take the usual
  7972. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7973. \code{False} as $0$.
  7974. Furthermore, x86 does not provide an instruction that directly
  7975. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7976. However, the \code{xorq} instruction can be used to encode \code{not}.
  7977. The \key{xorq} instruction takes two arguments, performs a pairwise
  7978. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7979. and writes the results into its second argument. Recall the following
  7980. truth table for exclusive-or:
  7981. \begin{center}
  7982. \begin{tabular}{l|cc}
  7983. & 0 & 1 \\ \hline
  7984. 0 & 0 & 1 \\
  7985. 1 & 1 & 0
  7986. \end{tabular}
  7987. \end{center}
  7988. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7989. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7990. for the bit $1$, the result is the opposite of the second bit. Thus,
  7991. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7992. the first argument, as follows, where $\Arg$ is the translation of
  7993. $\Atm$ to x86:
  7994. \[
  7995. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7996. \qquad\Rightarrow\qquad
  7997. \begin{array}{l}
  7998. \key{movq}~ \Arg\key{,} \Var\\
  7999. \key{xorq}~ \key{\$1,} \Var
  8000. \end{array}
  8001. \]
  8002. \newcommand{\GrammarXIfRacket}{
  8003. \begin{array}{lcl}
  8004. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8005. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8006. \Arg &::=& \key{\%}\itm{bytereg}\\
  8007. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8008. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8009. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8010. \MID \key{set}cc~\Arg
  8011. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8012. &\MID& \key{j}cc~\itm{label} \\
  8013. \end{array}
  8014. }
  8015. \newcommand{\GrammarXIfPython}{
  8016. \begin{array}{lcl}
  8017. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8018. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8019. \Arg &::=& \key{\%}\itm{bytereg}\\
  8020. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8021. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8022. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8023. \MID \key{set}cc~\Arg
  8024. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8025. &\MID& \key{jmp}\,\itm{label} \MID \key{j}cc~\itm{label}
  8026. \MID \itm{label}\key{:}\; \Instr
  8027. \end{array}
  8028. }
  8029. \begin{figure}[tp]
  8030. \begin{tcolorbox}[colback=white]
  8031. {\if\edition\racketEd
  8032. \[
  8033. \begin{array}{l}
  8034. \gray{\GrammarXIntRacket} \\ \hline
  8035. \GrammarXIfRacket \\
  8036. \begin{array}{lcl}
  8037. \LangXIfM{} &::= & \key{.globl main} \\
  8038. & & \key{main:} \; \Instr\ldots
  8039. \end{array}
  8040. \end{array}
  8041. \]
  8042. \fi}
  8043. {\if\edition\pythonEd
  8044. \[
  8045. \begin{array}{l}
  8046. \gray{\GrammarXIntPython} \\ \hline
  8047. \GrammarXIfPython \\
  8048. \begin{array}{lcl}
  8049. \LangXIfM{} &::= & \key{.globl main} \\
  8050. & & \key{main:} \; \Instr\ldots
  8051. \end{array}
  8052. \end{array}
  8053. \]
  8054. \fi}
  8055. \end{tcolorbox}
  8056. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  8057. \label{fig:x86-1-concrete}
  8058. \index{subject}{x86if@\LangXIf{} concrete syntax}
  8059. \end{figure}
  8060. \newcommand{\ASTXIfRacket}{
  8061. \begin{array}{lcl}
  8062. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8063. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8064. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8065. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8066. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8067. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8068. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8069. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8070. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8071. \end{array}
  8072. }
  8073. \newcommand{\ASTXIfPython}{
  8074. \begin{array}{lcl}
  8075. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8076. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8077. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8078. \MID \BYTEREG{\itm{bytereg}} \\
  8079. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8080. \Instr &::=& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8081. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8082. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8083. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8084. &\MID& \python{\JMP{\itm{label}}} \MID \JMPIF{\itm{cc}}{\itm{label}}
  8085. \end{array}
  8086. }
  8087. \begin{figure}[tp]
  8088. \begin{tcolorbox}[colback=white]
  8089. \small
  8090. {\if\edition\racketEd
  8091. \[\arraycolsep=3pt
  8092. \begin{array}{l}
  8093. \gray{\ASTXIntRacket} \\ \hline
  8094. \ASTXIfRacket \\
  8095. \begin{array}{lcl}
  8096. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8097. \end{array}
  8098. \end{array}
  8099. \]
  8100. \fi}
  8101. %
  8102. {\if\edition\pythonEd\pythonColor
  8103. \[
  8104. \begin{array}{l}
  8105. \gray{\ASTXIntPython} \\ \hline
  8106. \ASTXIfPython \\
  8107. \begin{array}{lcl}
  8108. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8109. \end{array}
  8110. \end{array}
  8111. \]
  8112. \fi}
  8113. \end{tcolorbox}
  8114. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8115. \label{fig:x86-1}
  8116. \index{subject}{x86if@\LangXIf{} abstract syntax}
  8117. \end{figure}
  8118. Next we consider the x86 instructions that are relevant for compiling
  8119. the comparison operations. The \key{cmpq} instruction compares its two
  8120. arguments to determine whether one argument is less than, equal to, or
  8121. greater than the other argument. The \key{cmpq} instruction is unusual
  8122. regarding the order of its arguments and where the result is
  8123. placed. The argument order is backward: if you want to test whether
  8124. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8125. \key{cmpq} is placed in the special EFLAGS register. This register
  8126. cannot be accessed directly, but it can be queried by a number of
  8127. instructions, including the \key{set} instruction. The instruction
  8128. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8129. depending on whether the contents of the EFLAGS register matches the
  8130. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8131. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8132. The \key{set} instruction has a quirk in that its destination argument
  8133. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8134. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8135. register. Thankfully, the \key{movzbq} instruction can be used to
  8136. move from a single-byte register to a normal 64-bit register. The
  8137. abstract syntax for the \code{set} instruction differs from the
  8138. concrete syntax in that it separates the instruction name from the
  8139. condition code.
  8140. \python{The x86 instructions for jumping are relevant to the
  8141. compilation of \key{if} expressions.}
  8142. %
  8143. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8144. counter to the address of the instruction after the specified
  8145. label.}
  8146. %
  8147. \racket{The x86 instruction for conditional jump is relevant to the
  8148. compilation of \key{if} expressions.}
  8149. %
  8150. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8151. counter to point to the instruction after \itm{label}, depending on
  8152. whether the result in the EFLAGS register matches the condition code
  8153. \itm{cc}; otherwise, the jump instruction falls through to the next
  8154. instruction. Like the abstract syntax for \code{set}, the abstract
  8155. syntax for conditional jump separates the instruction name from the
  8156. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8157. corresponds to \code{jle foo}. Because the conditional jump instruction
  8158. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8159. a \key{cmpq} instruction to set the EFLAGS register.
  8160. \section{Shrink the \LangIf{} Language}
  8161. \label{sec:shrink-Lif}
  8162. The \code{shrink} pass translates some of the language features into
  8163. other features, thereby reducing the kinds of expressions in the
  8164. language. For example, the short-circuiting nature of the \code{and}
  8165. and \code{or} logical operators can be expressed using \code{if} as
  8166. follows.
  8167. \begin{align*}
  8168. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8169. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8170. \end{align*}
  8171. By performing these translations in the front end of the compiler,
  8172. subsequent passes of the compiler can be shorter.
  8173. On the other hand, translations sometimes reduce the efficiency of the
  8174. generated code by increasing the number of instructions. For example,
  8175. expressing subtraction in terms of addition and negation
  8176. \[
  8177. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8178. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8179. \]
  8180. produces code with two x86 instructions (\code{negq} and \code{addq})
  8181. instead of just one (\code{subq}). Thus, we do not recommend
  8182. translating subtraction into addition and negation.
  8183. \begin{exercise}\normalfont\normalsize
  8184. %
  8185. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8186. the language by translating them to \code{if} expressions in \LangIf{}.
  8187. %
  8188. Create four test programs that involve these operators.
  8189. %
  8190. {\if\edition\racketEd
  8191. In the \code{run-tests.rkt} script, add the following entry for
  8192. \code{shrink} to the list of passes (it should be the only pass at
  8193. this point).
  8194. \begin{lstlisting}
  8195. (list "shrink" shrink interp_Lif type-check-Lif)
  8196. \end{lstlisting}
  8197. This instructs \code{interp-tests} to run the interpreter
  8198. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8199. output of \code{shrink}.
  8200. \fi}
  8201. %
  8202. Run the script to test your compiler on all the test programs.
  8203. \end{exercise}
  8204. {\if\edition\racketEd
  8205. \section{Uniquify Variables}
  8206. \label{sec:uniquify-Lif}
  8207. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8208. \code{if} expressions.
  8209. \begin{exercise}\normalfont\normalsize
  8210. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8211. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8212. \begin{lstlisting}
  8213. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8214. \end{lstlisting}
  8215. Run the script to test your compiler.
  8216. \end{exercise}
  8217. \fi}
  8218. \section{Remove Complex Operands}
  8219. \label{sec:remove-complex-opera-Lif}
  8220. The output language of \code{remove\_complex\_operands} is
  8221. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8222. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8223. but the \code{if} expression is not. All three subexpressions of an
  8224. \code{if} are allowed to be complex expressions, but the operands of
  8225. the \code{not} operator and comparison operators must be atomic.
  8226. %
  8227. \python{We add a new language form, the \code{Begin} expression, to aid
  8228. in the translation of \code{if} expressions. When we recursively
  8229. process the two branches of the \code{if}, we generate temporary
  8230. variables and their initializing expressions. However, these
  8231. expressions may contain side effects and should be executed only
  8232. when the condition of the \code{if} is true (for the ``then''
  8233. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8234. provides a way to initialize the temporary variables within the two branches
  8235. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8236. form executes the statements $ss$ and then returns the result of
  8237. expression $e$.}
  8238. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8239. the new features in \LangIf{}. In recursively processing
  8240. subexpressions, recall that you should invoke \code{rco\_atom} when
  8241. the output needs to be an \Atm{} (as specified in the grammar for
  8242. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8243. \Exp{}. Regarding \code{if}, it is particularly important
  8244. \emph{not} to replace its condition with a temporary variable, because
  8245. that would interfere with the generation of high-quality output in the
  8246. upcoming \code{explicate\_control} pass.
  8247. \newcommand{\LifMonadASTRacket}{
  8248. \begin{array}{rcl}
  8249. \Atm &::=& \BOOL{\itm{bool}}\\
  8250. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8251. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8252. \MID \IF{\Exp}{\Exp}{\Exp}
  8253. \end{array}
  8254. }
  8255. \newcommand{\LifMonadASTPython}{
  8256. \begin{array}{rcl}
  8257. \Atm &::=& \BOOL{\itm{bool}}\\
  8258. \Exp &::=& \UNIOP{\key{Not()}}{\Atm}
  8259. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8260. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8261. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8262. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8263. \end{array}
  8264. }
  8265. \begin{figure}[tp]
  8266. \centering
  8267. \begin{tcolorbox}[colback=white]
  8268. {\if\edition\racketEd
  8269. \[
  8270. \begin{array}{l}
  8271. \gray{\LvarMonadASTRacket} \\ \hline
  8272. \LifMonadASTRacket \\
  8273. \begin{array}{rcl}
  8274. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8275. \end{array}
  8276. \end{array}
  8277. \]
  8278. \fi}
  8279. {\if\edition\pythonEd\pythonColor
  8280. \[
  8281. \begin{array}{l}
  8282. \gray{\LvarMonadASTPython} \\ \hline
  8283. \LifMonadASTPython \\
  8284. \begin{array}{rcl}
  8285. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8286. \end{array}
  8287. \end{array}
  8288. \]
  8289. \fi}
  8290. \end{tcolorbox}
  8291. \python{\index{subject}{Begin@\texttt{Begin}}}
  8292. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8293. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8294. \label{fig:Lif-anf-syntax}
  8295. \index{subject}{Lifmon@\LangIfANF{} abstract syntax}
  8296. \end{figure}
  8297. \begin{exercise}\normalfont\normalsize
  8298. %
  8299. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8300. and \code{rco\_exp} functions.
  8301. %
  8302. Create three new \LangIf{} programs that exercise the interesting
  8303. code in this pass.
  8304. %
  8305. {\if\edition\racketEd
  8306. In the \code{run-tests.rkt} script, add the following entry to the
  8307. list of \code{passes} and then run the script to test your compiler.
  8308. \begin{lstlisting}
  8309. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8310. \end{lstlisting}
  8311. \fi}
  8312. \end{exercise}
  8313. \section{Explicate Control}
  8314. \label{sec:explicate-control-Lif}
  8315. \racket{Recall that the purpose of \code{explicate\_control} is to
  8316. make the order of evaluation explicit in the syntax of the program.
  8317. With the addition of \key{if}, this becomes more interesting.}
  8318. %
  8319. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8320. %
  8321. The main challenge to overcome is that the condition of an \key{if}
  8322. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8323. condition must be a comparison.
  8324. As a motivating example, consider the following program that has an
  8325. \key{if} expression nested in the condition of another \key{if}:%
  8326. \python{\footnote{Programmers rarely write nested \code{if}
  8327. expressions, but they do write nested expressions involving
  8328. logical \code{and}, which, as we have seen, translates to
  8329. \code{if}.}}
  8330. % cond_test_41.rkt, if_lt_eq.py
  8331. \begin{center}
  8332. \begin{minipage}{0.96\textwidth}
  8333. {\if\edition\racketEd
  8334. \begin{lstlisting}
  8335. (let ([x (read)])
  8336. (let ([y (read)])
  8337. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8338. (+ y 2)
  8339. (+ y 10))))
  8340. \end{lstlisting}
  8341. \fi}
  8342. {\if\edition\pythonEd\pythonColor
  8343. \begin{lstlisting}
  8344. x = input_int()
  8345. y = input_int()
  8346. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8347. \end{lstlisting}
  8348. \fi}
  8349. \end{minipage}
  8350. \end{center}
  8351. %
  8352. The naive way to compile \key{if} and the comparison operations would
  8353. be to handle each of them in isolation, regardless of their context.
  8354. Each comparison would be translated into a \key{cmpq} instruction
  8355. followed by several instructions to move the result from the EFLAGS
  8356. register into a general purpose register or stack location. Each
  8357. \key{if} would be translated into a \key{cmpq} instruction followed by
  8358. a conditional jump. The generated code for the inner \key{if} in this
  8359. example would be as follows:
  8360. \begin{center}
  8361. \begin{minipage}{0.96\textwidth}
  8362. \begin{lstlisting}
  8363. cmpq $1, x
  8364. setl %al
  8365. movzbq %al, tmp
  8366. cmpq $1, tmp
  8367. je then_branch_1
  8368. jmp else_branch_1
  8369. \end{lstlisting}
  8370. \end{minipage}
  8371. \end{center}
  8372. Notice that the three instructions starting with \code{setl} are
  8373. redundant; the conditional jump could come immediately after the first
  8374. \code{cmpq}.
  8375. Our goal is to compile \key{if} expressions so that the relevant
  8376. comparison instruction appears directly before the conditional jump.
  8377. For example, we want to generate the following code for the inner
  8378. \code{if}:
  8379. \begin{center}
  8380. \begin{minipage}{0.96\textwidth}
  8381. \begin{lstlisting}
  8382. cmpq $1, x
  8383. jl then_branch_1
  8384. jmp else_branch_1
  8385. \end{lstlisting}
  8386. \end{minipage}
  8387. \end{center}
  8388. One way to achieve this goal is to reorganize the code at the level of
  8389. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8390. the following code:
  8391. \begin{center}
  8392. \begin{minipage}{0.96\textwidth}
  8393. {\if\edition\racketEd
  8394. \begin{lstlisting}
  8395. (let ([x (read)])
  8396. (let ([y (read)])
  8397. (if (< x 1)
  8398. (if (eq? x 0)
  8399. (+ y 2)
  8400. (+ y 10))
  8401. (if (eq? x 2)
  8402. (+ y 2)
  8403. (+ y 10)))))
  8404. \end{lstlisting}
  8405. \fi}
  8406. {\if\edition\pythonEd\pythonColor
  8407. \begin{lstlisting}
  8408. x = input_int()
  8409. y = input_int()
  8410. print(((y + 2) if x == 0 else (y + 10)) \
  8411. if (x < 1) \
  8412. else ((y + 2) if (x == 2) else (y + 10)))
  8413. \end{lstlisting}
  8414. \fi}
  8415. \end{minipage}
  8416. \end{center}
  8417. Unfortunately, this approach duplicates the two branches from the
  8418. outer \code{if}, and a compiler must never duplicate code! After all,
  8419. the two branches could be very large expressions.
  8420. How can we apply this transformation without duplicating code? In
  8421. other words, how can two different parts of a program refer to one
  8422. piece of code?
  8423. %
  8424. The answer is that we must move away from abstract syntax \emph{trees}
  8425. and instead use \emph{graphs}.
  8426. %
  8427. At the level of x86 assembly, this is straightforward because we can
  8428. label the code for each branch and insert jumps in all the places that
  8429. need to execute the branch. In this way, jump instructions are edges
  8430. in the graph and the basic blocks are the nodes.
  8431. %
  8432. Likewise, our language \LangCIf{} provides the ability to label a
  8433. sequence of statements and to jump to a label via \code{goto}.
  8434. As a preview of what \code{explicate\_control} will do,
  8435. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8436. \code{explicate\_control} on this example. Note how the condition of
  8437. every \code{if} is a comparison operation and that we have not
  8438. duplicated any code but instead have used labels and \code{goto} to
  8439. enable sharing of code.
  8440. \begin{figure}[tbp]
  8441. \begin{tcolorbox}[colback=white]
  8442. {\if\edition\racketEd
  8443. \begin{tabular}{lll}
  8444. \begin{minipage}{0.4\textwidth}
  8445. % cond_test_41.rkt
  8446. \begin{lstlisting}
  8447. (let ([x (read)])
  8448. (let ([y (read)])
  8449. (if (if (< x 1)
  8450. (eq? x 0)
  8451. (eq? x 2))
  8452. (+ y 2)
  8453. (+ y 10))))
  8454. \end{lstlisting}
  8455. \end{minipage}
  8456. &
  8457. $\Rightarrow$
  8458. &
  8459. \begin{minipage}{0.55\textwidth}
  8460. \begin{lstlisting}
  8461. start:
  8462. x = (read);
  8463. y = (read);
  8464. if (< x 1)
  8465. goto block_4;
  8466. else
  8467. goto block_5;
  8468. block_4:
  8469. if (eq? x 0)
  8470. goto block_2;
  8471. else
  8472. goto block_3;
  8473. block_5:
  8474. if (eq? x 2)
  8475. goto block_2;
  8476. else
  8477. goto block_3;
  8478. block_2:
  8479. return (+ y 2);
  8480. block_3:
  8481. return (+ y 10);
  8482. \end{lstlisting}
  8483. \end{minipage}
  8484. \end{tabular}
  8485. \fi}
  8486. {\if\edition\pythonEd\pythonColor
  8487. \begin{tabular}{lll}
  8488. \begin{minipage}{0.4\textwidth}
  8489. % tests/if/if_lt_eq.py
  8490. \begin{lstlisting}
  8491. x = input_int()
  8492. y = input_int()
  8493. print(y + 2 \
  8494. if (x == 0 \
  8495. if x < 1 \
  8496. else x == 2) \
  8497. else y + 10)
  8498. \end{lstlisting}
  8499. \end{minipage}
  8500. &
  8501. $\Rightarrow\qquad$
  8502. &
  8503. \begin{minipage}{0.55\textwidth}
  8504. \begin{lstlisting}
  8505. start:
  8506. x = input_int()
  8507. y = input_int()
  8508. if x < 1:
  8509. goto block_6
  8510. else:
  8511. goto block_7
  8512. block_6:
  8513. if x == 0:
  8514. goto block_4
  8515. else:
  8516. goto block_5
  8517. block_7:
  8518. if x == 2:
  8519. goto block_4
  8520. else:
  8521. goto block_5
  8522. block_4:
  8523. tmp.82 = (y + 2)
  8524. goto block_3
  8525. block_5:
  8526. tmp.82 = (y + 10)
  8527. goto block_3
  8528. block_3:
  8529. print(tmp.82)
  8530. return 0
  8531. \end{lstlisting}
  8532. \end{minipage}
  8533. \end{tabular}
  8534. \fi}
  8535. \end{tcolorbox}
  8536. \caption{Translation from \LangIf{} to \LangCIf{}
  8537. via the \code{explicate\_control}.}
  8538. \label{fig:explicate-control-s1-38}
  8539. \end{figure}
  8540. {\if\edition\racketEd
  8541. %
  8542. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8543. \code{explicate\_control} for \LangVar{} using two recursive
  8544. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8545. former function translates expressions in tail position, whereas the
  8546. latter function translates expressions on the right-hand side of a
  8547. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8548. have a new kind of position to deal with: the predicate position of
  8549. the \key{if}. We need another function, \code{explicate\_pred}, that
  8550. decides how to compile an \key{if} by analyzing its condition. So,
  8551. \code{explicate\_pred} takes an \LangIf{} expression and two
  8552. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8553. and outputs a tail. In the following paragraphs we discuss specific
  8554. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8555. \code{explicate\_pred} functions.
  8556. %
  8557. \fi}
  8558. %
  8559. {\if\edition\pythonEd\pythonColor
  8560. %
  8561. We recommend implementing \code{explicate\_control} using the
  8562. following four auxiliary functions.
  8563. \begin{description}
  8564. \item[\code{explicate\_effect}] generates code for expressions as
  8565. statements, so their result is ignored and only their side effects
  8566. matter.
  8567. \item[\code{explicate\_assign}] generates code for expressions
  8568. on the right-hand side of an assignment.
  8569. \item[\code{explicate\_pred}] generates code for an \code{if}
  8570. expression or statement by analyzing the condition expression.
  8571. \item[\code{explicate\_stmt}] generates code for statements.
  8572. \end{description}
  8573. These four functions should build the dictionary of basic blocks. The
  8574. following auxiliary function \code{create\_block} is used to create a
  8575. new basic block from a list of statements. If the list just contains a
  8576. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8577. \code{create\_block} creates a new basic block and returns a
  8578. \code{goto} to its label.
  8579. \begin{center}
  8580. \begin{minipage}{\textwidth}
  8581. \begin{lstlisting}
  8582. def create_block(stmts, basic_blocks):
  8583. match stmts:
  8584. case [Goto(l)]:
  8585. return stmts
  8586. case _:
  8587. label = label_name(generate_name('block'))
  8588. basic_blocks[label] = stmts
  8589. return [Goto(label)]
  8590. \end{lstlisting}
  8591. \end{minipage}
  8592. \end{center}
  8593. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8594. \code{explicate\_control} pass.
  8595. The \code{explicate\_effect} function has three parameters: (1) the
  8596. expression to be compiled; (2) the already-compiled code for this
  8597. expression's \emph{continuation}, that is, the list of statements that
  8598. should execute after this expression; and (3) the dictionary of
  8599. generated basic blocks. The \code{explicate\_effect} function returns
  8600. a list of \LangCIf{} statements and it may add to the dictionary of
  8601. basic blocks.
  8602. %
  8603. Let's consider a few of the cases for the expression to be compiled.
  8604. If the expression to be compiled is a constant, then it can be
  8605. discarded because it has no side effects. If it's a \CREAD{}, then it
  8606. has a side effect and should be preserved. So the expression should be
  8607. translated into a statement using the \code{Expr} AST class. If the
  8608. expression to be compiled is an \code{if} expression, we translate the
  8609. two branches using \code{explicate\_effect} and then translate the
  8610. condition expression using \code{explicate\_pred}, which generates
  8611. code for the entire \code{if}.
  8612. The \code{explicate\_assign} function has four parameters: (1) the
  8613. right-hand side of the assignment, (2) the left-hand side of the
  8614. assignment (the variable), (3) the continuation, and (4) the dictionary
  8615. of basic blocks. The \code{explicate\_assign} function returns a list
  8616. of \LangCIf{} statements, and it may add to the dictionary of basic
  8617. blocks.
  8618. When the right-hand side is an \code{if} expression, there is some
  8619. work to do. In particular, the two branches should be translated using
  8620. \code{explicate\_assign}, and the condition expression should be
  8621. translated using \code{explicate\_pred}. Otherwise we can simply
  8622. generate an assignment statement, with the given left- and right-hand
  8623. sides, concatenated with its continuation.
  8624. \begin{figure}[tbp]
  8625. \begin{tcolorbox}[colback=white]
  8626. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8627. def explicate_effect(e, cont, basic_blocks):
  8628. match e:
  8629. case IfExp(test, body, orelse):
  8630. ...
  8631. case Call(func, args):
  8632. ...
  8633. case Begin(body, result):
  8634. ...
  8635. case _:
  8636. ...
  8637. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8638. match rhs:
  8639. case IfExp(test, body, orelse):
  8640. ...
  8641. case Begin(body, result):
  8642. ...
  8643. case _:
  8644. return [Assign([lhs], rhs)] + cont
  8645. def explicate_pred(cnd, thn, els, basic_blocks):
  8646. match cnd:
  8647. case Compare(left, [op], [right]):
  8648. goto_thn = create_block(thn, basic_blocks)
  8649. goto_els = create_block(els, basic_blocks)
  8650. return [If(cnd, goto_thn, goto_els)]
  8651. case Constant(True):
  8652. return thn;
  8653. case Constant(False):
  8654. return els;
  8655. case UnaryOp(Not(), operand):
  8656. ...
  8657. case IfExp(test, body, orelse):
  8658. ...
  8659. case Begin(body, result):
  8660. ...
  8661. case _:
  8662. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8663. create_block(els, basic_blocks),
  8664. create_block(thn, basic_blocks))]
  8665. def explicate_stmt(s, cont, basic_blocks):
  8666. match s:
  8667. case Assign([lhs], rhs):
  8668. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8669. case Expr(value):
  8670. return explicate_effect(value, cont, basic_blocks)
  8671. case If(test, body, orelse):
  8672. ...
  8673. def explicate_control(p):
  8674. match p:
  8675. case Module(body):
  8676. new_body = [Return(Constant(0))]
  8677. basic_blocks = {}
  8678. for s in reversed(body):
  8679. new_body = explicate_stmt(s, new_body, basic_blocks)
  8680. basic_blocks[label_name('start')] = new_body
  8681. return CProgram(basic_blocks)
  8682. \end{lstlisting}
  8683. \end{tcolorbox}
  8684. \caption{Skeleton for the \code{explicate\_control} pass.}
  8685. \label{fig:explicate-control-Lif}
  8686. \end{figure}
  8687. \fi}
  8688. {\if\edition\racketEd
  8689. \subsection{Explicate Tail and Assign}
  8690. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8691. additional cases for Boolean constants and \key{if}. The cases for
  8692. \code{if} should recursively compile the two branches using either
  8693. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8694. cases should then invoke \code{explicate\_pred} on the condition
  8695. expression, passing in the generated code for the two branches. For
  8696. example, consider the following program with an \code{if} in tail
  8697. position.
  8698. % cond_test_6.rkt
  8699. \begin{lstlisting}
  8700. (let ([x (read)])
  8701. (if (eq? x 0) 42 777))
  8702. \end{lstlisting}
  8703. The two branches are recursively compiled to return statements. We
  8704. then delegate to \code{explicate\_pred}, passing the condition
  8705. \code{(eq? x 0)} and the two return statements. We return to this
  8706. example shortly when we discuss \code{explicate\_pred}.
  8707. Next let us consider a program with an \code{if} on the right-hand
  8708. side of a \code{let}.
  8709. \begin{lstlisting}
  8710. (let ([y (read)])
  8711. (let ([x (if (eq? y 0) 40 777)])
  8712. (+ x 2)))
  8713. \end{lstlisting}
  8714. Note that the body of the inner \code{let} will have already been
  8715. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8716. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8717. to recursively process both branches of the \code{if}, and we do not
  8718. want to duplicate code, so we generate the following block using an
  8719. auxiliary function named \code{create\_block}, discussed in the next
  8720. section.
  8721. \begin{lstlisting}
  8722. block_6:
  8723. return (+ x 2)
  8724. \end{lstlisting}
  8725. We then use \code{goto block\_6;} as the \code{cont} argument for
  8726. compiling the branches. So the two branches compile to
  8727. \begin{center}
  8728. \begin{minipage}{0.2\textwidth}
  8729. \begin{lstlisting}
  8730. x = 40;
  8731. goto block_6;
  8732. \end{lstlisting}
  8733. \end{minipage}
  8734. \hspace{0.5in} and \hspace{0.5in}
  8735. \begin{minipage}{0.2\textwidth}
  8736. \begin{lstlisting}
  8737. x = 777;
  8738. goto block_6;
  8739. \end{lstlisting}
  8740. \end{minipage}
  8741. \end{center}
  8742. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8743. \code{(eq? y 0)} and the previously presented code for the branches.
  8744. \subsection{Create Block}
  8745. We recommend implementing the \code{create\_block} auxiliary function
  8746. as follows, using a global variable \code{basic-blocks} to store a
  8747. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8748. that \code{create\_block} generates a new label and then associates
  8749. the given \code{tail} with the new label in the \code{basic-blocks}
  8750. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8751. new label. However, if the given \code{tail} is already a \code{Goto},
  8752. then there is no need to generate a new label and entry in
  8753. \code{basic-blocks}; we can simply return that \code{Goto}.
  8754. %
  8755. \begin{lstlisting}
  8756. (define (create_block tail)
  8757. (match tail
  8758. [(Goto label) (Goto label)]
  8759. [else
  8760. (let ([label (gensym 'block)])
  8761. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8762. (Goto label))]))
  8763. \end{lstlisting}
  8764. \fi}
  8765. {\if\edition\racketEd
  8766. \subsection{Explicate Predicate}
  8767. The skeleton for the \code{explicate\_pred} function is given in
  8768. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8769. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8770. the code generated by explicate for the \emph{then} branch; and (3)
  8771. \code{els}, the code generated by explicate for the \emph{else}
  8772. branch. The \code{explicate\_pred} function should match on
  8773. \code{cnd} with a case for every kind of expression that can have type
  8774. \BOOLTY{}.
  8775. \begin{figure}[tbp]
  8776. \begin{tcolorbox}[colback=white]
  8777. \begin{lstlisting}
  8778. (define (explicate_pred cnd thn els)
  8779. (match cnd
  8780. [(Var x) ___]
  8781. [(Let x rhs body) ___]
  8782. [(Prim 'not (list e)) ___]
  8783. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8784. (IfStmt (Prim op es) (create_block thn)
  8785. (create_block els))]
  8786. [(Bool b) (if b thn els)]
  8787. [(If cnd^ thn^ els^) ___]
  8788. [else (error "explicate_pred unhandled case" cnd)]))
  8789. \end{lstlisting}
  8790. \end{tcolorbox}
  8791. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8792. \label{fig:explicate-pred}
  8793. \end{figure}
  8794. \fi}
  8795. %
  8796. {\if\edition\pythonEd\pythonColor
  8797. The \code{explicate\_pred} function has four parameters: (1) the
  8798. condition expression, (2) the generated statements for the \emph{then}
  8799. branch, (3) the generated statements for the \emph{else} branch, and
  8800. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8801. function returns a list of statements, and it adds to the dictionary
  8802. of basic blocks.
  8803. \fi}
  8804. Consider the case for comparison operators. We translate the
  8805. comparison to an \code{if} statement whose branches are \code{goto}
  8806. statements created by applying \code{create\_block} to the \code{thn}
  8807. and \code{els} parameters. Let us illustrate this translation by
  8808. returning to the program with an \code{if} expression in tail
  8809. position, shown next. We invoke \code{explicate\_pred} on its
  8810. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8811. %
  8812. {\if\edition\racketEd
  8813. \begin{lstlisting}
  8814. (let ([x (read)])
  8815. (if (eq? x 0) 42 777))
  8816. \end{lstlisting}
  8817. \fi}
  8818. %
  8819. {\if\edition\pythonEd\pythonColor
  8820. \begin{lstlisting}
  8821. x = input_int()
  8822. 42 if x == 0 else 777
  8823. \end{lstlisting}
  8824. \fi}
  8825. %
  8826. \noindent The two branches \code{42} and \code{777} were already
  8827. compiled to \code{return} statements, from which we now create the
  8828. following blocks:
  8829. %
  8830. \begin{center}
  8831. \begin{minipage}{\textwidth}
  8832. \begin{lstlisting}
  8833. block_1:
  8834. return 42;
  8835. block_2:
  8836. return 777;
  8837. \end{lstlisting}
  8838. \end{minipage}
  8839. \end{center}
  8840. %
  8841. After that, \code{explicate\_pred} compiles the comparison
  8842. \racket{\code{(eq? x 0)}}
  8843. \python{\code{x == 0}}
  8844. to the following \code{if} statement:
  8845. %
  8846. {\if\edition\racketEd
  8847. \begin{center}
  8848. \begin{minipage}{\textwidth}
  8849. \begin{lstlisting}
  8850. if (eq? x 0)
  8851. goto block_1;
  8852. else
  8853. goto block_2;
  8854. \end{lstlisting}
  8855. \end{minipage}
  8856. \end{center}
  8857. \fi}
  8858. {\if\edition\pythonEd\pythonColor
  8859. \begin{center}
  8860. \begin{minipage}{\textwidth}
  8861. \begin{lstlisting}
  8862. if x == 0:
  8863. goto block_1;
  8864. else
  8865. goto block_2;
  8866. \end{lstlisting}
  8867. \end{minipage}
  8868. \end{center}
  8869. \fi}
  8870. Next consider the case for Boolean constants. We perform a kind of
  8871. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8872. either the \code{thn} or \code{els} parameter, depending on whether the
  8873. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8874. following program:
  8875. {\if\edition\racketEd
  8876. \begin{lstlisting}
  8877. (if #t 42 777)
  8878. \end{lstlisting}
  8879. \fi}
  8880. {\if\edition\pythonEd\pythonColor
  8881. \begin{lstlisting}
  8882. 42 if True else 777
  8883. \end{lstlisting}
  8884. \fi}
  8885. %
  8886. \noindent Again, the two branches \code{42} and \code{777} were
  8887. compiled to \code{return} statements, so \code{explicate\_pred}
  8888. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8889. code for the \emph{then} branch.
  8890. \begin{lstlisting}
  8891. return 42;
  8892. \end{lstlisting}
  8893. This case demonstrates that we sometimes discard the \code{thn} or
  8894. \code{els} blocks that are input to \code{explicate\_pred}.
  8895. The case for \key{if} expressions in \code{explicate\_pred} is
  8896. particularly illuminating because it deals with the challenges
  8897. discussed previously regarding nested \key{if} expressions
  8898. (figure~\ref{fig:explicate-control-s1-38}). The
  8899. \racket{\lstinline{thn^}}\python{\code{body}} and
  8900. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8901. \key{if} inherit their context from the current one, that is,
  8902. predicate context. So, you should recursively apply
  8903. \code{explicate\_pred} to the
  8904. \racket{\lstinline{thn^}}\python{\code{body}} and
  8905. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8906. those recursive calls, pass \code{thn} and \code{els} as the extra
  8907. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8908. inside each recursive call. As discussed previously, to avoid
  8909. duplicating code, we need to add them to the dictionary of basic
  8910. blocks so that we can instead refer to them by name and execute them
  8911. with a \key{goto}.
  8912. {\if\edition\pythonEd\pythonColor
  8913. %
  8914. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8915. three parameters: (1) the statement to be compiled, (2) the code for its
  8916. continuation, and (3) the dictionary of basic blocks. The
  8917. \code{explicate\_stmt} returns a list of statements, and it may add to
  8918. the dictionary of basic blocks. The cases for assignment and an
  8919. expression-statement are given in full in the skeleton code: they
  8920. simply dispatch to \code{explicate\_assign} and
  8921. \code{explicate\_effect}, respectively. The case for \code{if}
  8922. statements is not given; it is similar to the case for \code{if}
  8923. expressions.
  8924. The \code{explicate\_control} function itself is given in
  8925. figure~\ref{fig:explicate-control-Lif}. It applies
  8926. \code{explicate\_stmt} to each statement in the program, from back to
  8927. front. Thus, the result so far, stored in \code{new\_body}, can be
  8928. used as the continuation parameter in the next call to
  8929. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8930. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8931. the dictionary of basic blocks, labeling it the ``start'' block.
  8932. %
  8933. \fi}
  8934. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8935. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8936. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8937. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8938. %% results from the two recursive calls. We complete the case for
  8939. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8940. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8941. %% the result $B_5$.
  8942. %% \[
  8943. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8944. %% \quad\Rightarrow\quad
  8945. %% B_5
  8946. %% \]
  8947. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8948. %% inherit the current context, so they are in tail position. Thus, the
  8949. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8950. %% \code{explicate\_tail}.
  8951. %% %
  8952. %% We need to pass $B_0$ as the accumulator argument for both of these
  8953. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8954. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8955. %% to the control-flow graph and obtain a promised goto $G_0$.
  8956. %% %
  8957. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8958. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8959. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8960. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8961. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8962. %% \[
  8963. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8964. %% \]
  8965. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8966. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8967. %% should not be confused with the labels for the blocks that appear in
  8968. %% the generated code. We initially construct unlabeled blocks; we only
  8969. %% attach labels to blocks when we add them to the control-flow graph, as
  8970. %% we see in the next case.
  8971. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8972. %% function. The context of the \key{if} is an assignment to some
  8973. %% variable $x$ and then the control continues to some promised block
  8974. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8975. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8976. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8977. %% branches of the \key{if} inherit the current context, so they are in
  8978. %% assignment positions. Let $B_2$ be the result of applying
  8979. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8980. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8981. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8982. %% the result of applying \code{explicate\_pred} to the predicate
  8983. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8984. %% translates to the promise $B_4$.
  8985. %% \[
  8986. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8987. %% \]
  8988. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8989. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8990. \code{remove\_complex\_operands} pass and then the
  8991. \code{explicate\_control} pass on the example program. We walk through
  8992. the output program.
  8993. %
  8994. Following the order of evaluation in the output of
  8995. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8996. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8997. in the predicate of the inner \key{if}. In the output of
  8998. \code{explicate\_control}, in the
  8999. block labeled \code{start}, two assignment statements are followed by an
  9000. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  9001. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  9002. The blocks associated with those labels contain the
  9003. translations of the code
  9004. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9005. and
  9006. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  9007. respectively. In particular, we start
  9008. \racket{\code{block\_4}}\python{\code{block\_6}}
  9009. with the comparison
  9010. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9011. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  9012. or \racket{\code{block\_3}}\python{\code{block\_5}},
  9013. which correspond to the two branches of the outer \key{if}, that is,
  9014. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  9015. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  9016. %
  9017. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  9018. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  9019. %
  9020. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  9021. {\if\edition\racketEd
  9022. \subsection{Interactions between Explicate and Shrink}
  9023. The way in which the \code{shrink} pass transforms logical operations
  9024. such as \code{and} and \code{or} can impact the quality of code
  9025. generated by \code{explicate\_control}. For example, consider the
  9026. following program:
  9027. % cond_test_21.rkt, and_eq_input.py
  9028. \begin{lstlisting}
  9029. (if (and (eq? (read) 0) (eq? (read) 1))
  9030. 0
  9031. 42)
  9032. \end{lstlisting}
  9033. The \code{and} operation should transform into something that the
  9034. \code{explicate\_pred} function can analyze and descend through to
  9035. reach the underlying \code{eq?} conditions. Ideally, for this program
  9036. your \code{explicate\_control} pass should generate code similar to
  9037. the following:
  9038. \begin{center}
  9039. \begin{minipage}{\textwidth}
  9040. \begin{lstlisting}
  9041. start:
  9042. tmp1 = (read);
  9043. if (eq? tmp1 0) goto block40;
  9044. else goto block39;
  9045. block40:
  9046. tmp2 = (read);
  9047. if (eq? tmp2 1) goto block38;
  9048. else goto block39;
  9049. block38:
  9050. return 0;
  9051. block39:
  9052. return 42;
  9053. \end{lstlisting}
  9054. \end{minipage}
  9055. \end{center}
  9056. \fi}
  9057. \begin{exercise}\normalfont\normalsize
  9058. \racket{
  9059. Implement the pass \code{explicate\_control} by adding the cases for
  9060. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9061. \code{explicate\_assign} functions. Implement the auxiliary function
  9062. \code{explicate\_pred} for predicate contexts.}
  9063. \python{Implement \code{explicate\_control} pass with its
  9064. four auxiliary functions.}
  9065. %
  9066. Create test cases that exercise all the new cases in the code for
  9067. this pass.
  9068. %
  9069. {\if\edition\racketEd
  9070. Add the following entry to the list of \code{passes} in
  9071. \code{run-tests.rkt}:
  9072. \begin{lstlisting}
  9073. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9074. \end{lstlisting}
  9075. and then run \code{run-tests.rkt} to test your compiler.
  9076. \fi}
  9077. \end{exercise}
  9078. \section{Select Instructions}
  9079. \label{sec:select-Lif}
  9080. \index{subject}{select instructions}
  9081. The \code{select\_instructions} pass translates \LangCIf{} to
  9082. \LangXIfVar{}.
  9083. %
  9084. \racket{Recall that we implement this pass using three auxiliary
  9085. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9086. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9087. %
  9088. \racket{For $\Atm$, we have new cases for the Booleans.}
  9089. %
  9090. \python{We begin with the Boolean constants.}
  9091. As previously discussed, we encode them as integers.
  9092. \[
  9093. \TRUE{} \quad\Rightarrow\quad \key{1}
  9094. \qquad\qquad
  9095. \FALSE{} \quad\Rightarrow\quad \key{0}
  9096. \]
  9097. For translating statements, we discuss some of the cases. The
  9098. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9099. discussed at the beginning of this section. Given an assignment, if
  9100. the left-hand-side variable is the same as the argument of \code{not},
  9101. then just the \code{xorq} instruction suffices.
  9102. \[
  9103. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9104. \quad\Rightarrow\quad
  9105. \key{xorq}~\key{\$}1\key{,}~\Var
  9106. \]
  9107. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9108. semantics of x86. In the following translation, let $\Arg$ be the
  9109. result of translating $\Atm$ to x86.
  9110. \[
  9111. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9112. \quad\Rightarrow\quad
  9113. \begin{array}{l}
  9114. \key{movq}~\Arg\key{,}~\Var\\
  9115. \key{xorq}~\key{\$}1\key{,}~\Var
  9116. \end{array}
  9117. \]
  9118. Next consider the cases for equality comparisons. Translating this
  9119. operation to x86 is slightly involved due to the unusual nature of the
  9120. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9121. We recommend translating an assignment with an equality on the
  9122. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9123. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9124. \begin{tabular}{lll}
  9125. \begin{minipage}{0.4\textwidth}
  9126. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9127. \end{minipage}
  9128. &
  9129. $\Rightarrow$
  9130. &
  9131. \begin{minipage}{0.4\textwidth}
  9132. \begin{lstlisting}
  9133. cmpq |$\Arg_2$|, |$\Arg_1$|
  9134. sete %al
  9135. movzbq %al, |$\Var$|
  9136. \end{lstlisting}
  9137. \end{minipage}
  9138. \end{tabular} \\
  9139. The translations for the other comparison operators are similar to
  9140. this but use different condition codes for the \code{set} instruction.
  9141. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9142. \key{goto} and \key{if} statements. Both are straightforward to
  9143. translate to x86.}
  9144. %
  9145. A \key{goto} statement becomes a jump instruction.
  9146. \[
  9147. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9148. \]
  9149. %
  9150. An \key{if} statement becomes a compare instruction followed by a
  9151. conditional jump (for the \emph{then} branch), and the fall-through is to
  9152. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9153. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9154. \begin{tabular}{lll}
  9155. \begin{minipage}{0.4\textwidth}
  9156. \begin{lstlisting}
  9157. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9158. goto |$\ell_1$||$\racket{\key{;}}$|
  9159. else|$\python{\key{:}}$|
  9160. goto |$\ell_2$||$\racket{\key{;}}$|
  9161. \end{lstlisting}
  9162. \end{minipage}
  9163. &
  9164. $\Rightarrow$
  9165. &
  9166. \begin{minipage}{0.4\textwidth}
  9167. \begin{lstlisting}
  9168. cmpq |$\Arg_2$|, |$\Arg_1$|
  9169. je |$\ell_1$|
  9170. jmp |$\ell_2$|
  9171. \end{lstlisting}
  9172. \end{minipage}
  9173. \end{tabular} \\
  9174. Again, the translations for the other comparison operators are similar to this
  9175. but use different condition codes for the conditional jump instruction.
  9176. \python{Regarding the \key{return} statement, we recommend treating it
  9177. as an assignment to the \key{rax} register followed by a jump to the
  9178. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9179. \begin{exercise}\normalfont\normalsize
  9180. Expand your \code{select\_instructions} pass to handle the new
  9181. features of the \LangCIf{} language.
  9182. %
  9183. {\if\edition\racketEd
  9184. Add the following entry to the list of \code{passes} in
  9185. \code{run-tests.rkt}
  9186. \begin{lstlisting}
  9187. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9188. \end{lstlisting}
  9189. \fi}
  9190. %
  9191. Run the script to test your compiler on all the test programs.
  9192. \end{exercise}
  9193. \section{Register Allocation}
  9194. \label{sec:register-allocation-Lif}
  9195. \index{subject}{register allocation}
  9196. The changes required for compiling \LangIf{} affect liveness analysis,
  9197. building the interference graph, and assigning homes, but the graph
  9198. coloring algorithm itself does not change.
  9199. \subsection{Liveness Analysis}
  9200. \label{sec:liveness-analysis-Lif}
  9201. \index{subject}{liveness analysis}
  9202. Recall that for \LangVar{} we implemented liveness analysis for a
  9203. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9204. the addition of \key{if} expressions to \LangIf{},
  9205. \code{explicate\_control} produces many basic blocks.
  9206. %% We recommend that you create a new auxiliary function named
  9207. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9208. %% control-flow graph.
  9209. The first question is, in what order should we process the basic blocks?
  9210. Recall that to perform liveness analysis on a basic block we need to
  9211. know the live-after set for the last instruction in the block. If a
  9212. basic block has no successors (i.e., contains no jumps to other
  9213. blocks), then it has an empty live-after set and we can immediately
  9214. apply liveness analysis to it. If a basic block has some successors,
  9215. then we need to complete liveness analysis on those blocks
  9216. first. These ordering constraints are the reverse of a
  9217. \emph{topological order}\index{subject}{topological order} on a graph
  9218. representation of the program. In particular, the \emph{control flow
  9219. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9220. of a program has a node for each basic block and an edge for each jump
  9221. from one block to another. It is straightforward to generate a CFG
  9222. from the dictionary of basic blocks. One then transposes the CFG and
  9223. applies the topological sort algorithm.
  9224. %
  9225. %
  9226. \racket{We recommend using the \code{tsort} and \code{transpose}
  9227. functions of the Racket \code{graph} package to accomplish this.}
  9228. %
  9229. \python{We provide implementations of \code{topological\_sort} and
  9230. \code{transpose} in the file \code{graph.py} of the support code.}
  9231. %
  9232. As an aside, a topological ordering is only guaranteed to exist if the
  9233. graph does not contain any cycles. This is the case for the
  9234. control-flow graphs that we generate from \LangIf{} programs.
  9235. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9236. and learn how to handle cycles in the control-flow graph.
  9237. \racket{You need to construct a directed graph to represent the
  9238. control-flow graph. Do not use the \code{directed-graph} of the
  9239. \code{graph} package because that allows at most one edge
  9240. between each pair of vertices, whereas a control-flow graph may have
  9241. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9242. file in the support code implements a graph representation that
  9243. allows multiple edges between a pair of vertices.}
  9244. {\if\edition\racketEd
  9245. The next question is how to analyze jump instructions. Recall that in
  9246. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9247. \code{label->live} that maps each label to the set of live locations
  9248. at the beginning of its block. We use \code{label->live} to determine
  9249. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9250. that we have many basic blocks, \code{label->live} needs to be updated
  9251. as we process the blocks. In particular, after performing liveness
  9252. analysis on a block, we take the live-before set of its first
  9253. instruction and associate that with the block's label in the
  9254. \code{label->live} alist.
  9255. \fi}
  9256. %
  9257. {\if\edition\pythonEd\pythonColor
  9258. %
  9259. The next question is how to analyze jump instructions. The locations
  9260. that are live before a \code{jmp} should be the locations in
  9261. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9262. maintaining a dictionary named \code{live\_before\_block} that maps each
  9263. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9264. block. After performing liveness analysis on each block, we take the
  9265. live-before set of its first instruction and associate that with the
  9266. block's label in the \code{live\_before\_block} dictionary.
  9267. %
  9268. \fi}
  9269. In \LangXIfVar{} we also have the conditional jump
  9270. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9271. this instruction is particularly interesting because during
  9272. compilation, we do not know which way a conditional jump will go. Thus
  9273. we do not know whether to use the live-before set for the block
  9274. associated with the $\itm{label}$ or the live-before set for the
  9275. following instruction. So we use both, by taking the union of the
  9276. live-before sets from the following instruction and from the mapping
  9277. for $\itm{label}$ in
  9278. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9279. The auxiliary functions for computing the variables in an
  9280. instruction's argument and for computing the variables read-from ($R$)
  9281. or written-to ($W$) by an instruction need to be updated to handle the
  9282. new kinds of arguments and instructions in \LangXIfVar{}.
  9283. \begin{exercise}\normalfont\normalsize
  9284. {\if\edition\racketEd
  9285. %
  9286. Update the \code{uncover\_live} pass to apply liveness analysis to
  9287. every basic block in the program.
  9288. %
  9289. Add the following entry to the list of \code{passes} in the
  9290. \code{run-tests.rkt} script:
  9291. \begin{lstlisting}
  9292. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9293. \end{lstlisting}
  9294. \fi}
  9295. {\if\edition\pythonEd\pythonColor
  9296. %
  9297. Update the \code{uncover\_live} function to perform liveness analysis,
  9298. in reverse topological order, on all the basic blocks in the
  9299. program.
  9300. %
  9301. \fi}
  9302. % Check that the live-after sets that you generate for
  9303. % example X matches the following... -Jeremy
  9304. \end{exercise}
  9305. \subsection{Build the Interference Graph}
  9306. \label{sec:build-interference-Lif}
  9307. Many of the new instructions in \LangXIfVar{} can be handled in the
  9308. same way as the instructions in \LangXVar{}.
  9309. % Thus, if your code was
  9310. % already quite general, it will not need to be changed to handle the
  9311. % new instructions. If your code is not general enough, we recommend that
  9312. % you change your code to be more general. For example, you can factor
  9313. % out the computing of the the read and write sets for each kind of
  9314. % instruction into auxiliary functions.
  9315. %
  9316. Some instructions, such as the \key{movzbq} instruction, require special care,
  9317. similar to the \key{movq} instruction. Refer to rule number 1 in
  9318. section~\ref{sec:build-interference}.
  9319. \begin{exercise}\normalfont\normalsize
  9320. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9321. {\if\edition\racketEd
  9322. Add the following entries to the list of \code{passes} in the
  9323. \code{run-tests.rkt} script:
  9324. \begin{lstlisting}
  9325. (list "build_interference" build_interference interp-pseudo-x86-1)
  9326. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9327. \end{lstlisting}
  9328. \fi}
  9329. % Check that the interference graph that you generate for
  9330. % example X matches the following graph G... -Jeremy
  9331. \end{exercise}
  9332. \section{Patch Instructions}
  9333. The new instructions \key{cmpq} and \key{movzbq} have some special
  9334. restrictions that need to be handled in the \code{patch\_instructions}
  9335. pass.
  9336. %
  9337. The second argument of the \key{cmpq} instruction must not be an
  9338. immediate value (such as an integer). So, if you are comparing two
  9339. immediates, we recommend inserting a \key{movq} instruction to put the
  9340. second argument in \key{rax}. On the other hand, if you implemented
  9341. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9342. update it for \LangIf{} and then this situation would not arise.
  9343. %
  9344. As usual, \key{cmpq} may have at most one memory reference.
  9345. %
  9346. The second argument of the \key{movzbq} must be a register.
  9347. \begin{exercise}\normalfont\normalsize
  9348. %
  9349. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9350. %
  9351. {\if\edition\racketEd
  9352. Add the following entry to the list of \code{passes} in
  9353. \code{run-tests.rkt}, and then run this script to test your compiler.
  9354. \begin{lstlisting}
  9355. (list "patch_instructions" patch_instructions interp-x86-1)
  9356. \end{lstlisting}
  9357. \fi}
  9358. \end{exercise}
  9359. {\if\edition\pythonEd\pythonColor
  9360. \section{Generate Prelude and Conclusion}
  9361. \label{sec:prelude-conclusion-cond}
  9362. The generation of the \code{main} function with its prelude and
  9363. conclusion must change to accommodate how the program now consists of
  9364. one or more basic blocks. After the prelude in \code{main}, jump to
  9365. the \code{start} block. Place the conclusion in a basic block labeled
  9366. with \code{conclusion}.
  9367. \fi}
  9368. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9369. \LangIf{} translated to x86, showing the results of
  9370. \code{explicate\_control}, \code{select\_instructions}, and the final
  9371. x86 assembly.
  9372. \begin{figure}[tbp]
  9373. \begin{tcolorbox}[colback=white]
  9374. {\if\edition\racketEd
  9375. \begin{tabular}{lll}
  9376. \begin{minipage}{0.4\textwidth}
  9377. % cond_test_20.rkt, eq_input.py
  9378. \begin{lstlisting}
  9379. (if (eq? (read) 1) 42 0)
  9380. \end{lstlisting}
  9381. $\Downarrow$
  9382. \begin{lstlisting}
  9383. start:
  9384. tmp7951 = (read);
  9385. if (eq? tmp7951 1)
  9386. goto block7952;
  9387. else
  9388. goto block7953;
  9389. block7952:
  9390. return 42;
  9391. block7953:
  9392. return 0;
  9393. \end{lstlisting}
  9394. $\Downarrow$
  9395. \begin{lstlisting}
  9396. start:
  9397. callq read_int
  9398. movq %rax, tmp7951
  9399. cmpq $1, tmp7951
  9400. je block7952
  9401. jmp block7953
  9402. block7953:
  9403. movq $0, %rax
  9404. jmp conclusion
  9405. block7952:
  9406. movq $42, %rax
  9407. jmp conclusion
  9408. \end{lstlisting}
  9409. \end{minipage}
  9410. &
  9411. $\Rightarrow\qquad$
  9412. \begin{minipage}{0.4\textwidth}
  9413. \begin{lstlisting}
  9414. start:
  9415. callq read_int
  9416. movq %rax, %rcx
  9417. cmpq $1, %rcx
  9418. je block7952
  9419. jmp block7953
  9420. block7953:
  9421. movq $0, %rax
  9422. jmp conclusion
  9423. block7952:
  9424. movq $42, %rax
  9425. jmp conclusion
  9426. .globl main
  9427. main:
  9428. pushq %rbp
  9429. movq %rsp, %rbp
  9430. pushq %r13
  9431. pushq %r12
  9432. pushq %rbx
  9433. pushq %r14
  9434. subq $0, %rsp
  9435. jmp start
  9436. conclusion:
  9437. addq $0, %rsp
  9438. popq %r14
  9439. popq %rbx
  9440. popq %r12
  9441. popq %r13
  9442. popq %rbp
  9443. retq
  9444. \end{lstlisting}
  9445. \end{minipage}
  9446. \end{tabular}
  9447. \fi}
  9448. {\if\edition\pythonEd\pythonColor
  9449. \begin{tabular}{lll}
  9450. \begin{minipage}{0.4\textwidth}
  9451. % cond_test_20.rkt, eq_input.py
  9452. \begin{lstlisting}
  9453. print(42 if input_int() == 1 else 0)
  9454. \end{lstlisting}
  9455. $\Downarrow$
  9456. \begin{lstlisting}
  9457. start:
  9458. tmp_0 = input_int()
  9459. if tmp_0 == 1:
  9460. goto block_3
  9461. else:
  9462. goto block_4
  9463. block_3:
  9464. tmp_1 = 42
  9465. goto block_2
  9466. block_4:
  9467. tmp_1 = 0
  9468. goto block_2
  9469. block_2:
  9470. print(tmp_1)
  9471. return 0
  9472. \end{lstlisting}
  9473. $\Downarrow$
  9474. \begin{lstlisting}
  9475. start:
  9476. callq read_int
  9477. movq %rax, tmp_0
  9478. cmpq 1, tmp_0
  9479. je block_3
  9480. jmp block_4
  9481. block_3:
  9482. movq 42, tmp_1
  9483. jmp block_2
  9484. block_4:
  9485. movq 0, tmp_1
  9486. jmp block_2
  9487. block_2:
  9488. movq tmp_1, %rdi
  9489. callq print_int
  9490. movq 0, %rax
  9491. jmp conclusion
  9492. \end{lstlisting}
  9493. \end{minipage}
  9494. &
  9495. $\Rightarrow\qquad$
  9496. \begin{minipage}{0.4\textwidth}
  9497. \begin{lstlisting}
  9498. .globl main
  9499. main:
  9500. pushq %rbp
  9501. movq %rsp, %rbp
  9502. subq $0, %rsp
  9503. jmp start
  9504. start:
  9505. callq read_int
  9506. movq %rax, %rcx
  9507. cmpq $1, %rcx
  9508. je block_3
  9509. jmp block_4
  9510. block_3:
  9511. movq $42, %rcx
  9512. jmp block_2
  9513. block_4:
  9514. movq $0, %rcx
  9515. jmp block_2
  9516. block_2:
  9517. movq %rcx, %rdi
  9518. callq print_int
  9519. movq $0, %rax
  9520. jmp conclusion
  9521. conclusion:
  9522. addq $0, %rsp
  9523. popq %rbp
  9524. retq
  9525. \end{lstlisting}
  9526. \end{minipage}
  9527. \end{tabular}
  9528. \fi}
  9529. \end{tcolorbox}
  9530. \caption{Example compilation of an \key{if} expression to x86, showing
  9531. the results of \code{explicate\_control},
  9532. \code{select\_instructions}, and the final x86 assembly code. }
  9533. \label{fig:if-example-x86}
  9534. \end{figure}
  9535. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9536. compilation of \LangIf{}.
  9537. \begin{figure}[htbp]
  9538. \begin{tcolorbox}[colback=white]
  9539. {\if\edition\racketEd
  9540. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9541. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9542. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9543. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9544. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9545. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9546. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9547. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9548. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9549. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9550. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9551. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9552. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9553. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9554. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9555. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9556. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9557. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9558. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9559. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9560. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9561. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9562. \end{tikzpicture}
  9563. \fi}
  9564. {\if\edition\pythonEd\pythonColor
  9565. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9566. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9567. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9568. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9569. \node (C-1) at (0,0) {\large \LangCIf{}};
  9570. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9571. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9572. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9573. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9574. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9575. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9576. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9577. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9578. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9579. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9580. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9581. \end{tikzpicture}
  9582. \fi}
  9583. \end{tcolorbox}
  9584. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9585. \label{fig:Lif-passes}
  9586. \end{figure}
  9587. \section{Challenge: Optimize Blocks and Remove Jumps}
  9588. \label{sec:opt-jumps}
  9589. We discuss two challenges that involve optimizing the control-flow of
  9590. the program.
  9591. \subsection{Optimize Blocks}
  9592. The algorithm for \code{explicate\_control} that we discussed in
  9593. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9594. blocks. It creates a block whenever a continuation \emph{might} get
  9595. used more than once (for example, whenever the \code{cont} parameter
  9596. is passed into two or more recursive calls). However, some
  9597. continuation arguments may not be used at all. Consider the case for
  9598. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9599. the \code{els} continuation.
  9600. %
  9601. {\if\edition\racketEd
  9602. The following example program falls into this
  9603. case, and it creates two unused blocks.
  9604. \begin{center}
  9605. \begin{tabular}{lll}
  9606. \begin{minipage}{0.4\textwidth}
  9607. % cond_test_82.rkt
  9608. \begin{lstlisting}
  9609. (let ([y (if #t
  9610. (read)
  9611. (if (eq? (read) 0)
  9612. 777
  9613. (let ([x (read)])
  9614. (+ 1 x))))])
  9615. (+ y 2))
  9616. \end{lstlisting}
  9617. \end{minipage}
  9618. &
  9619. $\Rightarrow$
  9620. &
  9621. \begin{minipage}{0.4\textwidth}
  9622. \begin{lstlisting}
  9623. start:
  9624. y = (read);
  9625. goto block_5;
  9626. block_5:
  9627. return (+ y 2);
  9628. block_6:
  9629. y = 777;
  9630. goto block_5;
  9631. block_7:
  9632. x = (read);
  9633. y = (+ 1 x2);
  9634. goto block_5;
  9635. \end{lstlisting}
  9636. \end{minipage}
  9637. \end{tabular}
  9638. \end{center}
  9639. \fi}
  9640. {\if\edition\pythonEd
  9641. The following example program falls into this
  9642. case, and it creates the unused \code{block\_9}.
  9643. \begin{center}
  9644. \begin{minipage}{0.4\textwidth}
  9645. % if/if_true.py
  9646. \begin{lstlisting}
  9647. if True:
  9648. print(0)
  9649. else:
  9650. x = 1 if False else 2
  9651. print(x)
  9652. \end{lstlisting}
  9653. \end{minipage}
  9654. $\Rightarrow\qquad\qquad$
  9655. \begin{minipage}{0.4\textwidth}
  9656. \begin{lstlisting}
  9657. start:
  9658. print(0)
  9659. goto block_8
  9660. block_9:
  9661. print(x)
  9662. goto block_8
  9663. block_8:
  9664. return 0
  9665. \end{lstlisting}
  9666. \end{minipage}
  9667. \end{center}
  9668. \fi}
  9669. The question is, how can we decide whether to create a basic block?
  9670. \emph{Lazy evaluation}\index{subject}{lazy
  9671. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9672. delaying the creation of a basic block until the point in time at which
  9673. we know that it will be used.
  9674. %
  9675. {\if\edition\racketEd
  9676. %
  9677. Racket provides support for
  9678. lazy evaluation with the
  9679. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9680. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9681. \index{subject}{delay} creates a
  9682. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9683. expressions is postponed. When \key{(force}
  9684. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9685. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9686. result of $e_n$ is cached in the promise and returned. If \code{force}
  9687. is applied again to the same promise, then the cached result is
  9688. returned. If \code{force} is applied to an argument that is not a
  9689. promise, \code{force} simply returns the argument.
  9690. %
  9691. \fi}
  9692. %
  9693. {\if\edition\pythonEd\pythonColor
  9694. %
  9695. Although Python does not provide direct support for lazy evaluation,
  9696. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9697. by wrapping it inside a function with no parameters. We \emph{force}
  9698. its evaluation by calling the function. However, we might need to
  9699. force multiple times, so we store the result of calling the
  9700. function instead of recomputing it each time. The following
  9701. \code{Promise} class handles this memoization process.
  9702. \begin{minipage}{0.8\textwidth}
  9703. \begin{lstlisting}
  9704. @dataclass
  9705. class Promise:
  9706. fun : typing.Any
  9707. cache : list[stmt] = None
  9708. def force(self):
  9709. if self.cache is None:
  9710. self.cache = self.fun(); return self.cache
  9711. else:
  9712. return self.cache
  9713. \end{lstlisting}
  9714. \end{minipage}
  9715. \noindent However, in some cases of \code{explicate\_pred}, we return
  9716. a list of statements, and in other cases we return a function that
  9717. computes a list of statements. To uniformly deal with both regular
  9718. data and promises, we define the following \code{force} function that
  9719. checks whether its input is delayed (i.e., whether it is a
  9720. \code{Promise}) and then either (1) forces the promise or (2) returns
  9721. the input.
  9722. %
  9723. \begin{lstlisting}
  9724. def force(promise):
  9725. if isinstance(promise, Promise):
  9726. return promise.force()
  9727. else:
  9728. return promise
  9729. \end{lstlisting}
  9730. %
  9731. \fi}
  9732. We use promises for the input and output of the functions
  9733. \code{explicate\_pred}, \code{explicate\_assign},
  9734. %
  9735. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9736. %
  9737. So, instead of taking and returning \racket{$\Tail$
  9738. expressions}\python{lists of statements}, they take and return
  9739. promises. Furthermore, when we come to a situation in which a
  9740. continuation might be used more than once, as in the case for
  9741. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9742. that creates a basic block for each continuation (if there is not
  9743. already one) and then returns a \code{goto} statement to that basic
  9744. block. When we come to a situation in which we have a promise but need an
  9745. actual piece of code, for example, to create a larger piece of code with a
  9746. constructor such as \code{Seq}, then insert a call to \code{force}.
  9747. %
  9748. {\if\edition\racketEd
  9749. %
  9750. Also, we must modify the \code{create\_block} function to begin with
  9751. \code{delay} to create a promise. When forced, this promise forces the
  9752. original promise. If that returns a \code{Goto} (because the block was
  9753. already added to \code{basic-blocks}), then we return the
  9754. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9755. return a \code{Goto} to the new label.
  9756. \begin{center}
  9757. \begin{minipage}{\textwidth}
  9758. \begin{lstlisting}
  9759. (define (create_block tail)
  9760. (delay
  9761. (define t (force tail))
  9762. (match t
  9763. [(Goto label) (Goto label)]
  9764. [else
  9765. (let ([label (gensym 'block)])
  9766. (set! basic-blocks (cons (cons label t) basic-blocks))
  9767. (Goto label))])))
  9768. \end{lstlisting}
  9769. \end{minipage}
  9770. \end{center}
  9771. \fi}
  9772. {\if\edition\pythonEd\pythonColor
  9773. %
  9774. Here is the new version of the \code{create\_block} auxiliary function
  9775. that delays the creation of the new basic block.\\
  9776. \begin{minipage}{\textwidth}
  9777. \begin{lstlisting}
  9778. def create_block(promise, basic_blocks):
  9779. def delay():
  9780. stmts = force(promise)
  9781. match stmts:
  9782. case [Goto(l)]:
  9783. return [Goto(l)]
  9784. case _:
  9785. label = label_name(generate_name('block'))
  9786. basic_blocks[label] = stmts
  9787. return [Goto(label)]
  9788. return Promise(delay)
  9789. \end{lstlisting}
  9790. \end{minipage}
  9791. \fi}
  9792. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9793. improved \code{explicate\_control} on this example.
  9794. \racket{As you can see, the number of basic blocks has been reduced
  9795. from four blocks to two blocks.}%
  9796. \python{As you can see, the number of basic blocks has been reduced
  9797. from three blocks to two blocks.}
  9798. \begin{figure}[tbp]
  9799. \begin{tcolorbox}[colback=white]
  9800. {\if\edition\racketEd
  9801. \begin{tabular}{lll}
  9802. \begin{minipage}{0.45\textwidth}
  9803. % cond_test_82.rkt
  9804. \begin{lstlisting}
  9805. (let ([y (if #t
  9806. (read)
  9807. (if (eq? (read) 0)
  9808. 777
  9809. (let ([x (read)])
  9810. (+ 1 x))))])
  9811. (+ y 2))
  9812. \end{lstlisting}
  9813. \end{minipage}
  9814. &
  9815. $\quad\Rightarrow\quad$
  9816. &
  9817. \begin{minipage}{0.4\textwidth}
  9818. \begin{lstlisting}
  9819. start:
  9820. y = (read);
  9821. goto block_5;
  9822. block_5:
  9823. return (+ y 2);
  9824. \end{lstlisting}
  9825. \end{minipage}
  9826. \end{tabular}
  9827. \fi}
  9828. {\if\edition\pythonEd\pythonColor
  9829. \begin{tabular}{lll}
  9830. \begin{minipage}{0.4\textwidth}
  9831. % if/if_true.py
  9832. \begin{lstlisting}
  9833. if True:
  9834. print(0)
  9835. else:
  9836. x = 1 if False else 2
  9837. print(x)
  9838. \end{lstlisting}
  9839. \end{minipage}
  9840. &
  9841. $\Rightarrow$
  9842. &
  9843. \begin{minipage}{0.55\textwidth}
  9844. \begin{lstlisting}
  9845. start:
  9846. print(0)
  9847. goto block_4
  9848. block_4:
  9849. return 0
  9850. \end{lstlisting}
  9851. \end{minipage}
  9852. \end{tabular}
  9853. \fi}
  9854. \end{tcolorbox}
  9855. \caption{Translation from \LangIf{} to \LangCIf{}
  9856. via the improved \code{explicate\_control}.}
  9857. \label{fig:explicate-control-challenge}
  9858. \end{figure}
  9859. %% Recall that in the example output of \code{explicate\_control} in
  9860. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9861. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9862. %% block. The first goal of this challenge assignment is to remove those
  9863. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9864. %% \code{explicate\_control} on the left and shows the result of bypassing
  9865. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9866. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9867. %% \code{block55}. The optimized code on the right of
  9868. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9869. %% \code{then} branch jumping directly to \code{block55}. The story is
  9870. %% similar for the \code{else} branch, as well as for the two branches in
  9871. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9872. %% have been optimized in this way, there are no longer any jumps to
  9873. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9874. %% \begin{figure}[tbp]
  9875. %% \begin{tabular}{lll}
  9876. %% \begin{minipage}{0.4\textwidth}
  9877. %% \begin{lstlisting}
  9878. %% block62:
  9879. %% tmp54 = (read);
  9880. %% if (eq? tmp54 2) then
  9881. %% goto block59;
  9882. %% else
  9883. %% goto block60;
  9884. %% block61:
  9885. %% tmp53 = (read);
  9886. %% if (eq? tmp53 0) then
  9887. %% goto block57;
  9888. %% else
  9889. %% goto block58;
  9890. %% block60:
  9891. %% goto block56;
  9892. %% block59:
  9893. %% goto block55;
  9894. %% block58:
  9895. %% goto block56;
  9896. %% block57:
  9897. %% goto block55;
  9898. %% block56:
  9899. %% return (+ 700 77);
  9900. %% block55:
  9901. %% return (+ 10 32);
  9902. %% start:
  9903. %% tmp52 = (read);
  9904. %% if (eq? tmp52 1) then
  9905. %% goto block61;
  9906. %% else
  9907. %% goto block62;
  9908. %% \end{lstlisting}
  9909. %% \end{minipage}
  9910. %% &
  9911. %% $\Rightarrow$
  9912. %% &
  9913. %% \begin{minipage}{0.55\textwidth}
  9914. %% \begin{lstlisting}
  9915. %% block62:
  9916. %% tmp54 = (read);
  9917. %% if (eq? tmp54 2) then
  9918. %% goto block55;
  9919. %% else
  9920. %% goto block56;
  9921. %% block61:
  9922. %% tmp53 = (read);
  9923. %% if (eq? tmp53 0) then
  9924. %% goto block55;
  9925. %% else
  9926. %% goto block56;
  9927. %% block56:
  9928. %% return (+ 700 77);
  9929. %% block55:
  9930. %% return (+ 10 32);
  9931. %% start:
  9932. %% tmp52 = (read);
  9933. %% if (eq? tmp52 1) then
  9934. %% goto block61;
  9935. %% else
  9936. %% goto block62;
  9937. %% \end{lstlisting}
  9938. %% \end{minipage}
  9939. %% \end{tabular}
  9940. %% \caption{Optimize jumps by removing trivial blocks.}
  9941. %% \label{fig:optimize-jumps}
  9942. %% \end{figure}
  9943. %% The name of this pass is \code{optimize-jumps}. We recommend
  9944. %% implementing this pass in two phases. The first phrase builds a hash
  9945. %% table that maps labels to possibly improved labels. The second phase
  9946. %% changes the target of each \code{goto} to use the improved label. If
  9947. %% the label is for a trivial block, then the hash table should map the
  9948. %% label to the first non-trivial block that can be reached from this
  9949. %% label by jumping through trivial blocks. If the label is for a
  9950. %% non-trivial block, then the hash table should map the label to itself;
  9951. %% we do not want to change jumps to non-trivial blocks.
  9952. %% The first phase can be accomplished by constructing an empty hash
  9953. %% table, call it \code{short-cut}, and then iterating over the control
  9954. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9955. %% then update the hash table, mapping the block's source to the target
  9956. %% of the \code{goto}. Also, the hash table may already have mapped some
  9957. %% labels to the block's source, to you must iterate through the hash
  9958. %% table and update all of those so that they instead map to the target
  9959. %% of the \code{goto}.
  9960. %% For the second phase, we recommend iterating through the $\Tail$ of
  9961. %% each block in the program, updating the target of every \code{goto}
  9962. %% according to the mapping in \code{short-cut}.
  9963. \begin{exercise}\normalfont\normalsize
  9964. Implement the improvements to the \code{explicate\_control} pass.
  9965. Check that it removes trivial blocks in a few example programs. Then
  9966. check that your compiler still passes all your tests.
  9967. \end{exercise}
  9968. \subsection{Remove Jumps}
  9969. There is an opportunity for removing jumps that is apparent in the
  9970. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9971. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9972. and there are no other jumps to
  9973. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9974. In this situation we can avoid the runtime overhead of this jump by merging
  9975. \racket{\code{block\_5}}\python{\code{block\_4}}
  9976. into the preceding block, which in this case is the \code{start} block.
  9977. Figure~\ref{fig:remove-jumps} shows the output of
  9978. \code{allocate\_registers} on the left and the result of this
  9979. optimization on the right.
  9980. \begin{figure}[tbp]
  9981. \begin{tcolorbox}[colback=white]
  9982. {\if\edition\racketEd
  9983. \begin{tabular}{lll}
  9984. \begin{minipage}{0.5\textwidth}
  9985. % cond_test_82.rkt
  9986. \begin{lstlisting}
  9987. start:
  9988. callq read_int
  9989. movq %rax, %rcx
  9990. jmp block_5
  9991. block_5:
  9992. movq %rcx, %rax
  9993. addq $2, %rax
  9994. jmp conclusion
  9995. \end{lstlisting}
  9996. \end{minipage}
  9997. &
  9998. $\Rightarrow\qquad$
  9999. \begin{minipage}{0.4\textwidth}
  10000. \begin{lstlisting}
  10001. start:
  10002. callq read_int
  10003. movq %rax, %rcx
  10004. movq %rcx, %rax
  10005. addq $2, %rax
  10006. jmp conclusion
  10007. \end{lstlisting}
  10008. \end{minipage}
  10009. \end{tabular}
  10010. \fi}
  10011. {\if\edition\pythonEd\pythonColor
  10012. \begin{tabular}{lll}
  10013. \begin{minipage}{0.5\textwidth}
  10014. % cond_test_20.rkt
  10015. \begin{lstlisting}
  10016. start:
  10017. callq read_int
  10018. movq %rax, tmp_0
  10019. cmpq 1, tmp_0
  10020. je block_3
  10021. jmp block_4
  10022. block_3:
  10023. movq 42, tmp_1
  10024. jmp block_2
  10025. block_4:
  10026. movq 0, tmp_1
  10027. jmp block_2
  10028. block_2:
  10029. movq tmp_1, %rdi
  10030. callq print_int
  10031. movq 0, %rax
  10032. jmp conclusion
  10033. \end{lstlisting}
  10034. \end{minipage}
  10035. &
  10036. $\Rightarrow\qquad$
  10037. \begin{minipage}{0.4\textwidth}
  10038. \begin{lstlisting}
  10039. start:
  10040. callq read_int
  10041. movq %rax, tmp_0
  10042. cmpq 1, tmp_0
  10043. je block_3
  10044. movq 0, tmp_1
  10045. jmp block_2
  10046. block_3:
  10047. movq 42, tmp_1
  10048. jmp block_2
  10049. block_2:
  10050. movq tmp_1, %rdi
  10051. callq print_int
  10052. movq 0, %rax
  10053. jmp conclusion
  10054. \end{lstlisting}
  10055. \end{minipage}
  10056. \end{tabular}
  10057. \fi}
  10058. \end{tcolorbox}
  10059. \caption{Merging basic blocks by removing unnecessary jumps.}
  10060. \label{fig:remove-jumps}
  10061. \end{figure}
  10062. \begin{exercise}\normalfont\normalsize
  10063. %
  10064. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10065. into their preceding basic block, when there is only one preceding
  10066. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10067. %
  10068. {\if\edition\racketEd
  10069. In the \code{run-tests.rkt} script, add the following entry to the
  10070. list of \code{passes} between \code{allocate\_registers}
  10071. and \code{patch\_instructions}:
  10072. \begin{lstlisting}
  10073. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10074. \end{lstlisting}
  10075. \fi}
  10076. %
  10077. Run the script to test your compiler.
  10078. %
  10079. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10080. blocks on several test programs.
  10081. \end{exercise}
  10082. \section{Further Reading}
  10083. \label{sec:cond-further-reading}
  10084. The algorithm for \code{explicate\_control} is based on the
  10085. \code{expose-basic-blocks} pass in the course notes of
  10086. \citet{Dybvig:2010aa}.
  10087. %
  10088. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10089. \citet{Appel:2003fk}, and is related to translations into continuation
  10090. passing
  10091. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10092. %
  10093. The treatment of conditionals in the \code{explicate\_control} pass is
  10094. similar to short-cut Boolean
  10095. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10096. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10097. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10098. \chapter{Loops and Dataflow Analysis}
  10099. \label{ch:Lwhile}
  10100. \setcounter{footnote}{0}
  10101. % TODO: define R'_8
  10102. % TODO: multi-graph
  10103. {\if\edition\racketEd
  10104. %
  10105. In this chapter we study two features that are the hallmarks of
  10106. imperative programming languages: loops and assignments to local
  10107. variables. The following example demonstrates these new features by
  10108. computing the sum of the first five positive integers:
  10109. % similar to loop_test_1.rkt
  10110. \begin{lstlisting}
  10111. (let ([sum 0])
  10112. (let ([i 5])
  10113. (begin
  10114. (while (> i 0)
  10115. (begin
  10116. (set! sum (+ sum i))
  10117. (set! i (- i 1))))
  10118. sum)))
  10119. \end{lstlisting}
  10120. The \code{while} loop consists of a condition and a
  10121. body.\footnote{The \code{while} loop is not a built-in
  10122. feature of the Racket language, but Racket includes many looping
  10123. constructs and it is straightforward to define \code{while} as a
  10124. macro.} The body is evaluated repeatedly so long as the condition
  10125. remains true.
  10126. %
  10127. The \code{set!} consists of a variable and a right-hand side
  10128. expression. The \code{set!} updates value of the variable to the
  10129. value of the right-hand side.
  10130. %
  10131. The primary purpose of both the \code{while} loop and \code{set!} is
  10132. to cause side effects, so they do not give a meaningful result
  10133. value. Instead, their result is the \code{\#<void>} value. The
  10134. expression \code{(void)} is an explicit way to create the
  10135. \code{\#<void>} value, and it has type \code{Void}. The
  10136. \code{\#<void>} value can be passed around just like other values
  10137. inside an \LangLoop{} program, and it can be compared for equality with
  10138. another \code{\#<void>} value. However, there are no other operations
  10139. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10140. Racket defines the \code{void?} predicate that returns \code{\#t}
  10141. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10142. %
  10143. \footnote{Racket's \code{Void} type corresponds to what is often
  10144. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10145. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10146. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10147. %
  10148. With the addition of side effect-producing features such as
  10149. \code{while} loop and \code{set!}, it is helpful to include a language
  10150. feature for sequencing side effects: the \code{begin} expression. It
  10151. consists of one or more subexpressions that are evaluated
  10152. left to right.
  10153. %
  10154. \fi}
  10155. {\if\edition\pythonEd\pythonColor
  10156. %
  10157. In this chapter we study loops, one of the hallmarks of imperative
  10158. programming languages. The following example demonstrates the
  10159. \code{while} loop by computing the sum of the first five positive
  10160. integers.
  10161. \begin{lstlisting}
  10162. sum = 0
  10163. i = 5
  10164. while i > 0:
  10165. sum = sum + i
  10166. i = i - 1
  10167. print(sum)
  10168. \end{lstlisting}
  10169. The \code{while} loop consists of a condition and a body (a sequence
  10170. of statements). The body is evaluated repeatedly so long as the
  10171. condition remains true.
  10172. %
  10173. \fi}
  10174. \section{The \LangLoop{} Language}
  10175. \newcommand{\LwhileGrammarRacket}{
  10176. \begin{array}{lcl}
  10177. \Type &::=& \key{Void}\\
  10178. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10179. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10180. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10181. \end{array}
  10182. }
  10183. \newcommand{\LwhileASTRacket}{
  10184. \begin{array}{lcl}
  10185. \Type &::=& \key{Void}\\
  10186. \Exp &::=& \SETBANG{\Var}{\Exp}
  10187. \MID \BEGIN{\Exp^{*}}{\Exp}
  10188. \MID \WHILE{\Exp}{\Exp}
  10189. \MID \VOID{}
  10190. \end{array}
  10191. }
  10192. \newcommand{\LwhileGrammarPython}{
  10193. \begin{array}{rcl}
  10194. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10195. \end{array}
  10196. }
  10197. \newcommand{\LwhileASTPython}{
  10198. \begin{array}{lcl}
  10199. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10200. \end{array}
  10201. }
  10202. \begin{figure}[tp]
  10203. \centering
  10204. \begin{tcolorbox}[colback=white]
  10205. \small
  10206. {\if\edition\racketEd
  10207. \[
  10208. \begin{array}{l}
  10209. \gray{\LintGrammarRacket{}} \\ \hline
  10210. \gray{\LvarGrammarRacket{}} \\ \hline
  10211. \gray{\LifGrammarRacket{}} \\ \hline
  10212. \LwhileGrammarRacket \\
  10213. \begin{array}{lcl}
  10214. \LangLoopM{} &::=& \Exp
  10215. \end{array}
  10216. \end{array}
  10217. \]
  10218. \fi}
  10219. {\if\edition\pythonEd\pythonColor
  10220. \[
  10221. \begin{array}{l}
  10222. \gray{\LintGrammarPython} \\ \hline
  10223. \gray{\LvarGrammarPython} \\ \hline
  10224. \gray{\LifGrammarPython} \\ \hline
  10225. \LwhileGrammarPython \\
  10226. \begin{array}{rcl}
  10227. \LangLoopM{} &::=& \Stmt^{*}
  10228. \end{array}
  10229. \end{array}
  10230. \]
  10231. \fi}
  10232. \end{tcolorbox}
  10233. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10234. \label{fig:Lwhile-concrete-syntax}
  10235. \index{subject}{Lwhile@\LangLoop{} concrete syntax}
  10236. \end{figure}
  10237. \begin{figure}[tp]
  10238. \centering
  10239. \begin{tcolorbox}[colback=white]
  10240. \small
  10241. {\if\edition\racketEd
  10242. \[
  10243. \begin{array}{l}
  10244. \gray{\LintOpAST} \\ \hline
  10245. \gray{\LvarASTRacket{}} \\ \hline
  10246. \gray{\LifASTRacket{}} \\ \hline
  10247. \LwhileASTRacket{} \\
  10248. \begin{array}{lcl}
  10249. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10250. \end{array}
  10251. \end{array}
  10252. \]
  10253. \fi}
  10254. {\if\edition\pythonEd\pythonColor
  10255. \[
  10256. \begin{array}{l}
  10257. \gray{\LintASTPython} \\ \hline
  10258. \gray{\LvarASTPython} \\ \hline
  10259. \gray{\LifASTPython} \\ \hline
  10260. \LwhileASTPython \\
  10261. \begin{array}{lcl}
  10262. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10263. \end{array}
  10264. \end{array}
  10265. \]
  10266. \fi}
  10267. \end{tcolorbox}
  10268. \python{
  10269. \index{subject}{While@\texttt{While}}
  10270. }
  10271. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10272. \label{fig:Lwhile-syntax}
  10273. \index{subject}{Lwhile@\LangLoop{} abstract syntax}
  10274. \end{figure}
  10275. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10276. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10277. shows the definition of its abstract syntax.
  10278. %
  10279. The definitional interpreter for \LangLoop{} is shown in
  10280. figure~\ref{fig:interp-Lwhile}.
  10281. %
  10282. {\if\edition\racketEd
  10283. %
  10284. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10285. and \code{Void}, and we make changes to the cases for \code{Var} and
  10286. \code{Let} regarding variables. To support assignment to variables and
  10287. to make their lifetimes indefinite (see the second example in
  10288. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10289. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10290. value.
  10291. %
  10292. Now we discuss the new cases. For \code{SetBang}, we find the
  10293. variable in the environment to obtain a boxed value, and then we change
  10294. it using \code{set-box!} to the result of evaluating the right-hand
  10295. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10296. %
  10297. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10298. if the result is true, (2) evaluate the body.
  10299. The result value of a \code{while} loop is also \code{\#<void>}.
  10300. %
  10301. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10302. subexpressions \itm{es} for their effects and then evaluates
  10303. and returns the result from \itm{body}.
  10304. %
  10305. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10306. %
  10307. \fi}
  10308. {\if\edition\pythonEd\pythonColor
  10309. %
  10310. We add a new case for \code{While} in the \code{interp\_stmts}
  10311. function, in which we repeatedly interpret the \code{body} so long as the
  10312. \code{test} expression remains true.
  10313. %
  10314. \fi}
  10315. \begin{figure}[tbp]
  10316. \begin{tcolorbox}[colback=white]
  10317. {\if\edition\racketEd
  10318. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10319. (define interp-Lwhile-class
  10320. (class interp-Lif-class
  10321. (super-new)
  10322. (define/override ((interp-exp env) e)
  10323. (define recur (interp-exp env))
  10324. (match e
  10325. [(Let x e body)
  10326. (define new-env (dict-set env x (box (recur e))))
  10327. ((interp-exp new-env) body)]
  10328. [(Var x) (unbox (dict-ref env x))]
  10329. [(SetBang x rhs)
  10330. (set-box! (dict-ref env x) (recur rhs))]
  10331. [(WhileLoop cnd body)
  10332. (define (loop)
  10333. (cond [(recur cnd) (recur body) (loop)]
  10334. [else (void)]))
  10335. (loop)]
  10336. [(Begin es body)
  10337. (for ([e es]) (recur e))
  10338. (recur body)]
  10339. [(Void) (void)]
  10340. [else ((super interp-exp env) e)]))
  10341. ))
  10342. (define (interp-Lwhile p)
  10343. (send (new interp-Lwhile-class) interp-program p))
  10344. \end{lstlisting}
  10345. \fi}
  10346. {\if\edition\pythonEd\pythonColor
  10347. \begin{lstlisting}
  10348. class InterpLwhile(InterpLif):
  10349. def interp_stmt(self, s, env, cont):
  10350. match s:
  10351. case While(test, body, []):
  10352. if self.interp_exp(test, env):
  10353. self.interp_stmts(body + [s] + cont, env)
  10354. else:
  10355. return self.interp_stmts(cont, env)
  10356. case _:
  10357. return super().interp_stmt(s, env, cont)
  10358. \end{lstlisting}
  10359. \fi}
  10360. \end{tcolorbox}
  10361. \caption{Interpreter for \LangLoop{}.}
  10362. \label{fig:interp-Lwhile}
  10363. \end{figure}
  10364. The definition of the type checker for \LangLoop{} is shown in
  10365. figure~\ref{fig:type-check-Lwhile}.
  10366. %
  10367. {\if\edition\racketEd
  10368. %
  10369. The type checking of the \code{SetBang} expression requires the type
  10370. of the variable and the right-hand side to agree. The result type is
  10371. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10372. and the result type is \code{Void}. For \code{Begin}, the result type
  10373. is the type of its last subexpression.
  10374. %
  10375. \fi}
  10376. %
  10377. {\if\edition\pythonEd\pythonColor
  10378. %
  10379. A \code{while} loop is well typed if the type of the \code{test}
  10380. expression is \code{bool} and the statements in the \code{body} are
  10381. well typed.
  10382. %
  10383. \fi}
  10384. \begin{figure}[tbp]
  10385. \begin{tcolorbox}[colback=white]
  10386. {\if\edition\racketEd
  10387. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10388. (define type-check-Lwhile-class
  10389. (class type-check-Lif-class
  10390. (super-new)
  10391. (inherit check-type-equal?)
  10392. (define/override (type-check-exp env)
  10393. (lambda (e)
  10394. (define recur (type-check-exp env))
  10395. (match e
  10396. [(SetBang x rhs)
  10397. (define-values (rhs^ rhsT) (recur rhs))
  10398. (define varT (dict-ref env x))
  10399. (check-type-equal? rhsT varT e)
  10400. (values (SetBang x rhs^) 'Void)]
  10401. [(WhileLoop cnd body)
  10402. (define-values (cnd^ Tc) (recur cnd))
  10403. (check-type-equal? Tc 'Boolean e)
  10404. (define-values (body^ Tbody) ((type-check-exp env) body))
  10405. (values (WhileLoop cnd^ body^) 'Void)]
  10406. [(Begin es body)
  10407. (define-values (es^ ts)
  10408. (for/lists (l1 l2) ([e es]) (recur e)))
  10409. (define-values (body^ Tbody) (recur body))
  10410. (values (Begin es^ body^) Tbody)]
  10411. [else ((super type-check-exp env) e)])))
  10412. ))
  10413. (define (type-check-Lwhile p)
  10414. (send (new type-check-Lwhile-class) type-check-program p))
  10415. \end{lstlisting}
  10416. \fi}
  10417. {\if\edition\pythonEd\pythonColor
  10418. \begin{lstlisting}
  10419. class TypeCheckLwhile(TypeCheckLif):
  10420. def type_check_stmts(self, ss, env):
  10421. if len(ss) == 0:
  10422. return
  10423. match ss[0]:
  10424. case While(test, body, []):
  10425. test_t = self.type_check_exp(test, env)
  10426. check_type_equal(bool, test_t, test)
  10427. body_t = self.type_check_stmts(body, env)
  10428. return self.type_check_stmts(ss[1:], env)
  10429. case _:
  10430. return super().type_check_stmts(ss, env)
  10431. \end{lstlisting}
  10432. \fi}
  10433. \end{tcolorbox}
  10434. \caption{Type checker for the \LangLoop{} language.}
  10435. \label{fig:type-check-Lwhile}
  10436. \end{figure}
  10437. {\if\edition\racketEd
  10438. %
  10439. At first glance, the translation of these language features to x86
  10440. seems straightforward because the \LangCIf{} intermediate language
  10441. already supports all the ingredients that we need: assignment,
  10442. \code{goto}, conditional branching, and sequencing. However,
  10443. complications arise, which we discuss in the next section. After
  10444. that we introduce the changes necessary to the existing passes.
  10445. %
  10446. \fi}
  10447. {\if\edition\pythonEd\pythonColor
  10448. %
  10449. At first glance, the translation of \code{while} loops to x86 seems
  10450. straightforward because the \LangCIf{} intermediate language already
  10451. supports \code{goto} and conditional branching. However, there are
  10452. complications that arise, which we discuss in the next section. After
  10453. that we introduce the changes necessary to the existing passes.
  10454. %
  10455. \fi}
  10456. \section{Cyclic Control Flow and Dataflow Analysis}
  10457. \label{sec:dataflow-analysis}
  10458. Up until this point, the programs generated in
  10459. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10460. \code{while} loop introduces a cycle. Does that matter?
  10461. %
  10462. Indeed, it does. Recall that for register allocation, the compiler
  10463. performs liveness analysis to determine which variables can share the
  10464. same register. To accomplish this, we analyzed the control-flow graph
  10465. in reverse topological order
  10466. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10467. well defined only for acyclic graphs.
  10468. Let us return to the example of computing the sum of the first five
  10469. positive integers. Here is the program after instruction
  10470. selection\index{subject}{instruction selection} but before register
  10471. allocation.
  10472. \begin{center}
  10473. {\if\edition\racketEd
  10474. \begin{minipage}{0.45\textwidth}
  10475. \begin{lstlisting}
  10476. (define (main) : Integer
  10477. mainstart:
  10478. movq $0, sum
  10479. movq $5, i
  10480. jmp block5
  10481. block5:
  10482. movq i, tmp3
  10483. cmpq tmp3, $0
  10484. jl block7
  10485. jmp block8
  10486. \end{lstlisting}
  10487. \end{minipage}
  10488. \begin{minipage}{0.45\textwidth}
  10489. \begin{lstlisting}
  10490. block7:
  10491. addq i, sum
  10492. movq $1, tmp4
  10493. negq tmp4
  10494. addq tmp4, i
  10495. jmp block5
  10496. block8:
  10497. movq $27, %rax
  10498. addq sum, %rax
  10499. jmp mainconclusion)
  10500. \end{lstlisting}
  10501. \end{minipage}
  10502. \fi}
  10503. {\if\edition\pythonEd\pythonColor
  10504. \begin{minipage}{0.45\textwidth}
  10505. \begin{lstlisting}
  10506. mainstart:
  10507. movq $0, sum
  10508. movq $5, i
  10509. jmp block5
  10510. block5:
  10511. cmpq $0, i
  10512. jg block7
  10513. jmp block8
  10514. \end{lstlisting}
  10515. \end{minipage}
  10516. \begin{minipage}{0.45\textwidth}
  10517. \begin{lstlisting}
  10518. block7:
  10519. addq i, sum
  10520. subq $1, i
  10521. jmp block5
  10522. block8:
  10523. movq sum, %rdi
  10524. callq print_int
  10525. movq $0, %rax
  10526. jmp mainconclusion
  10527. \end{lstlisting}
  10528. \end{minipage}
  10529. \fi}
  10530. \end{center}
  10531. Recall that liveness analysis works backward, starting at the end
  10532. of each function. For this example we could start with \code{block8}
  10533. because we know what is live at the beginning of the conclusion:
  10534. only \code{rax} and \code{rsp}. So the live-before set
  10535. for \code{block8} is \code{\{rsp,sum\}}.
  10536. %
  10537. Next we might try to analyze \code{block5} or \code{block7}, but
  10538. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10539. we are stuck.
  10540. The way out of this impasse is to realize that we can compute an
  10541. underapproximation of each live-before set by starting with empty
  10542. live-after sets. By \emph{underapproximation}, we mean that the set
  10543. contains only variables that are live for some execution of the
  10544. program, but the set may be missing some variables that are live.
  10545. Next, the underapproximations for each block can be improved by (1)
  10546. updating the live-after set for each block using the approximate
  10547. live-before sets from the other blocks, and (2) performing liveness
  10548. analysis again on each block. In fact, by iterating this process, the
  10549. underapproximations eventually become the correct solutions!
  10550. %
  10551. This approach of iteratively analyzing a control-flow graph is
  10552. applicable to many static analysis problems and goes by the name
  10553. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10554. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10555. Washington.
  10556. Let us apply this approach to the previously presented example. We use
  10557. the empty set for the initial live-before set for each block. Let
  10558. $m_0$ be the following mapping from label names to sets of locations
  10559. (variables and registers):
  10560. \begin{center}
  10561. \begin{lstlisting}
  10562. mainstart: {}, block5: {}, block7: {}, block8: {}
  10563. \end{lstlisting}
  10564. \end{center}
  10565. Using the above live-before approximations, we determine the
  10566. live-after for each block and then apply liveness analysis to each
  10567. block. This produces our next approximation $m_1$ of the live-before
  10568. sets.
  10569. \begin{center}
  10570. \begin{lstlisting}
  10571. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10572. \end{lstlisting}
  10573. \end{center}
  10574. For the second round, the live-after for \code{mainstart} is the
  10575. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10576. the liveness analysis for \code{mainstart} computes the empty set. The
  10577. live-after for \code{block5} is the union of the live-before sets for
  10578. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10579. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10580. sum\}}. The live-after for \code{block7} is the live-before for
  10581. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10582. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10583. Together these yield the following approximation $m_2$ of
  10584. the live-before sets:
  10585. \begin{center}
  10586. \begin{lstlisting}
  10587. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10588. \end{lstlisting}
  10589. \end{center}
  10590. In the preceding iteration, only \code{block5} changed, so we can
  10591. limit our attention to \code{mainstart} and \code{block7}, the two
  10592. blocks that jump to \code{block5}. As a result, the live-before sets
  10593. for \code{mainstart} and \code{block7} are updated to include
  10594. \code{rsp}, yielding the following approximation $m_3$:
  10595. \begin{center}
  10596. \begin{lstlisting}
  10597. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10598. \end{lstlisting}
  10599. \end{center}
  10600. Because \code{block7} changed, we analyze \code{block5} once more, but
  10601. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10602. our approximations have converged, so $m_3$ is the solution.
  10603. This iteration process is guaranteed to converge to a solution by the
  10604. Kleene fixed-point theorem, a general theorem about functions on
  10605. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10606. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10607. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10608. join operator
  10609. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10610. will be working with join semilattices.} When two elements are
  10611. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10612. as much information as $m_i$, so we can think of $m_j$ as a
  10613. better-than-or-equal-to approximation in relation to $m_i$. The
  10614. bottom element $\bot$ represents the complete lack of information,
  10615. that is, the worst approximation. The join operator takes two lattice
  10616. elements and combines their information; that is, it produces the
  10617. least upper bound of the two.\index{subject}{least upper bound}
  10618. A dataflow analysis typically involves two lattices: one lattice to
  10619. represent abstract states and another lattice that aggregates the
  10620. abstract states of all the blocks in the control-flow graph. For
  10621. liveness analysis, an abstract state is a set of locations. We form
  10622. the lattice $L$ by taking its elements to be sets of locations, the
  10623. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10624. set, and the join operator to be set union.
  10625. %
  10626. We form a second lattice $M$ by taking its elements to be mappings
  10627. from the block labels to sets of locations (elements of $L$). We
  10628. order the mappings point-wise, using the ordering of $L$. So, given any
  10629. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10630. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10631. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10632. to the empty set, $\bot_M(\ell) = \emptyset$.
  10633. We can think of one iteration of liveness analysis applied to the
  10634. whole program as being a function $f$ on the lattice $M$. It takes a
  10635. mapping as input and computes a new mapping.
  10636. \[
  10637. f(m_i) = m_{i+1}
  10638. \]
  10639. Next let us think for a moment about what a final solution $m_s$
  10640. should look like. If we perform liveness analysis using the solution
  10641. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10642. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10643. \[
  10644. f(m_s) = m_s
  10645. \]
  10646. Furthermore, the solution should include only locations that are
  10647. forced to be there by performing liveness analysis on the program, so
  10648. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10649. The Kleene fixed-point theorem states that if a function $f$ is
  10650. monotone (better inputs produce better outputs), then the least fixed
  10651. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10652. chain} that starts at $\bot$ and iterates $f$ as
  10653. follows:\index{subject}{Kleene fixed-point theorem}
  10654. \[
  10655. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10656. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10657. \]
  10658. When a lattice contains only finitely long ascending chains, then
  10659. every Kleene chain tops out at some fixed point after some number of
  10660. iterations of $f$.
  10661. \[
  10662. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10663. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10664. \]
  10665. The liveness analysis is indeed a monotone function and the lattice
  10666. $M$ has finitely long ascending chains because there are only a
  10667. finite number of variables and blocks in the program. Thus we are
  10668. guaranteed that iteratively applying liveness analysis to all blocks
  10669. in the program will eventually produce the least fixed point solution.
  10670. Next let us consider dataflow analysis in general and discuss the
  10671. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10672. %
  10673. The algorithm has four parameters: the control-flow graph \code{G}, a
  10674. function \code{transfer} that applies the analysis to one block, and the
  10675. \code{bottom} and \code{join} operators for the lattice of abstract
  10676. states. The \code{analyze\_dataflow} function is formulated as a
  10677. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10678. function come from the predecessor nodes in the control-flow
  10679. graph. However, liveness analysis is a \emph{backward} dataflow
  10680. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10681. function with the transpose of the control-flow graph.
  10682. The algorithm begins by creating the bottom mapping, represented by a
  10683. hash table. It then pushes all the nodes in the control-flow graph
  10684. onto the work list (a queue). The algorithm repeats the \code{while}
  10685. loop as long as there are items in the work list. In each iteration, a
  10686. node is popped from the work list and processed. The \code{input} for
  10687. the node is computed by taking the join of the abstract states of all
  10688. the predecessor nodes. The \code{transfer} function is then applied to
  10689. obtain the \code{output} abstract state. If the output differs from
  10690. the previous state for this block, the mapping for this block is
  10691. updated and its successor nodes are pushed onto the work list.
  10692. \begin{figure}[tb]
  10693. \begin{tcolorbox}[colback=white]
  10694. {\if\edition\racketEd
  10695. \begin{lstlisting}
  10696. (define (analyze_dataflow G transfer bottom join)
  10697. (define mapping (make-hash))
  10698. (for ([v (in-vertices G)])
  10699. (dict-set! mapping v bottom))
  10700. (define worklist (make-queue))
  10701. (for ([v (in-vertices G)])
  10702. (enqueue! worklist v))
  10703. (define trans-G (transpose G))
  10704. (while (not (queue-empty? worklist))
  10705. (define node (dequeue! worklist))
  10706. (define input (for/fold ([state bottom])
  10707. ([pred (in-neighbors trans-G node)])
  10708. (join state (dict-ref mapping pred))))
  10709. (define output (transfer node input))
  10710. (cond [(not (equal? output (dict-ref mapping node)))
  10711. (dict-set! mapping node output)
  10712. (for ([v (in-neighbors G node)])
  10713. (enqueue! worklist v))]))
  10714. mapping)
  10715. \end{lstlisting}
  10716. \fi}
  10717. {\if\edition\pythonEd\pythonColor
  10718. \begin{lstlisting}
  10719. def analyze_dataflow(G, transfer, bottom, join):
  10720. trans_G = transpose(G)
  10721. mapping = dict((v, bottom) for v in G.vertices())
  10722. worklist = deque(G.vertices)
  10723. while worklist:
  10724. node = worklist.pop()
  10725. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10726. input = reduce(join, inputs, bottom)
  10727. output = transfer(node, input)
  10728. if output != mapping[node]:
  10729. mapping[node] = output
  10730. worklist.extend(G.adjacent(node))
  10731. \end{lstlisting}
  10732. \fi}
  10733. \end{tcolorbox}
  10734. \caption{Generic work list algorithm for dataflow analysis.}
  10735. \label{fig:generic-dataflow}
  10736. \end{figure}
  10737. {\if\edition\racketEd
  10738. \section{Mutable Variables and Remove Complex Operands}
  10739. There is a subtle interaction between the
  10740. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10741. and the left-to-right order of evaluation of Racket. Consider the
  10742. following example:
  10743. \begin{lstlisting}
  10744. (let ([x 2])
  10745. (+ x (begin (set! x 40) x)))
  10746. \end{lstlisting}
  10747. The result of this program is \code{42} because the first read from
  10748. \code{x} produces \code{2} and the second produces \code{40}. However,
  10749. if we naively apply the \code{remove\_complex\_operands} pass to this
  10750. example we obtain the following program whose result is \code{80}!
  10751. \begin{lstlisting}
  10752. (let ([x 2])
  10753. (let ([tmp (begin (set! x 40) x)])
  10754. (+ x tmp)))
  10755. \end{lstlisting}
  10756. The problem is that with mutable variables, the ordering between
  10757. reads and writes is important, and the
  10758. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10759. before the first read of \code{x}.
  10760. We recommend solving this problem by giving special treatment to reads
  10761. from mutable variables, that is, variables that occur on the left-hand
  10762. side of a \code{set!}. We mark each read from a mutable variable with
  10763. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10764. that the read operation is effectful in that it can produce different
  10765. results at different points in time. Let's apply this idea to the
  10766. following variation that also involves a variable that is not mutated:
  10767. % loop_test_24.rkt
  10768. \begin{lstlisting}
  10769. (let ([x 2])
  10770. (let ([y 0])
  10771. (+ y (+ x (begin (set! x 40) x)))))
  10772. \end{lstlisting}
  10773. We first analyze this program to discover that variable \code{x}
  10774. is mutable but \code{y} is not. We then transform the program as
  10775. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10776. \begin{lstlisting}
  10777. (let ([x 2])
  10778. (let ([y 0])
  10779. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10780. \end{lstlisting}
  10781. Now that we have a clear distinction between reads from mutable and
  10782. immutable variables, we can apply the \code{remove\_complex\_operands}
  10783. pass, where reads from immutable variables are still classified as
  10784. atomic expressions but reads from mutable variables are classified as
  10785. complex. Thus, \code{remove\_complex\_operands} yields the following
  10786. program:\\
  10787. \begin{minipage}{\textwidth}
  10788. \begin{lstlisting}
  10789. (let ([x 2])
  10790. (let ([y 0])
  10791. (let ([t1 x])
  10792. (let ([t2 (begin (set! x 40) x)])
  10793. (let ([t3 (+ t1 t2)])
  10794. (+ y t3))))))
  10795. \end{lstlisting}
  10796. \end{minipage}
  10797. The temporary variable \code{t1} gets the value of \code{x} before the
  10798. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10799. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10800. do not generate a temporary variable for the occurrence of \code{y}
  10801. because it's an immutable variable. We want to avoid such unnecessary
  10802. extra temporaries because they would needlessly increase the number of
  10803. variables, making it more likely for some of them to be spilled. The
  10804. result of this program is \code{42}, the same as the result prior to
  10805. \code{remove\_complex\_operands}.
  10806. The approach that we've sketched requires only a small
  10807. modification to \code{remove\_complex\_operands} to handle
  10808. \code{get!}. However, it requires a new pass, called
  10809. \code{uncover-get!}, that we discuss in
  10810. section~\ref{sec:uncover-get-bang}.
  10811. As an aside, this problematic interaction between \code{set!} and the
  10812. pass \code{remove\_complex\_operands} is particular to Racket and not
  10813. its predecessor, the Scheme language. The key difference is that
  10814. Scheme does not specify an order of evaluation for the arguments of an
  10815. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10816. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10817. would be correct results for the example program. Interestingly,
  10818. Racket is implemented on top of the Chez Scheme
  10819. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10820. presented in this section (using extra \code{let} bindings to control
  10821. the order of evaluation) is used in the translation from Racket to
  10822. Scheme~\citep{Flatt:2019tb}.
  10823. \fi} % racket
  10824. Having discussed the complications that arise from adding support for
  10825. assignment and loops, we turn to discussing the individual compilation
  10826. passes.
  10827. {\if\edition\racketEd
  10828. \section{Uncover \texttt{get!}}
  10829. \label{sec:uncover-get-bang}
  10830. The goal of this pass is to mark uses of mutable variables so that
  10831. \code{remove\_complex\_operands} can treat them as complex expressions
  10832. and thereby preserve their ordering relative to the side effects in
  10833. other operands. So, the first step is to collect all the mutable
  10834. variables. We recommend creating an auxiliary function for this,
  10835. named \code{collect-set!}, that recursively traverses expressions,
  10836. returning the set of all variables that occur on the left-hand side of a
  10837. \code{set!}. Here's an excerpt of its implementation.
  10838. \begin{center}
  10839. \begin{minipage}{\textwidth}
  10840. \begin{lstlisting}
  10841. (define (collect-set! e)
  10842. (match e
  10843. [(Var x) (set)]
  10844. [(Int n) (set)]
  10845. [(Let x rhs body)
  10846. (set-union (collect-set! rhs) (collect-set! body))]
  10847. [(SetBang var rhs)
  10848. (set-union (set var) (collect-set! rhs))]
  10849. ...))
  10850. \end{lstlisting}
  10851. \end{minipage}
  10852. \end{center}
  10853. By placing this pass after \code{uniquify}, we need not worry about
  10854. variable shadowing, and our logic for \code{Let} can remain simple, as
  10855. in this excerpt.
  10856. The second step is to mark the occurrences of the mutable variables
  10857. with the new \code{GetBang} AST node (\code{get!} in concrete
  10858. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10859. function, which takes two parameters: the set of mutable variables
  10860. \code{set!-vars} and the expression \code{e} to be processed. The
  10861. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10862. mutable variable or leaves it alone if not.
  10863. \begin{center}
  10864. \begin{minipage}{\textwidth}
  10865. \begin{lstlisting}
  10866. (define ((uncover-get!-exp set!-vars) e)
  10867. (match e
  10868. [(Var x)
  10869. (if (set-member? set!-vars x)
  10870. (GetBang x)
  10871. (Var x))]
  10872. ...))
  10873. \end{lstlisting}
  10874. \end{minipage}
  10875. \end{center}
  10876. To wrap things up, define the \code{uncover-get!} function for
  10877. processing a whole program, using \code{collect-set!} to obtain the
  10878. set of mutable variables and then \code{uncover-get!-exp} to replace
  10879. their occurrences with \code{GetBang}.
  10880. \fi}
  10881. \section{Remove Complex Operands}
  10882. \label{sec:rco-loop}
  10883. {\if\edition\racketEd
  10884. %
  10885. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10886. \code{while} are all complex expressions. The subexpressions of
  10887. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10888. %
  10889. \fi}
  10890. {\if\edition\pythonEd\pythonColor
  10891. %
  10892. The change needed for this pass is to add a case for the \code{while}
  10893. statement. The condition of a loop is allowed to be a complex
  10894. expression, just like the condition of the \code{if} statement.
  10895. %
  10896. \fi}
  10897. %
  10898. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10899. \LangLoopANF{} of this pass.
  10900. \newcommand{\LwhileMonadASTRacket}{
  10901. \begin{array}{rcl}
  10902. \Atm &::=& \VOID{} \\
  10903. \Exp &::=& \GETBANG{\Var}
  10904. \MID \SETBANG{\Var}{\Exp}
  10905. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10906. &\MID& \WHILE{\Exp}{\Exp}
  10907. \end{array}
  10908. }
  10909. \newcommand{\LwhileMonadASTPython}{
  10910. \begin{array}{rcl}
  10911. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10912. \end{array}
  10913. }
  10914. \begin{figure}[tp]
  10915. \centering
  10916. \begin{tcolorbox}[colback=white]
  10917. \small
  10918. {\if\edition\racketEd
  10919. \[
  10920. \begin{array}{l}
  10921. \gray{\LvarMonadASTRacket} \\ \hline
  10922. \gray{\LifMonadASTRacket} \\ \hline
  10923. \LwhileMonadASTRacket \\
  10924. \begin{array}{rcl}
  10925. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10926. \end{array}
  10927. \end{array}
  10928. \]
  10929. \fi}
  10930. {\if\edition\pythonEd\pythonColor
  10931. \[
  10932. \begin{array}{l}
  10933. \gray{\LvarMonadASTPython} \\ \hline
  10934. \gray{\LifMonadASTPython} \\ \hline
  10935. \LwhileMonadASTPython \\
  10936. \begin{array}{rcl}
  10937. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10938. \end{array}
  10939. \end{array}
  10940. \]
  10941. \fi}
  10942. \end{tcolorbox}
  10943. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10944. \label{fig:Lwhile-anf-syntax}
  10945. \index{subject}{Lwhilemon@\LangLoopANF{} abstract syntax}
  10946. \end{figure}
  10947. {\if\edition\racketEd
  10948. %
  10949. As usual, when a complex expression appears in a grammar position that
  10950. needs to be atomic, such as the argument of a primitive operator, we
  10951. must introduce a temporary variable and bind it to the complex
  10952. expression. This approach applies, unchanged, to handle the new
  10953. language forms. For example, in the following code there are two
  10954. \code{begin} expressions appearing as arguments to the \code{+}
  10955. operator. The output of \code{rco\_exp} is then shown, in which the
  10956. \code{begin} expressions have been bound to temporary
  10957. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10958. allowed to have arbitrary expressions in their right-hand side
  10959. expression, so it is fine to place \code{begin} there.
  10960. %
  10961. \begin{center}
  10962. \begin{tabular}{lcl}
  10963. \begin{minipage}{0.4\textwidth}
  10964. \begin{lstlisting}
  10965. (let ([x2 10])
  10966. (let ([y3 0])
  10967. (+ (+ (begin
  10968. (set! y3 (read))
  10969. (get! x2))
  10970. (begin
  10971. (set! x2 (read))
  10972. (get! y3)))
  10973. (get! x2))))
  10974. \end{lstlisting}
  10975. \end{minipage}
  10976. &
  10977. $\Rightarrow$
  10978. &
  10979. \begin{minipage}{0.4\textwidth}
  10980. \begin{lstlisting}
  10981. (let ([x2 10])
  10982. (let ([y3 0])
  10983. (let ([tmp4 (begin
  10984. (set! y3 (read))
  10985. x2)])
  10986. (let ([tmp5 (begin
  10987. (set! x2 (read))
  10988. y3)])
  10989. (let ([tmp6 (+ tmp4 tmp5)])
  10990. (let ([tmp7 x2])
  10991. (+ tmp6 tmp7)))))))
  10992. \end{lstlisting}
  10993. \end{minipage}
  10994. \end{tabular}
  10995. \end{center}
  10996. \fi}
  10997. \section{Explicate Control \racket{and \LangCLoop{}}}
  10998. \label{sec:explicate-loop}
  10999. \newcommand{\CloopASTRacket}{
  11000. \begin{array}{lcl}
  11001. \Atm &::=& \VOID \\
  11002. \Stmt &::=& \READ{}
  11003. \end{array}
  11004. }
  11005. {\if\edition\racketEd
  11006. Recall that in the \code{explicate\_control} pass we define one helper
  11007. function for each kind of position in the program. For the \LangVar{}
  11008. language of integers and variables, we needed assignment and tail
  11009. positions. The \code{if} expressions of \LangIf{} introduced predicate
  11010. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  11011. another kind of position: effect position. Except for the last
  11012. subexpression, the subexpressions inside a \code{begin} are evaluated
  11013. only for their effect. Their result values are discarded. We can
  11014. generate better code by taking this fact into account.
  11015. The output language of \code{explicate\_control} is \LangCLoop{}
  11016. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  11017. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  11018. and that \code{read} may appear as a statement. The most significant
  11019. difference between the programs generated by \code{explicate\_control}
  11020. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  11021. chapter is that the control-flow graphs of the latter may contain
  11022. cycles.
  11023. \begin{figure}[tp]
  11024. \begin{tcolorbox}[colback=white]
  11025. \small
  11026. \[
  11027. \begin{array}{l}
  11028. \gray{\CvarASTRacket} \\ \hline
  11029. \gray{\CifASTRacket} \\ \hline
  11030. \CloopASTRacket \\
  11031. \begin{array}{lcl}
  11032. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11033. \end{array}
  11034. \end{array}
  11035. \]
  11036. \end{tcolorbox}
  11037. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  11038. \label{fig:c7-syntax}
  11039. \index{subject}{Cwhile@\LangCLoop{} abstract syntax}
  11040. \end{figure}
  11041. The new auxiliary function \code{explicate\_effect} takes an
  11042. expression (in an effect position) and the code for its
  11043. continuation. The function returns a $\Tail$ that includes the
  11044. generated code for the input expression followed by the
  11045. continuation. If the expression is obviously pure, that is, never
  11046. causes side effects, then the expression can be removed, so the result
  11047. is just the continuation.
  11048. %
  11049. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  11050. interesting; the generated code is depicted in the following diagram:
  11051. \begin{center}
  11052. \begin{minipage}{0.3\textwidth}
  11053. \xymatrix{
  11054. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  11055. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  11056. & *+[F]{\txt{\itm{cont}}} \\
  11057. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  11058. }
  11059. \end{minipage}
  11060. \end{center}
  11061. We start by creating a fresh label $\itm{loop}$ for the top of the
  11062. loop. Next, recursively process the \itm{body} (in effect position)
  11063. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  11064. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11065. \itm{body'} as the \emph{then} branch and the continuation block as the
  11066. \emph{else} branch. The result should be added to the dictionary of
  11067. \code{basic-blocks} with the label \itm{loop}. The result for the
  11068. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11069. The auxiliary functions for tail, assignment, and predicate positions
  11070. need to be updated. The three new language forms, \code{while},
  11071. \code{set!}, and \code{begin}, can appear in assignment and tail
  11072. positions. Only \code{begin} may appear in predicate positions; the
  11073. other two have result type \code{Void}.
  11074. \fi}
  11075. %
  11076. {\if\edition\pythonEd\pythonColor
  11077. %
  11078. The output of this pass is the language \LangCIf{}. No new language
  11079. features are needed in the output, because a \code{while} loop can be
  11080. expressed in terms of \code{goto} and \code{if} statements, which are
  11081. already in \LangCIf{}.
  11082. %
  11083. Add a case for the \code{while} statement to the
  11084. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11085. the condition expression.
  11086. %
  11087. \fi}
  11088. {\if\edition\racketEd
  11089. \section{Select Instructions}
  11090. \label{sec:select-instructions-loop}
  11091. \index{subject}{select instructions}
  11092. Only two small additions are needed in the \code{select\_instructions}
  11093. pass to handle the changes to \LangCLoop{}. First, to handle the
  11094. addition of \VOID{} we simply translate it to \code{0}. Second,
  11095. \code{read} may appear as a stand-alone statement instead of
  11096. appearing only on the right-hand side of an assignment statement. The code
  11097. generation is nearly identical to the one for assignment; just leave
  11098. off the instruction for moving the result into the left-hand side.
  11099. \fi}
  11100. \section{Register Allocation}
  11101. \label{sec:register-allocation-loop}
  11102. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11103. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11104. which complicates the liveness analysis needed for register
  11105. allocation.
  11106. %
  11107. We recommend using the generic \code{analyze\_dataflow} function that
  11108. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11109. perform liveness analysis, replacing the code in
  11110. \code{uncover\_live} that processed the basic blocks in topological
  11111. order (section~\ref{sec:liveness-analysis-Lif}).
  11112. The \code{analyze\_dataflow} function has the following four parameters.
  11113. \begin{enumerate}
  11114. \item The first parameter \code{G} should be passed the transpose
  11115. of the control-flow graph.
  11116. \item The second parameter \code{transfer} should be passed a function
  11117. that applies liveness analysis to a basic block. It takes two
  11118. parameters: the label for the block to analyze and the live-after
  11119. set for that block. The transfer function should return the
  11120. live-before set for the block.
  11121. %
  11122. \racket{Also, as a side effect, it should update the block's
  11123. $\itm{info}$ with the liveness information for each instruction.}
  11124. %
  11125. \python{Also, as a side effect, it should update the live-before and
  11126. live-after sets for each instruction.}
  11127. %
  11128. To implement the \code{transfer} function, you should be able to
  11129. reuse the code you already have for analyzing basic blocks.
  11130. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11131. \code{bottom} and \code{join} for the lattice of abstract states,
  11132. that is, sets of locations. For liveness analysis, the bottom of the
  11133. lattice is the empty set, and the join operator is set union.
  11134. \end{enumerate}
  11135. \begin{figure}[tp]
  11136. \begin{tcolorbox}[colback=white]
  11137. {\if\edition\racketEd
  11138. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11139. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11140. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11141. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11142. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11143. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11144. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11145. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11146. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11147. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11148. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11149. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11150. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11151. \path[->,bend left=15] (Lfun) edge [above] node
  11152. {\ttfamily\footnotesize shrink} (Lfun-2);
  11153. \path[->,bend left=15] (Lfun-2) edge [above] node
  11154. {\ttfamily\footnotesize uniquify} (F1-4);
  11155. \path[->,bend left=15] (F1-4) edge [above] node
  11156. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11157. \path[->,bend left=15] (F1-5) edge [left] node
  11158. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11159. \path[->,bend left=10] (F1-6) edge [above] node
  11160. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11161. \path[->,bend left=15] (C3-2) edge [right] node
  11162. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11163. \path[->,bend right=15] (x86-2) edge [right] node
  11164. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11165. \path[->,bend right=15] (x86-2-1) edge [below] node
  11166. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11167. \path[->,bend right=15] (x86-2-2) edge [right] node
  11168. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11169. \path[->,bend left=15] (x86-3) edge [above] node
  11170. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11171. \path[->,bend left=15] (x86-4) edge [right] node
  11172. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11173. \end{tikzpicture}
  11174. \fi}
  11175. {\if\edition\pythonEd\pythonColor
  11176. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11177. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11178. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11179. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11180. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11181. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11182. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11183. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11184. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11185. \path[->,bend left=15] (Lfun) edge [above] node
  11186. {\ttfamily\footnotesize shrink} (Lfun-2);
  11187. \path[->,bend left=15] (Lfun-2) edge [above] node
  11188. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11189. \path[->,bend left=10] (F1-6) edge [right] node
  11190. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11191. \path[->,bend right=15] (C3-2) edge [right] node
  11192. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11193. \path[->,bend right=15] (x86-2) edge [below] node
  11194. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11195. \path[->,bend left=15] (x86-3) edge [above] node
  11196. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11197. \path[->,bend right=15] (x86-4) edge [below] node
  11198. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11199. \end{tikzpicture}
  11200. \fi}
  11201. \end{tcolorbox}
  11202. \caption{Diagram of the passes for \LangLoop{}.}
  11203. \label{fig:Lwhile-passes}
  11204. \end{figure}
  11205. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11206. for the compilation of \LangLoop{}.
  11207. % Further Reading: dataflow analysis
  11208. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11209. \chapter{Tuples and Garbage Collection}
  11210. \label{ch:Lvec}
  11211. \index{subject}{tuple}
  11212. \index{subject}{vector}
  11213. \setcounter{footnote}{0}
  11214. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11215. %% all the IR grammars are spelled out! \\ --Jeremy}
  11216. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11217. %% the root stack. \\ --Jeremy}
  11218. In this chapter we study the implementation of tuples\racket{, called
  11219. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11220. in which each element may have a different type.
  11221. %
  11222. This language feature is the first to use the computer's
  11223. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11224. indefinite; that is, a tuple lives forever from the programmer's
  11225. viewpoint. Of course, from an implementer's viewpoint, it is important
  11226. to reclaim the space associated with a tuple when it is no longer
  11227. needed, which is why we also study \emph{garbage collection}
  11228. \index{subject}{garbage collection} techniques in this chapter.
  11229. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11230. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11231. language (chapter~\ref{ch:Lwhile}) with tuples.
  11232. %
  11233. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11234. copying live tuples back and forth between two halves of the heap. The
  11235. garbage collector requires coordination with the compiler so that it
  11236. can find all the live tuples.
  11237. %
  11238. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11239. discuss the necessary changes and additions to the compiler passes,
  11240. including a new compiler pass named \code{expose\_allocation}.
  11241. \section{The \LangVec{} Language}
  11242. \label{sec:r3}
  11243. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11244. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11245. the definition of the abstract syntax.
  11246. %
  11247. \racket{The \LangVec{} language includes the forms \code{vector} for
  11248. creating a tuple, \code{vector-ref} for reading an element of a
  11249. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11250. \code{vector-length} for obtaining the number of elements of a
  11251. tuple.}
  11252. %
  11253. \python{The \LangVec{} language adds (1) tuple creation via a
  11254. comma-separated list of expressions; (2) accessing an element of a
  11255. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11256. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11257. comparison operator; and (4) obtaining the number of elements (the
  11258. length) of a tuple. In this chapter, we restrict access indices to
  11259. constant integers.}
  11260. %
  11261. The following program shows an example of the use of tuples. It creates a tuple
  11262. \code{t} containing the elements \code{40},
  11263. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11264. contains just \code{2}. The element at index $1$ of \code{t} is
  11265. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11266. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11267. to which we add \code{2}, the element at index $0$ of the tuple.
  11268. The result of the program is \code{42}.
  11269. %
  11270. {\if\edition\racketEd
  11271. \begin{lstlisting}
  11272. (let ([t (vector 40 #t (vector 2))])
  11273. (if (vector-ref t 1)
  11274. (+ (vector-ref t 0)
  11275. (vector-ref (vector-ref t 2) 0))
  11276. 44))
  11277. \end{lstlisting}
  11278. \fi}
  11279. {\if\edition\pythonEd\pythonColor
  11280. \begin{lstlisting}
  11281. t = 40, True, (2,)
  11282. print(t[0] + t[2][0] if t[1] else 44)
  11283. \end{lstlisting}
  11284. \fi}
  11285. \newcommand{\LtupGrammarRacket}{
  11286. \begin{array}{lcl}
  11287. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11288. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11289. \MID \LP\key{vector-length}\;\Exp\RP \\
  11290. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11291. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11292. \end{array}
  11293. }
  11294. \newcommand{\LtupASTRacket}{
  11295. \begin{array}{lcl}
  11296. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11297. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11298. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11299. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11300. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11301. \end{array}
  11302. }
  11303. \newcommand{\LtupGrammarPython}{
  11304. \begin{array}{rcl}
  11305. \itm{cmp} &::= & \key{is} \\
  11306. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11307. \end{array}
  11308. }
  11309. \newcommand{\LtupASTPython}{
  11310. \begin{array}{lcl}
  11311. \itm{cmp} &::= & \code{Is()} \\
  11312. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11313. &\MID& \LEN{\Exp}
  11314. \end{array}
  11315. }
  11316. \begin{figure}[tbp]
  11317. \centering
  11318. \begin{tcolorbox}[colback=white]
  11319. \small
  11320. {\if\edition\racketEd
  11321. \[
  11322. \begin{array}{l}
  11323. \gray{\LintGrammarRacket{}} \\ \hline
  11324. \gray{\LvarGrammarRacket{}} \\ \hline
  11325. \gray{\LifGrammarRacket{}} \\ \hline
  11326. \gray{\LwhileGrammarRacket} \\ \hline
  11327. \LtupGrammarRacket \\
  11328. \begin{array}{lcl}
  11329. \LangVecM{} &::=& \Exp
  11330. \end{array}
  11331. \end{array}
  11332. \]
  11333. \fi}
  11334. {\if\edition\pythonEd\pythonColor
  11335. \[
  11336. \begin{array}{l}
  11337. \gray{\LintGrammarPython{}} \\ \hline
  11338. \gray{\LvarGrammarPython{}} \\ \hline
  11339. \gray{\LifGrammarPython{}} \\ \hline
  11340. \gray{\LwhileGrammarPython} \\ \hline
  11341. \LtupGrammarPython \\
  11342. \begin{array}{rcl}
  11343. \LangVecM{} &::=& \Stmt^{*}
  11344. \end{array}
  11345. \end{array}
  11346. \]
  11347. \fi}
  11348. \end{tcolorbox}
  11349. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11350. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11351. \label{fig:Lvec-concrete-syntax}
  11352. \index{subject}{Ltup@\LangVec{} concrete syntax}
  11353. \end{figure}
  11354. \begin{figure}[tp]
  11355. \centering
  11356. \begin{tcolorbox}[colback=white]
  11357. \small
  11358. {\if\edition\racketEd
  11359. \[
  11360. \begin{array}{l}
  11361. \gray{\LintOpAST} \\ \hline
  11362. \gray{\LvarASTRacket{}} \\ \hline
  11363. \gray{\LifASTRacket{}} \\ \hline
  11364. \gray{\LwhileASTRacket{}} \\ \hline
  11365. \LtupASTRacket{} \\
  11366. \begin{array}{lcl}
  11367. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11368. \end{array}
  11369. \end{array}
  11370. \]
  11371. \fi}
  11372. {\if\edition\pythonEd\pythonColor
  11373. \[
  11374. \begin{array}{l}
  11375. \gray{\LintASTPython} \\ \hline
  11376. \gray{\LvarASTPython} \\ \hline
  11377. \gray{\LifASTPython} \\ \hline
  11378. \gray{\LwhileASTPython} \\ \hline
  11379. \LtupASTPython \\
  11380. \begin{array}{lcl}
  11381. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11382. \end{array}
  11383. \end{array}
  11384. \]
  11385. \fi}
  11386. \end{tcolorbox}
  11387. \caption{The abstract syntax of \LangVec{}.}
  11388. \label{fig:Lvec-syntax}
  11389. \index{subject}{Ltup@\LangVec{} abstract syntax}
  11390. \end{figure}
  11391. Tuples raise several interesting new issues. First, variable binding
  11392. performs a shallow copy in dealing with tuples, which means that
  11393. different variables can refer to the same tuple; that is, two
  11394. variables can be \emph{aliases}\index{subject}{alias} for the same
  11395. entity. Consider the following example, in which \code{t1} and
  11396. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11397. different tuple value with equal elements. The result of the
  11398. program is \code{42}.
  11399. \begin{center}
  11400. \begin{minipage}{0.96\textwidth}
  11401. {\if\edition\racketEd
  11402. \begin{lstlisting}
  11403. (let ([t1 (vector 3 7)])
  11404. (let ([t2 t1])
  11405. (let ([t3 (vector 3 7)])
  11406. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11407. 42
  11408. 0))))
  11409. \end{lstlisting}
  11410. \fi}
  11411. {\if\edition\pythonEd\pythonColor
  11412. \begin{lstlisting}
  11413. t1 = 3, 7
  11414. t2 = t1
  11415. t3 = 3, 7
  11416. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11417. \end{lstlisting}
  11418. \fi}
  11419. \end{minipage}
  11420. \end{center}
  11421. {\if\edition\racketEd
  11422. Whether two variables are aliased or not affects what happens
  11423. when the underlying tuple is mutated\index{subject}{mutation}.
  11424. Consider the following example in which \code{t1} and \code{t2}
  11425. again refer to the same tuple value.
  11426. \begin{center}
  11427. \begin{minipage}{0.96\textwidth}
  11428. \begin{lstlisting}
  11429. (let ([t1 (vector 3 7)])
  11430. (let ([t2 t1])
  11431. (let ([_ (vector-set! t2 0 42)])
  11432. (vector-ref t1 0))))
  11433. \end{lstlisting}
  11434. \end{minipage}
  11435. \end{center}
  11436. The mutation through \code{t2} is visible in referencing the tuple
  11437. from \code{t1}, so the result of this program is \code{42}.
  11438. \fi}
  11439. The next issue concerns the lifetime of tuples. When does a tuple's
  11440. lifetime end? Notice that \LangVec{} does not include an operation
  11441. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11442. to any notion of static scoping.
  11443. %
  11444. {\if\edition\racketEd
  11445. %
  11446. For example, the following program returns \code{42} even though the
  11447. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11448. that reads from the vector to which it was bound.
  11449. \begin{center}
  11450. \begin{minipage}{0.96\textwidth}
  11451. \begin{lstlisting}
  11452. (let ([v (vector (vector 44))])
  11453. (let ([x (let ([w (vector 42)])
  11454. (let ([_ (vector-set! v 0 w)])
  11455. 0))])
  11456. (+ x (vector-ref (vector-ref v 0) 0))))
  11457. \end{lstlisting}
  11458. \end{minipage}
  11459. \end{center}
  11460. \fi}
  11461. %
  11462. {\if\edition\pythonEd\pythonColor
  11463. %
  11464. For example, the following program returns \code{42} even though the
  11465. variable \code{x} goes out of scope when the function returns, prior
  11466. to reading the tuple element at index $0$. (We study the compilation
  11467. of functions in chapter~\ref{ch:Lfun}.)
  11468. %
  11469. \begin{center}
  11470. \begin{minipage}{0.96\textwidth}
  11471. \begin{lstlisting}
  11472. def f():
  11473. x = 42, 43
  11474. return x
  11475. t = f()
  11476. print(t[0])
  11477. \end{lstlisting}
  11478. \end{minipage}
  11479. \end{center}
  11480. \fi}
  11481. %
  11482. From the perspective of programmer-observable behavior, tuples live
  11483. forever. However, if they really lived forever then many long-running
  11484. programs would run out of memory. To solve this problem, the
  11485. language's runtime system performs automatic garbage collection.
  11486. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11487. \LangVec{} language.
  11488. %
  11489. \racket{We define the \code{vector}, \code{vector-ref},
  11490. \code{vector-set!}, and \code{vector-length} operations for
  11491. \LangVec{} in terms of the corresponding operations in Racket. One
  11492. subtle point is that the \code{vector-set!} operation returns the
  11493. \code{\#<void>} value.}
  11494. %
  11495. \python{We represent tuples with Python lists in the interpreter
  11496. because we need to write to them
  11497. (section~\ref{sec:expose-allocation}). (Python tuples are
  11498. immutable.) We define element access, the \code{is} operator, and
  11499. the \code{len} operator for \LangVec{} in terms of the corresponding
  11500. operations in Python.}
  11501. \begin{figure}[tbp]
  11502. \begin{tcolorbox}[colback=white]
  11503. {\if\edition\racketEd
  11504. \begin{lstlisting}
  11505. (define interp-Lvec-class
  11506. (class interp-Lwhile-class
  11507. (super-new)
  11508. (define/override (interp-op op)
  11509. (match op
  11510. ['eq? (lambda (v1 v2)
  11511. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11512. (and (boolean? v1) (boolean? v2))
  11513. (and (vector? v1) (vector? v2))
  11514. (and (void? v1) (void? v2)))
  11515. (eq? v1 v2)]))]
  11516. ['vector vector]
  11517. ['vector-length vector-length]
  11518. ['vector-ref vector-ref]
  11519. ['vector-set! vector-set!]
  11520. [else (super interp-op op)]
  11521. ))
  11522. (define/override ((interp-exp env) e)
  11523. (match e
  11524. [(HasType e t) ((interp-exp env) e)]
  11525. [else ((super interp-exp env) e)]
  11526. ))
  11527. ))
  11528. (define (interp-Lvec p)
  11529. (send (new interp-Lvec-class) interp-program p))
  11530. \end{lstlisting}
  11531. \fi}
  11532. %
  11533. {\if\edition\pythonEd\pythonColor
  11534. \begin{lstlisting}
  11535. class InterpLtup(InterpLwhile):
  11536. def interp_cmp(self, cmp):
  11537. match cmp:
  11538. case Is():
  11539. return lambda x, y: x is y
  11540. case _:
  11541. return super().interp_cmp(cmp)
  11542. def interp_exp(self, e, env):
  11543. match e:
  11544. case Tuple(es, Load()):
  11545. return tuple([self.interp_exp(e, env) for e in es])
  11546. case Subscript(tup, index, Load()):
  11547. t = self.interp_exp(tup, env)
  11548. n = self.interp_exp(index, env)
  11549. return t[n]
  11550. case _:
  11551. return super().interp_exp(e, env)
  11552. \end{lstlisting}
  11553. \fi}
  11554. \end{tcolorbox}
  11555. \caption{Interpreter for the \LangVec{} language.}
  11556. \label{fig:interp-Lvec}
  11557. \end{figure}
  11558. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11559. \LangVec{}.
  11560. %
  11561. The type of a tuple is a
  11562. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11563. type for each of its elements.
  11564. %
  11565. \racket{To create the s-expression for the \code{Vector} type, we use the
  11566. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11567. operator} \code{,@} to insert the list \code{t*} without its usual
  11568. start and end parentheses. \index{subject}{unquote-splicing}}
  11569. %
  11570. The type of accessing the ith element of a tuple is the ith element
  11571. type of the tuple's type, if there is one. If not, an error is
  11572. signaled. Note that the index \code{i} is required to be a constant
  11573. integer (and not, for example, a call to
  11574. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11575. can determine the element's type given the tuple type.
  11576. %
  11577. \racket{
  11578. Regarding writing an element to a tuple, the element's type must
  11579. be equal to the ith element type of the tuple's type.
  11580. The result type is \code{Void}.}
  11581. %% When allocating a tuple,
  11582. %% we need to know which elements of the tuple are themselves tuples for
  11583. %% the purposes of garbage collection. We can obtain this information
  11584. %% during type checking. The type checker shown in
  11585. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11586. %% expression; it also
  11587. %% %
  11588. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11589. %% where $T$ is the tuple's type.
  11590. %
  11591. %records the type of each tuple expression in a new field named \code{has\_type}.
  11592. \begin{figure}[tp]
  11593. \begin{tcolorbox}[colback=white]
  11594. {\if\edition\racketEd
  11595. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11596. (define type-check-Lvec-class
  11597. (class type-check-Lif-class
  11598. (super-new)
  11599. (inherit check-type-equal?)
  11600. (define/override (type-check-exp env)
  11601. (lambda (e)
  11602. (define recur (type-check-exp env))
  11603. (match e
  11604. [(Prim 'vector es)
  11605. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11606. (define t `(Vector ,@t*))
  11607. (values (Prim 'vector e*) t)]
  11608. [(Prim 'vector-ref (list e1 (Int i)))
  11609. (define-values (e1^ t) (recur e1))
  11610. (match t
  11611. [`(Vector ,ts ...)
  11612. (unless (and (0 . <= . i) (i . < . (length ts)))
  11613. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11614. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11615. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11616. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11617. (define-values (e-vec t-vec) (recur e1))
  11618. (define-values (e-elt^ t-elt) (recur elt))
  11619. (match t-vec
  11620. [`(Vector ,ts ...)
  11621. (unless (and (0 . <= . i) (i . < . (length ts)))
  11622. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11623. (check-type-equal? (list-ref ts i) t-elt e)
  11624. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11625. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11626. [(Prim 'vector-length (list e))
  11627. (define-values (e^ t) (recur e))
  11628. (match t
  11629. [`(Vector ,ts ...)
  11630. (values (Prim 'vector-length (list e^)) 'Integer)]
  11631. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11632. [(Prim 'eq? (list arg1 arg2))
  11633. (define-values (e1 t1) (recur arg1))
  11634. (define-values (e2 t2) (recur arg2))
  11635. (match* (t1 t2)
  11636. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11637. [(other wise) (check-type-equal? t1 t2 e)])
  11638. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11639. [else ((super type-check-exp env) e)]
  11640. )))
  11641. ))
  11642. (define (type-check-Lvec p)
  11643. (send (new type-check-Lvec-class) type-check-program p))
  11644. \end{lstlisting}
  11645. \fi}
  11646. {\if\edition\pythonEd\pythonColor
  11647. \begin{lstlisting}
  11648. class TypeCheckLtup(TypeCheckLwhile):
  11649. def type_check_exp(self, e, env):
  11650. match e:
  11651. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11652. l = self.type_check_exp(left, env)
  11653. r = self.type_check_exp(right, env)
  11654. check_type_equal(l, r, e)
  11655. return bool
  11656. case Tuple(es, Load()):
  11657. ts = [self.type_check_exp(e, env) for e in es]
  11658. e.has_type = TupleType(ts)
  11659. return e.has_type
  11660. case Subscript(tup, Constant(i), Load()):
  11661. tup_ty = self.type_check_exp(tup, env)
  11662. i_ty = self.type_check_exp(Constant(i), env)
  11663. check_type_equal(i_ty, int, i)
  11664. match tup_ty:
  11665. case TupleType(ts):
  11666. return ts[i]
  11667. case _:
  11668. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11669. case _:
  11670. return super().type_check_exp(e, env)
  11671. \end{lstlisting}
  11672. \fi}
  11673. \end{tcolorbox}
  11674. \caption{Type checker for the \LangVec{} language.}
  11675. \label{fig:type-check-Lvec}
  11676. \end{figure}
  11677. \section{Garbage Collection}
  11678. \label{sec:GC}
  11679. Garbage collection is a runtime technique for reclaiming space on the
  11680. heap that will not be used in the future of the running program. We
  11681. use the term \emph{object}\index{subject}{object} to refer to any
  11682. value that is stored in the heap, which for now includes only
  11683. tuples.%
  11684. %
  11685. \footnote{The term \emph{object} as it is used in the context of
  11686. object-oriented programming has a more specific meaning than the
  11687. way in which we use the term here.}
  11688. %
  11689. Unfortunately, it is impossible to know precisely which objects will
  11690. be accessed in the future and which will not. Instead, garbage
  11691. collectors overapproximate the set of objects that will be accessed by
  11692. identifying which objects can possibly be accessed. The running
  11693. program can directly access objects that are in registers and on the
  11694. procedure call stack. It can also transitively access the elements of
  11695. tuples, starting with a tuple whose address is in a register or on the
  11696. procedure call stack. We define the \emph{root
  11697. set}\index{subject}{root set} to be all the tuple addresses that are
  11698. in registers or on the procedure call stack. We define the \emph{live
  11699. objects}\index{subject}{live objects} to be the objects that are
  11700. reachable from the root set. Garbage collectors reclaim the space that
  11701. is allocated to objects that are no longer live. \index{subject}{allocate}
  11702. That means that some objects may not get reclaimed as soon as they could be,
  11703. but at least
  11704. garbage collectors do not reclaim the space dedicated to objects that
  11705. will be accessed in the future! The programmer can influence which
  11706. objects get reclaimed by causing them to become unreachable.
  11707. So the goal of the garbage collector is twofold:
  11708. \begin{enumerate}
  11709. \item to preserve all the live objects, and
  11710. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11711. \end{enumerate}
  11712. \subsection{Two-Space Copying Collector}
  11713. Here we study a relatively simple algorithm for garbage collection
  11714. that is the basis of many state-of-the-art garbage
  11715. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11716. particular, we describe a two-space copying
  11717. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11718. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11719. collector} \index{subject}{two-space copying collector}
  11720. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11721. what happens in a two-space collector, showing two time steps, prior
  11722. to garbage collection (on the top) and after garbage collection (on
  11723. the bottom). In a two-space collector, the heap is divided into two
  11724. parts named the FromSpace\index{subject}{FromSpace} and the
  11725. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11726. FromSpace until there is not enough room for the next allocation
  11727. request. At that point, the garbage collector goes to work to make
  11728. room for the next allocation.
  11729. A copying collector makes more room by copying all the live objects
  11730. from the FromSpace into the ToSpace and then performs a sleight of
  11731. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11732. as the new ToSpace. In the example shown in
  11733. figure~\ref{fig:copying-collector}, the root set consists of three
  11734. pointers, one in a register and two on the stack. All the live
  11735. objects have been copied to the ToSpace (the right-hand side of
  11736. figure~\ref{fig:copying-collector}) in a way that preserves the
  11737. pointer relationships. For example, the pointer in the register still
  11738. points to a tuple that in turn points to two other tuples. There are
  11739. four tuples that are not reachable from the root set and therefore do
  11740. not get copied into the ToSpace.
  11741. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11742. created by a well-typed program in \LangVec{} because it contains a
  11743. cycle. However, creating cycles will be possible once we get to
  11744. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11745. to deal with cycles to begin with, so we will not need to revisit this
  11746. issue.
  11747. \begin{figure}[tbp]
  11748. \centering
  11749. \begin{tcolorbox}[colback=white]
  11750. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11751. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11752. \\[5ex]
  11753. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11754. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11755. \end{tcolorbox}
  11756. \caption{A copying collector in action.}
  11757. \label{fig:copying-collector}
  11758. \end{figure}
  11759. \subsection{Graph Copying via Cheney's Algorithm}
  11760. \label{sec:cheney}
  11761. \index{subject}{Cheney's algorithm}
  11762. Let us take a closer look at the copying of the live objects. The
  11763. allocated\index{subject}{allocate} objects and pointers can be viewed
  11764. as a graph, and we need to copy the part of the graph that is
  11765. reachable from the root set. To make sure that we copy all the
  11766. reachable vertices in the graph, we need an exhaustive graph traversal
  11767. algorithm, such as depth-first search or breadth-first
  11768. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11769. take into account the possibility of cycles by marking which vertices
  11770. have already been visited, so to ensure termination of the
  11771. algorithm. These search algorithms also use a data structure such as a
  11772. stack or queue as a to-do list to keep track of the vertices that need
  11773. to be visited. We use breadth-first search and a trick due to
  11774. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11775. copying tuples into the ToSpace.
  11776. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11777. copy progresses. The queue is represented by a chunk of contiguous
  11778. memory at the beginning of the ToSpace, using two pointers to track
  11779. the front and the back of the queue, called the \emph{free pointer}
  11780. and the \emph{scan pointer}, respectively. The algorithm starts by
  11781. copying all tuples that are immediately reachable from the root set
  11782. into the ToSpace to form the initial queue. When we copy a tuple, we
  11783. mark the old tuple to indicate that it has been visited. We discuss
  11784. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11785. that any pointers inside the copied tuples in the queue still point
  11786. back to the FromSpace. Once the initial queue has been created, the
  11787. algorithm enters a loop in which it repeatedly processes the tuple at
  11788. the front of the queue and pops it off the queue. To process a tuple,
  11789. the algorithm copies all the objects that are directly reachable from it
  11790. to the ToSpace, placing them at the back of the queue. The algorithm
  11791. then updates the pointers in the popped tuple so that they point to the
  11792. newly copied objects.
  11793. \begin{figure}[tbp]
  11794. \centering
  11795. \begin{tcolorbox}[colback=white]
  11796. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11797. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11798. \end{tcolorbox}
  11799. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11800. \label{fig:cheney}
  11801. \end{figure}
  11802. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11803. tuple whose second element is $42$ to the back of the queue. The other
  11804. pointer goes to a tuple that has already been copied, so we do not
  11805. need to copy it again, but we do need to update the pointer to the new
  11806. location. This can be accomplished by storing a \emph{forwarding
  11807. pointer}\index{subject}{forwarding pointer} to the new location in the
  11808. old tuple, when we initially copied the tuple into the
  11809. ToSpace. This completes one step of the algorithm. The algorithm
  11810. continues in this way until the queue is empty; that is, when the scan
  11811. pointer catches up with the free pointer.
  11812. \subsection{Data Representation}
  11813. \label{sec:data-rep-gc}
  11814. The garbage collector places some requirements on the data
  11815. representations used by our compiler. First, the garbage collector
  11816. needs to distinguish between pointers and other kinds of data such as
  11817. integers. The following are three ways to accomplish this:
  11818. \begin{enumerate}
  11819. \item Attach a tag to each object that identifies what type of
  11820. object it is~\citep{McCarthy:1960dz}.
  11821. \item Store different types of objects in different
  11822. regions~\citep{Steele:1977ab}.
  11823. \item Use type information from the program to either (a) generate
  11824. type-specific code for collecting, or (b) generate tables that
  11825. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11826. \end{enumerate}
  11827. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11828. need to tag objects in any case, so option 1 is a natural choice for those
  11829. languages. However, \LangVec{} is a statically typed language, so it
  11830. would be unfortunate to require tags on every object, especially small
  11831. and pervasive objects like integers and Booleans. Option 3 is the
  11832. best-performing choice for statically typed languages, but it comes with
  11833. a relatively high implementation complexity. To keep this chapter
  11834. within a reasonable scope of complexity, we recommend a combination of options
  11835. 1 and 2, using separate strategies for the stack and the heap.
  11836. Regarding the stack, we recommend using a separate stack for pointers,
  11837. which we call the \emph{root stack}\index{subject}{root stack}
  11838. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11839. That is, when a local variable needs to be spilled and is of type
  11840. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11841. root stack instead of putting it on the procedure call
  11842. stack. Furthermore, we always spill tuple-typed variables if they are
  11843. live during a call to the collector, thereby ensuring that no pointers
  11844. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11845. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11846. contrasts it with the data layout using a root stack. The root stack
  11847. contains the two pointers from the regular stack and also the pointer
  11848. in the second register.
  11849. \begin{figure}[tbp]
  11850. \centering
  11851. \begin{tcolorbox}[colback=white]
  11852. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11853. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11854. \end{tcolorbox}
  11855. \caption{Maintaining a root stack to facilitate garbage collection.}
  11856. \label{fig:shadow-stack}
  11857. \end{figure}
  11858. The problem of distinguishing between pointers and other kinds of data
  11859. also arises inside each tuple on the heap. We solve this problem by
  11860. attaching a tag, an extra 64 bits, to each
  11861. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11862. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11863. Note that we have drawn the bits in a big-endian way, from right to left,
  11864. with bit location 0 (the least significant bit) on the far right,
  11865. which corresponds to the direction of the x86 shifting instructions
  11866. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11867. is dedicated to specifying which elements of the tuple are pointers,
  11868. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11869. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11870. data. The pointer mask starts at bit location 7. We limit tuples to a
  11871. maximum size of fifty elements, so we need 50 bits for the pointer
  11872. mask.%
  11873. %
  11874. \footnote{A production-quality compiler would handle
  11875. arbitrarily sized tuples and use a more complex approach.}
  11876. %
  11877. The tag also contains two other pieces of information. The length of
  11878. the tuple (number of elements) is stored in bits at locations 1 through
  11879. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11880. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11881. has not yet been copied. If the bit has value 0, then the entire tag
  11882. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11883. zero in any case, because our tuples are 8-byte aligned.)
  11884. \begin{figure}[tbp]
  11885. \centering
  11886. \begin{tcolorbox}[colback=white]
  11887. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11888. \end{tcolorbox}
  11889. \caption{Representation of tuples in the heap.}
  11890. \label{fig:tuple-rep}
  11891. \end{figure}
  11892. \subsection{Implementation of the Garbage Collector}
  11893. \label{sec:organize-gz}
  11894. \index{subject}{prelude}
  11895. An implementation of the copying collector is provided in the
  11896. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11897. interface to the garbage collector that is used by the compiler. The
  11898. \code{initialize} function creates the FromSpace, ToSpace, and root
  11899. stack and should be called in the prelude of the \code{main}
  11900. function. The arguments of \code{initialize} are the root stack size
  11901. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11902. good choice for both. The \code{initialize} function puts the address
  11903. of the beginning of the FromSpace into the global variable
  11904. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11905. the address that is one past the last element of the FromSpace. We use
  11906. half-open intervals to represent chunks of
  11907. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11908. points to the first element of the root stack.
  11909. As long as there is room left in the FromSpace, your generated code
  11910. can allocate\index{subject}{allocate} tuples simply by moving the
  11911. \code{free\_ptr} forward.
  11912. %
  11913. The amount of room left in the FromSpace is the difference between the
  11914. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11915. function should be called when there is not enough room left in the
  11916. FromSpace for the next allocation. The \code{collect} function takes
  11917. a pointer to the current top of the root stack (one past the last item
  11918. that was pushed) and the number of bytes that need to be
  11919. allocated. The \code{collect} function performs the copying collection
  11920. and leaves the heap in a state such that there is enough room for the
  11921. next allocation.
  11922. \begin{figure}[tbp]
  11923. \begin{tcolorbox}[colback=white]
  11924. \begin{lstlisting}
  11925. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11926. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11927. int64_t* free_ptr;
  11928. int64_t* fromspace_begin;
  11929. int64_t* fromspace_end;
  11930. int64_t** rootstack_begin;
  11931. \end{lstlisting}
  11932. \end{tcolorbox}
  11933. \caption{The compiler's interface to the garbage collector.}
  11934. \label{fig:gc-header}
  11935. \end{figure}
  11936. %% \begin{exercise}
  11937. %% In the file \code{runtime.c} you will find the implementation of
  11938. %% \code{initialize} and a partial implementation of \code{collect}.
  11939. %% The \code{collect} function calls another function, \code{cheney},
  11940. %% to perform the actual copy, and that function is left to the reader
  11941. %% to implement. The following is the prototype for \code{cheney}.
  11942. %% \begin{lstlisting}
  11943. %% static void cheney(int64_t** rootstack_ptr);
  11944. %% \end{lstlisting}
  11945. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11946. %% rootstack (which is an array of pointers). The \code{cheney} function
  11947. %% also communicates with \code{collect} through the global
  11948. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11949. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11950. %% the ToSpace:
  11951. %% \begin{lstlisting}
  11952. %% static int64_t* tospace_begin;
  11953. %% static int64_t* tospace_end;
  11954. %% \end{lstlisting}
  11955. %% The job of the \code{cheney} function is to copy all the live
  11956. %% objects (reachable from the root stack) into the ToSpace, update
  11957. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11958. %% update the root stack so that it points to the objects in the
  11959. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11960. %% and ToSpace.
  11961. %% \end{exercise}
  11962. The introduction of garbage collection has a nontrivial impact on our
  11963. compiler passes. We introduce a new compiler pass named
  11964. \code{expose\_allocation} that elaborates the code for allocating
  11965. tuples. We also make significant changes to
  11966. \code{select\_instructions}, \code{build\_interference},
  11967. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11968. make minor changes in several more passes.
  11969. The following program serves as our running example. It creates
  11970. two tuples, one nested inside the other. Both tuples have length
  11971. one. The program accesses the element in the inner tuple.
  11972. % tests/vectors_test_17.rkt
  11973. {\if\edition\racketEd
  11974. \begin{lstlisting}
  11975. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11976. \end{lstlisting}
  11977. \fi}
  11978. % tests/tuple/get_get.py
  11979. {\if\edition\pythonEd\pythonColor
  11980. \begin{lstlisting}
  11981. v1 = (42,)
  11982. v2 = (v1,)
  11983. print(v2[0][0])
  11984. \end{lstlisting}
  11985. \fi}
  11986. %% {\if\edition\racketEd
  11987. %% \section{Shrink}
  11988. %% \label{sec:shrink-Lvec}
  11989. %% Recall that the \code{shrink} pass translates the primitives operators
  11990. %% into a smaller set of primitives.
  11991. %% %
  11992. %% This pass comes after type checking, and the type checker adds a
  11993. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11994. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11995. %% \fi}
  11996. \section{Expose Allocation}
  11997. \label{sec:expose-allocation}
  11998. The pass \code{expose\_allocation} lowers tuple creation into making a
  11999. conditional call to the collector followed by allocating the
  12000. appropriate amount of memory and initializing it. We choose to place
  12001. the \code{expose\_allocation} pass before
  12002. \code{remove\_complex\_operands} because it generates code that
  12003. contains complex operands. However, with some care it can also be
  12004. placed after \code{remove\_complex\_operands}, which would simplify
  12005. tuple creation by removing the need to assign the initializing
  12006. expressions to temporary variables (see below).
  12007. The output of \code{expose\_allocation} is a language \LangAlloc{}
  12008. that replaces tuple creation with new lower-level forms that we use in the
  12009. translation of tuple creation\index{subject}{Lalloc@\LangAlloc{}}.
  12010. %
  12011. {\if\edition\racketEd
  12012. \[
  12013. \begin{array}{lcl}
  12014. \Exp &::=& (\key{collect} \,\itm{int})
  12015. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  12016. \MID (\key{global-value} \,\itm{name})
  12017. \end{array}
  12018. \]
  12019. \fi}
  12020. {\if\edition\pythonEd\pythonColor
  12021. \[
  12022. \begin{array}{lcl}
  12023. \Exp &::=& \key{collect}(\itm{int})
  12024. \MID \key{allocate}(\itm{int},\itm{type})
  12025. \MID \key{global\_value}(\itm{name}) \\
  12026. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  12027. \end{array}
  12028. \]
  12029. \fi}
  12030. %
  12031. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  12032. there be $n$ bytes ready to be allocated. During instruction
  12033. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  12034. form will become a call to the \code{collect} function in
  12035. \code{runtime.c}.
  12036. %
  12037. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  12038. space at the front for the 64-bit tag), but the elements are not
  12039. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  12040. of the tuple:
  12041. %
  12042. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  12043. %
  12044. where $\Type_i$ is the type of the $i$th element.
  12045. %
  12046. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  12047. variable, such as \code{free\_ptr}.
  12048. \racket{
  12049. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  12050. can be obtained by running the
  12051. \code{type-check-Lvec-has-type} type checker immediately before the
  12052. \code{expose\_allocation} pass. This version of the type checker
  12053. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  12054. around each tuple creation. The concrete syntax
  12055. for \code{HasType} is \code{has-type}.}
  12056. The following shows the transformation of tuple creation into (1) a
  12057. sequence of temporary variable bindings for the initializing
  12058. expressions, (2) a conditional call to \code{collect}, (3) a call to
  12059. \code{allocate}, and (4) the initialization of the tuple. The
  12060. \itm{len} placeholder refers to the length of the tuple, and
  12061. \itm{bytes} is the total number of bytes that need to be allocated for
  12062. the tuple, which is 8 for the tag plus \itm{len} times 8.
  12063. %
  12064. \python{The \itm{type} needed for the second argument of the
  12065. \code{allocate} form can be obtained from the \code{has\_type} field
  12066. of the tuple AST node, which is stored there by running the type
  12067. checker for \LangVec{} immediately before this pass.}
  12068. %
  12069. \begin{center}
  12070. \begin{minipage}{\textwidth}
  12071. {\if\edition\racketEd
  12072. \begin{lstlisting}
  12073. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12074. |$\Longrightarrow$|
  12075. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12076. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12077. (global-value fromspace_end))
  12078. (void)
  12079. (collect |\itm{bytes}|))])
  12080. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12081. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12082. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12083. |$v$|) ... )))) ...)
  12084. \end{lstlisting}
  12085. \fi}
  12086. {\if\edition\pythonEd\pythonColor
  12087. \begin{lstlisting}
  12088. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12089. |$\Longrightarrow$|
  12090. begin:
  12091. |$x_0$| = |$e_0$|
  12092. |$\vdots$|
  12093. |$x_{n-1}$| = |$e_{n-1}$|
  12094. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12095. 0
  12096. else:
  12097. collect(|\itm{bytes}|)
  12098. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12099. |$v$|[0] = |$x_0$|
  12100. |$\vdots$|
  12101. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12102. |$v$|
  12103. \end{lstlisting}
  12104. \fi}
  12105. \end{minipage}
  12106. \end{center}
  12107. %
  12108. \noindent The sequencing of the initializing expressions
  12109. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12110. they may trigger garbage collection and we cannot have an allocated
  12111. but uninitialized tuple on the heap during a collection.
  12112. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12113. \code{expose\_allocation} pass on our running example.
  12114. \begin{figure}[tbp]
  12115. \begin{tcolorbox}[colback=white]
  12116. % tests/s2_17.rkt
  12117. {\if\edition\racketEd
  12118. \begin{lstlisting}
  12119. (vector-ref
  12120. (vector-ref
  12121. (let ([vecinit6
  12122. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12123. (global-value fromspace_end))
  12124. (void)
  12125. (collect 16))])
  12126. (let ([alloc2 (allocate 1 (Vector Integer))])
  12127. (let ([_3 (vector-set! alloc2 0 42)])
  12128. alloc2)))])
  12129. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12130. (global-value fromspace_end))
  12131. (void)
  12132. (collect 16))])
  12133. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12134. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12135. alloc5))))
  12136. 0)
  12137. 0)
  12138. \end{lstlisting}
  12139. \fi}
  12140. {\if\edition\pythonEd\pythonColor
  12141. \begin{lstlisting}
  12142. v1 = begin:
  12143. init.514 = 42
  12144. if (free_ptr + 16) < fromspace_end:
  12145. else:
  12146. collect(16)
  12147. alloc.513 = allocate(1,tuple[int])
  12148. alloc.513[0] = init.514
  12149. alloc.513
  12150. v2 = begin:
  12151. init.516 = v1
  12152. if (free_ptr + 16) < fromspace_end:
  12153. else:
  12154. collect(16)
  12155. alloc.515 = allocate(1,tuple[tuple[int]])
  12156. alloc.515[0] = init.516
  12157. alloc.515
  12158. print(v2[0][0])
  12159. \end{lstlisting}
  12160. \fi}
  12161. \end{tcolorbox}
  12162. \caption{Output of the \code{expose\_allocation} pass.}
  12163. \label{fig:expose-alloc-output}
  12164. \end{figure}
  12165. \section{Remove Complex Operands}
  12166. \label{sec:remove-complex-opera-Lvec}
  12167. {\if\edition\racketEd
  12168. %
  12169. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12170. should be treated as complex operands.
  12171. %
  12172. \fi}
  12173. %
  12174. {\if\edition\pythonEd\pythonColor
  12175. %
  12176. The expressions \code{allocate}, \code{begin},
  12177. and tuple access should be treated as complex operands. The
  12178. subexpressions of tuple access must be atomic.
  12179. The \code{global\_value} AST node is atomic.
  12180. %
  12181. \fi}
  12182. %% A new case for
  12183. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12184. %% handled carefully to prevent the \code{Prim} node from being separated
  12185. %% from its enclosing \code{HasType}.
  12186. Figure~\ref{fig:Lvec-anf-syntax}
  12187. shows the grammar for the output language \LangAllocANF{} of this
  12188. pass, which is \LangAlloc{} in monadic normal form.
  12189. \newcommand{\LtupMonadASTRacket}{
  12190. \begin{array}{rcl}
  12191. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12192. \MID \GLOBALVALUE{\Var}
  12193. \end{array}
  12194. }
  12195. \newcommand{\LtupMonadASTPython}{
  12196. \begin{array}{rcl}
  12197. \Atm &::=& \GLOBALVALUE{\Var} \\
  12198. \Exp &::=& \GET{\Atm}{\Atm}
  12199. \MID \LEN{\Atm}\\
  12200. &\MID& \ALLOCATE{\Int}{\Type}\\
  12201. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12202. &\MID& \COLLECT{\Int}
  12203. \end{array}
  12204. }
  12205. \begin{figure}[tp]
  12206. \centering
  12207. \begin{tcolorbox}[colback=white]
  12208. \small
  12209. {\if\edition\racketEd
  12210. \[
  12211. \begin{array}{l}
  12212. \gray{\LvarMonadASTRacket} \\ \hline
  12213. \gray{\LifMonadASTRacket} \\ \hline
  12214. \gray{\LwhileMonadASTRacket} \\ \hline
  12215. \LtupMonadASTRacket \\
  12216. \begin{array}{rcl}
  12217. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12218. \end{array}
  12219. \end{array}
  12220. \]
  12221. \fi}
  12222. {\if\edition\pythonEd\pythonColor
  12223. \[
  12224. \begin{array}{l}
  12225. \gray{\LvarMonadASTPython} \\ \hline
  12226. \gray{\LifMonadASTPython} \\ \hline
  12227. \gray{\LwhileMonadASTPython} \\ \hline
  12228. \LtupMonadASTPython \\
  12229. \begin{array}{rcl}
  12230. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12231. \end{array}
  12232. \end{array}
  12233. \]
  12234. \fi}
  12235. \end{tcolorbox}
  12236. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12237. \label{fig:Lvec-anf-syntax}
  12238. \index{subject}{Ltupmon@\LangAllocANF{} abstract syntax}
  12239. \end{figure}
  12240. \section{Explicate Control and the \LangCVec{} Language}
  12241. \label{sec:explicate-control-r3}
  12242. \newcommand{\CtupASTRacket}{
  12243. \begin{array}{lcl}
  12244. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12245. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12246. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12247. &\MID& \VECLEN{\Atm} \\
  12248. &\MID& \GLOBALVALUE{\Var} \\
  12249. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12250. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12251. \end{array}
  12252. }
  12253. \newcommand{\CtupASTPython}{
  12254. \begin{array}{lcl}
  12255. \Atm &::=& \GLOBALVALUE{\Var} \\
  12256. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12257. &\MID& \LEN{\Atm} \\
  12258. \Stmt &::=& \COLLECT{\Int}
  12259. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12260. \end{array}
  12261. }
  12262. \begin{figure}[tp]
  12263. \begin{tcolorbox}[colback=white]
  12264. \small
  12265. {\if\edition\racketEd
  12266. \[
  12267. \begin{array}{l}
  12268. \gray{\CvarASTRacket} \\ \hline
  12269. \gray{\CifASTRacket} \\ \hline
  12270. \gray{\CloopASTRacket} \\ \hline
  12271. \CtupASTRacket \\
  12272. \begin{array}{lcl}
  12273. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12274. \end{array}
  12275. \end{array}
  12276. \]
  12277. \fi}
  12278. {\if\edition\pythonEd\pythonColor
  12279. \[
  12280. \begin{array}{l}
  12281. \gray{\CifASTPython} \\ \hline
  12282. \CtupASTPython \\
  12283. \begin{array}{lcl}
  12284. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12285. \end{array}
  12286. \end{array}
  12287. \]
  12288. \fi}
  12289. \end{tcolorbox}
  12290. \caption{The abstract syntax of \LangCVec{}, extending
  12291. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12292. (figure~\ref{fig:c1-syntax})}.}
  12293. \label{fig:c2-syntax}
  12294. \index{subject}{Cvec@\LangCVec{} abstract syntax}
  12295. \end{figure}
  12296. The output of \code{explicate\_control} is a program in the
  12297. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12298. shows the definition of the abstract syntax.
  12299. %
  12300. %% \racket{(The concrete syntax is defined in
  12301. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12302. %
  12303. The new expressions of \LangCVec{} include \key{allocate},
  12304. %
  12305. \racket{\key{vector-ref}, and \key{vector-set!},}
  12306. %
  12307. \python{accessing tuple elements,}
  12308. %
  12309. and \key{global\_value}.
  12310. %
  12311. \python{\LangCVec{} also includes the \code{collect} statement and
  12312. assignment to a tuple element.}
  12313. %
  12314. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12315. %
  12316. The \code{explicate\_control} pass can treat these new forms much like
  12317. the other forms that we've already encountered. The output of the
  12318. \code{explicate\_control} pass on the running example is shown on the
  12319. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12320. section.
  12321. \section{Select Instructions and the \LangXGlobal{} Language}
  12322. \label{sec:select-instructions-gc}
  12323. \index{subject}{select instructions}
  12324. %% void (rep as zero)
  12325. %% allocate
  12326. %% collect (callq collect)
  12327. %% vector-ref
  12328. %% vector-set!
  12329. %% vector-length
  12330. %% global (postpone)
  12331. In this pass we generate x86 code for most of the new operations that
  12332. are needed to compile tuples, including \code{Allocate},
  12333. \code{Collect}, accessing tuple elements, and the \code{Is}
  12334. comparison.
  12335. %
  12336. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12337. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12338. \ref{fig:x86-2}). \index{subject}{x86}
  12339. The tuple read and write forms translate into \code{movq}
  12340. instructions. (The $+1$ in the offset serves to move past the tag at the
  12341. beginning of the tuple representation.)
  12342. %
  12343. \begin{center}
  12344. \begin{minipage}{\textwidth}
  12345. {\if\edition\racketEd
  12346. \begin{lstlisting}
  12347. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12348. |$\Longrightarrow$|
  12349. movq |$\itm{tup}'$|, %r11
  12350. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12351. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12352. |$\Longrightarrow$|
  12353. movq |$\itm{tup}'$|, %r11
  12354. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12355. movq $0, |$\itm{lhs'}$|
  12356. \end{lstlisting}
  12357. \fi}
  12358. {\if\edition\pythonEd\pythonColor
  12359. \begin{lstlisting}
  12360. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12361. |$\Longrightarrow$|
  12362. movq |$\itm{tup}'$|, %r11
  12363. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12364. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12365. |$\Longrightarrow$|
  12366. movq |$\itm{tup}'$|, %r11
  12367. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12368. \end{lstlisting}
  12369. \fi}
  12370. \end{minipage}
  12371. \end{center}
  12372. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12373. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12374. are obtained by translating from \LangCVec{} to x86.
  12375. %
  12376. The move of $\itm{tup}'$ to
  12377. register \code{r11} ensures that the offset expression
  12378. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12379. removing \code{r11} from consideration by the register allocator.
  12380. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12381. \code{rax}. Then the generated code for tuple assignment would be
  12382. \begin{lstlisting}
  12383. movq |$\itm{tup}'$|, %rax
  12384. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12385. \end{lstlisting}
  12386. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12387. \code{patch\_instructions} would insert a move through \code{rax}
  12388. as follows:
  12389. \begin{lstlisting}
  12390. movq |$\itm{tup}'$|, %rax
  12391. movq |$\itm{rhs}'$|, %rax
  12392. movq %rax, |$8(n+1)$|(%rax)
  12393. \end{lstlisting}
  12394. However, this sequence of instructions does not work because we're
  12395. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12396. $\itm{rhs}'$) at the same time!
  12397. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12398. be translated into a sequence of instructions that read the tag of the
  12399. tuple and extract the 6 bits that represent the tuple length, which
  12400. are the bits starting at index 1 and going up to and including bit 6.
  12401. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12402. (shift right) can be used to accomplish this.
  12403. We compile the \code{allocate} form to operations on the
  12404. \code{free\_ptr}, as shown next. This approach is called
  12405. \emph{inline allocation} because it implements allocation without a
  12406. function call by simply incrementing the allocation pointer. It is much
  12407. more efficient than calling a function for each allocation. The
  12408. address in the \code{free\_ptr} is the next free address in the
  12409. FromSpace, so we copy it into \code{r11} and then move it forward by
  12410. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12411. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12412. the tag. We then initialize the \itm{tag} and finally copy the
  12413. address in \code{r11} to the left-hand side. Refer to
  12414. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12415. %
  12416. \racket{We recommend using the Racket operations
  12417. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12418. during compilation.}
  12419. %
  12420. \python{We recommend using the bitwise-or operator \code{|} and the
  12421. shift-left operator \code{<<} to compute the tag during
  12422. compilation.}
  12423. %
  12424. The type annotation in the \code{allocate} form is used to determine
  12425. the pointer mask region of the tag.
  12426. %
  12427. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12428. address of the \code{free\_ptr} global variable using a special
  12429. instruction-pointer-relative addressing mode of the x86-64 processor.
  12430. In particular, the assembler computes the distance $d$ between the
  12431. address of \code{free\_ptr} and where the \code{rip} would be at that
  12432. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12433. \code{$d$(\%rip)}, which at runtime will compute the address of
  12434. \code{free\_ptr}.
  12435. %
  12436. {\if\edition\racketEd
  12437. \begin{lstlisting}
  12438. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12439. |$\Longrightarrow$|
  12440. movq free_ptr(%rip), %r11
  12441. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12442. movq $|$\itm{tag}$|, 0(%r11)
  12443. movq %r11, |$\itm{lhs}'$|
  12444. \end{lstlisting}
  12445. \fi}
  12446. {\if\edition\pythonEd\pythonColor
  12447. \begin{lstlisting}
  12448. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12449. |$\Longrightarrow$|
  12450. movq free_ptr(%rip), %r11
  12451. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12452. movq $|$\itm{tag}$|, 0(%r11)
  12453. movq %r11, |$\itm{lhs}'$|
  12454. \end{lstlisting}
  12455. \fi}
  12456. %
  12457. The \code{collect} form is compiled to a call to the \code{collect}
  12458. function in the runtime. The arguments to \code{collect} are (1) the
  12459. top of the root stack, and (2) the number of bytes that need to be
  12460. allocated. We use another dedicated register, \code{r15}, to store
  12461. the pointer to the top of the root stack. Therefore \code{r15} is not
  12462. available for use by the register allocator.
  12463. %
  12464. {\if\edition\racketEd
  12465. \begin{lstlisting}
  12466. (collect |$\itm{bytes}$|)
  12467. |$\Longrightarrow$|
  12468. movq %r15, %rdi
  12469. movq $|\itm{bytes}|, %rsi
  12470. callq collect
  12471. \end{lstlisting}
  12472. \fi}
  12473. {\if\edition\pythonEd\pythonColor
  12474. \begin{lstlisting}
  12475. collect(|$\itm{bytes}$|)
  12476. |$\Longrightarrow$|
  12477. movq %r15, %rdi
  12478. movq $|\itm{bytes}|, %rsi
  12479. callq collect
  12480. \end{lstlisting}
  12481. \fi}
  12482. {\if\edition\pythonEd\pythonColor
  12483. The \code{is} comparison is compiled similarly to the other comparison
  12484. operators, using the \code{cmpq} instruction. Because the value of a
  12485. tuple is its address, we can translate \code{is} into a simple check
  12486. for equality using the \code{e} condition code. \\
  12487. \begin{tabular}{lll}
  12488. \begin{minipage}{0.4\textwidth}
  12489. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12490. \end{minipage}
  12491. &
  12492. $\Rightarrow$
  12493. &
  12494. \begin{minipage}{0.4\textwidth}
  12495. \begin{lstlisting}
  12496. cmpq |$\Arg_2$|, |$\Arg_1$|
  12497. sete %al
  12498. movzbq %al, |$\Var$|
  12499. \end{lstlisting}
  12500. \end{minipage}
  12501. \end{tabular}
  12502. \fi}
  12503. \newcommand{\GrammarXGlobal}{
  12504. \begin{array}{lcl}
  12505. \Arg &::=& \itm{label} \key{(\%rip)}
  12506. \end{array}
  12507. }
  12508. \newcommand{\ASTXGlobalRacket}{
  12509. \begin{array}{lcl}
  12510. \Arg &::=& \GLOBAL{\itm{label}}
  12511. \end{array}
  12512. }
  12513. \begin{figure}[tp]
  12514. \begin{tcolorbox}[colback=white]
  12515. {\if\edition\racketEd
  12516. \[
  12517. \begin{array}{l}
  12518. \gray{\GrammarXIntRacket} \\ \hline
  12519. \gray{\GrammarXIfRacket} \\ \hline
  12520. \GrammarXGlobal \\
  12521. \begin{array}{lcl}
  12522. \LangXGlobalM{} &::= & \key{.globl main} \\
  12523. & & \key{main:} \; \Instr^{*}
  12524. \end{array}
  12525. \end{array}
  12526. \]
  12527. \fi}
  12528. {\if\edition\pythonEd\pythonColor
  12529. \[
  12530. \begin{array}{l}
  12531. \gray{\GrammarXIntPython} \\ \hline
  12532. \gray{\GrammarXIfPython} \\ \hline
  12533. \GrammarXGlobal \\
  12534. \begin{array}{lcl}
  12535. \LangXGlobalM{} &::= & \key{.globl main} \\
  12536. & & \key{main:} \; \Instr^{*}
  12537. \end{array}
  12538. \end{array}
  12539. \]
  12540. \fi}
  12541. \end{tcolorbox}
  12542. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12543. \label{fig:x86-2-concrete}
  12544. \end{figure}
  12545. \begin{figure}[tp]
  12546. \begin{tcolorbox}[colback=white]
  12547. \small
  12548. {\if\edition\racketEd
  12549. \[
  12550. \begin{array}{l}
  12551. \gray{\ASTXIntRacket} \\ \hline
  12552. \gray{\ASTXIfRacket} \\ \hline
  12553. \ASTXGlobalRacket \\
  12554. \begin{array}{lcl}
  12555. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12556. \end{array}
  12557. \end{array}
  12558. \]
  12559. \fi}
  12560. {\if\edition\pythonEd\pythonColor
  12561. \[
  12562. \begin{array}{l}
  12563. \gray{\ASTXIntPython} \\ \hline
  12564. \gray{\ASTXIfPython} \\ \hline
  12565. \ASTXGlobalRacket \\
  12566. \begin{array}{lcl}
  12567. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12568. \end{array}
  12569. \end{array}
  12570. \]
  12571. \fi}
  12572. \end{tcolorbox}
  12573. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12574. \label{fig:x86-2}
  12575. \end{figure}
  12576. The definitions of the concrete and abstract syntax of the
  12577. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12578. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12579. of global variables.
  12580. %
  12581. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12582. \code{select\_instructions} pass on the running example.
  12583. \begin{figure}[tbp]
  12584. \centering
  12585. \begin{tcolorbox}[colback=white]
  12586. {\if\edition\racketEd
  12587. % tests/s2_17.rkt
  12588. \begin{tabular}{lll}
  12589. \begin{minipage}{0.5\textwidth}
  12590. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12591. start:
  12592. tmp9 = (global-value free_ptr);
  12593. tmp0 = (+ tmp9 16);
  12594. tmp1 = (global-value fromspace_end);
  12595. if (< tmp0 tmp1)
  12596. goto block0;
  12597. else
  12598. goto block1;
  12599. block0:
  12600. _4 = (void);
  12601. goto block9;
  12602. block1:
  12603. (collect 16)
  12604. goto block9;
  12605. block9:
  12606. alloc2 = (allocate 1 (Vector Integer));
  12607. _3 = (vector-set! alloc2 0 42);
  12608. vecinit6 = alloc2;
  12609. tmp2 = (global-value free_ptr);
  12610. tmp3 = (+ tmp2 16);
  12611. tmp4 = (global-value fromspace_end);
  12612. if (< tmp3 tmp4)
  12613. goto block7;
  12614. else
  12615. goto block8;
  12616. block7:
  12617. _8 = (void);
  12618. goto block6;
  12619. block8:
  12620. (collect 16)
  12621. goto block6;
  12622. block6:
  12623. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12624. _7 = (vector-set! alloc5 0 vecinit6);
  12625. tmp5 = (vector-ref alloc5 0);
  12626. return (vector-ref tmp5 0);
  12627. \end{lstlisting}
  12628. \end{minipage}
  12629. &$\Rightarrow$&
  12630. \begin{minipage}{0.4\textwidth}
  12631. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12632. start:
  12633. movq free_ptr(%rip), tmp9
  12634. movq tmp9, tmp0
  12635. addq $16, tmp0
  12636. movq fromspace_end(%rip), tmp1
  12637. cmpq tmp1, tmp0
  12638. jl block0
  12639. jmp block1
  12640. block0:
  12641. movq $0, _4
  12642. jmp block9
  12643. block1:
  12644. movq %r15, %rdi
  12645. movq $16, %rsi
  12646. callq collect
  12647. jmp block9
  12648. block9:
  12649. movq free_ptr(%rip), %r11
  12650. addq $16, free_ptr(%rip)
  12651. movq $3, 0(%r11)
  12652. movq %r11, alloc2
  12653. movq alloc2, %r11
  12654. movq $42, 8(%r11)
  12655. movq $0, _3
  12656. movq alloc2, vecinit6
  12657. movq free_ptr(%rip), tmp2
  12658. movq tmp2, tmp3
  12659. addq $16, tmp3
  12660. movq fromspace_end(%rip), tmp4
  12661. cmpq tmp4, tmp3
  12662. jl block7
  12663. jmp block8
  12664. block7:
  12665. movq $0, _8
  12666. jmp block6
  12667. block8:
  12668. movq %r15, %rdi
  12669. movq $16, %rsi
  12670. callq collect
  12671. jmp block6
  12672. block6:
  12673. movq free_ptr(%rip), %r11
  12674. addq $16, free_ptr(%rip)
  12675. movq $131, 0(%r11)
  12676. movq %r11, alloc5
  12677. movq alloc5, %r11
  12678. movq vecinit6, 8(%r11)
  12679. movq $0, _7
  12680. movq alloc5, %r11
  12681. movq 8(%r11), tmp5
  12682. movq tmp5, %r11
  12683. movq 8(%r11), %rax
  12684. jmp conclusion
  12685. \end{lstlisting}
  12686. \end{minipage}
  12687. \end{tabular}
  12688. \fi}
  12689. {\if\edition\pythonEd
  12690. % tests/tuple/get_get.py
  12691. \begin{tabular}{lll}
  12692. \begin{minipage}{0.5\textwidth}
  12693. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12694. start:
  12695. init.514 = 42
  12696. tmp.517 = free_ptr
  12697. tmp.518 = (tmp.517 + 16)
  12698. tmp.519 = fromspace_end
  12699. if tmp.518 < tmp.519:
  12700. goto block.529
  12701. else:
  12702. goto block.530
  12703. block.529:
  12704. goto block.528
  12705. block.530:
  12706. collect(16)
  12707. goto block.528
  12708. block.528:
  12709. alloc.513 = allocate(1,tuple[int])
  12710. alloc.513:tuple[int][0] = init.514
  12711. v1 = alloc.513
  12712. init.516 = v1
  12713. tmp.520 = free_ptr
  12714. tmp.521 = (tmp.520 + 16)
  12715. tmp.522 = fromspace_end
  12716. if tmp.521 < tmp.522:
  12717. goto block.526
  12718. else:
  12719. goto block.527
  12720. block.526:
  12721. goto block.525
  12722. block.527:
  12723. collect(16)
  12724. goto block.525
  12725. block.525:
  12726. alloc.515 = allocate(1,tuple[tuple[int]])
  12727. alloc.515:tuple[tuple[int]][0] = init.516
  12728. v2 = alloc.515
  12729. tmp.523 = v2[0]
  12730. tmp.524 = tmp.523[0]
  12731. print(tmp.524)
  12732. return 0
  12733. \end{lstlisting}
  12734. \end{minipage}
  12735. &$\Rightarrow$&
  12736. \begin{minipage}{0.4\textwidth}
  12737. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12738. start:
  12739. movq $42, init.514
  12740. movq free_ptr(%rip), tmp.517
  12741. movq tmp.517, tmp.518
  12742. addq $16, tmp.518
  12743. movq fromspace_end(%rip), tmp.519
  12744. cmpq tmp.519, tmp.518
  12745. jl block.529
  12746. jmp block.530
  12747. block.529:
  12748. jmp block.528
  12749. block.530:
  12750. movq %r15, %rdi
  12751. movq $16, %rsi
  12752. callq collect
  12753. jmp block.528
  12754. block.528:
  12755. movq free_ptr(%rip), %r11
  12756. addq $16, free_ptr(%rip)
  12757. movq $3, 0(%r11)
  12758. movq %r11, alloc.513
  12759. movq alloc.513, %r11
  12760. movq init.514, 8(%r11)
  12761. movq alloc.513, v1
  12762. movq v1, init.516
  12763. movq free_ptr(%rip), tmp.520
  12764. movq tmp.520, tmp.521
  12765. addq $16, tmp.521
  12766. movq fromspace_end(%rip), tmp.522
  12767. cmpq tmp.522, tmp.521
  12768. jl block.526
  12769. jmp block.527
  12770. block.526:
  12771. jmp block.525
  12772. block.527:
  12773. movq %r15, %rdi
  12774. movq $16, %rsi
  12775. callq collect
  12776. jmp block.525
  12777. block.525:
  12778. movq free_ptr(%rip), %r11
  12779. addq $16, free_ptr(%rip)
  12780. movq $131, 0(%r11)
  12781. movq %r11, alloc.515
  12782. movq alloc.515, %r11
  12783. movq init.516, 8(%r11)
  12784. movq alloc.515, v2
  12785. movq v2, %r11
  12786. movq 8(%r11), %r11
  12787. movq %r11, tmp.523
  12788. movq tmp.523, %r11
  12789. movq 8(%r11), %r11
  12790. movq %r11, tmp.524
  12791. movq tmp.524, %rdi
  12792. callq print_int
  12793. movq $0, %rax
  12794. jmp conclusion
  12795. \end{lstlisting}
  12796. \end{minipage}
  12797. \end{tabular}
  12798. \fi}
  12799. \end{tcolorbox}
  12800. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12801. \code{select\_instructions} (\emph{right}) on the running example.}
  12802. \label{fig:select-instr-output-gc}
  12803. \end{figure}
  12804. \clearpage
  12805. \section{Register Allocation}
  12806. \label{sec:reg-alloc-gc}
  12807. \index{subject}{register allocation}
  12808. As discussed previously in this chapter, the garbage collector needs to
  12809. access all the pointers in the root set, that is, all variables that
  12810. are tuples. It will be the responsibility of the register allocator
  12811. to make sure that
  12812. \begin{enumerate}
  12813. \item the root stack is used for spilling tuple-typed variables, and
  12814. \item if a tuple-typed variable is live during a call to the
  12815. collector, it must be spilled to ensure that it is visible to the
  12816. collector.
  12817. \end{enumerate}
  12818. The latter responsibility can be handled during construction of the
  12819. interference graph, by adding interference edges between the call-live
  12820. tuple-typed variables and all the callee-saved registers. (They
  12821. already interfere with the caller-saved registers.)
  12822. %
  12823. \racket{The type information for variables is in the \code{Program}
  12824. form, so we recommend adding another parameter to the
  12825. \code{build\_interference} function to communicate this alist.}
  12826. %
  12827. \python{The type information for variables is generated by the type
  12828. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12829. the \code{CProgram} AST mode. You'll need to propagate that
  12830. information so that it is available in this pass.}
  12831. The spilling of tuple-typed variables to the root stack can be handled
  12832. after graph coloring, in choosing how to assign the colors
  12833. (integers) to registers and stack locations. The
  12834. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12835. changes to also record the number of spills to the root stack.
  12836. % build-interference
  12837. %
  12838. % callq
  12839. % extra parameter for var->type assoc. list
  12840. % update 'program' and 'if'
  12841. % allocate-registers
  12842. % allocate spilled vectors to the rootstack
  12843. % don't change color-graph
  12844. % TODO:
  12845. %\section{Patch Instructions}
  12846. %[mention that global variables are memory references]
  12847. \section{Generate Prelude and Conclusion}
  12848. \label{sec:print-x86-gc}
  12849. \label{sec:prelude-conclusion-x86-gc}
  12850. \index{subject}{prelude}\index{subject}{conclusion}
  12851. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12852. \code{prelude\_and\_conclusion} pass on the running example. In the
  12853. prelude of the \code{main} function, we allocate space
  12854. on the root stack to make room for the spills of tuple-typed
  12855. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12856. taking care that the root stack grows up instead of down. For the
  12857. running example, there was just one spill, so we increment \code{r15}
  12858. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12859. One issue that deserves special care is that there may be a call to
  12860. \code{collect} prior to the initializing assignments for all the
  12861. variables in the root stack. We do not want the garbage collector to
  12862. mistakenly determine that some uninitialized variable is a pointer that
  12863. needs to be followed. Thus, we zero out all locations on the root
  12864. stack in the prelude of \code{main}. In
  12865. figure~\ref{fig:print-x86-output-gc}, the instruction
  12866. %
  12867. \lstinline{movq $0, 0(%r15)}
  12868. %
  12869. is sufficient to accomplish this task because there is only one spill.
  12870. In general, we have to clear as many words as there are spills of
  12871. tuple-typed variables. The garbage collector tests each root to see
  12872. if it is null prior to dereferencing it.
  12873. \begin{figure}[htbp]
  12874. \begin{tcolorbox}[colback=white]
  12875. {\if\edition\racketEd
  12876. \begin{minipage}[t]{0.5\textwidth}
  12877. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12878. .globl main
  12879. main:
  12880. pushq %rbp
  12881. movq %rsp, %rbp
  12882. subq $0, %rsp
  12883. movq $65536, %rdi
  12884. movq $65536, %rsi
  12885. callq initialize
  12886. movq rootstack_begin(%rip), %r15
  12887. movq $0, 0(%r15)
  12888. addq $8, %r15
  12889. jmp start
  12890. conclusion:
  12891. subq $8, %r15
  12892. addq $0, %rsp
  12893. popq %rbp
  12894. retq
  12895. \end{lstlisting}
  12896. \end{minipage}
  12897. \fi}
  12898. {\if\edition\pythonEd
  12899. \begin{minipage}[t]{0.5\textwidth}
  12900. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12901. .globl main
  12902. main:
  12903. pushq %rbp
  12904. movq %rsp, %rbp
  12905. pushq %rbx
  12906. subq $8, %rsp
  12907. movq $65536, %rdi
  12908. movq $16, %rsi
  12909. callq initialize
  12910. movq rootstack_begin(%rip), %r15
  12911. movq $0, 0(%r15)
  12912. addq $8, %r15
  12913. jmp start
  12914. conclusion:
  12915. subq $8, %r15
  12916. addq $8, %rsp
  12917. popq %rbx
  12918. popq %rbp
  12919. retq
  12920. \end{lstlisting}
  12921. \end{minipage}
  12922. \fi}
  12923. \end{tcolorbox}
  12924. \caption{The prelude and conclusion for the running example.}
  12925. \label{fig:print-x86-output-gc}
  12926. \end{figure}
  12927. \begin{figure}[tbp]
  12928. \begin{tcolorbox}[colback=white]
  12929. {\if\edition\racketEd
  12930. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12931. \node (Lvec) at (0,2) {\large \LangVec{}};
  12932. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12933. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12934. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12935. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12936. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12937. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12938. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12939. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12940. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12941. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12942. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12943. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12944. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12945. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12946. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12947. \path[->,bend left=15] (Lvec-4) edge [right] node
  12948. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12949. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12950. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12951. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12952. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12953. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12954. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12955. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12956. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12957. \end{tikzpicture}
  12958. \fi}
  12959. {\if\edition\pythonEd\pythonColor
  12960. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12961. \node (Lvec) at (0,2) {\large \LangVec{}};
  12962. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12963. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12964. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12965. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12966. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12967. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12968. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12969. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12970. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12971. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12972. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12973. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12974. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12975. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12976. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12977. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12978. \end{tikzpicture}
  12979. \fi}
  12980. \end{tcolorbox}
  12981. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12982. \label{fig:Lvec-passes}
  12983. \end{figure}
  12984. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12985. for the compilation of \LangVec{}.
  12986. \clearpage
  12987. {\if\edition\racketEd
  12988. \section{Challenge: Simple Structures}
  12989. \label{sec:simple-structures}
  12990. \index{subject}{struct}
  12991. \index{subject}{structure}
  12992. The language \LangStruct{} extends \LangVec{} with support for simple
  12993. structures. The definition of its concrete syntax is shown in
  12994. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12995. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12996. in Typed Racket is a user-defined data type that contains named fields
  12997. and that is heap allocated\index{subject}{heap allocated},
  12998. similarly to a vector. The following is an
  12999. example of a structure definition, in this case the definition of a
  13000. \code{point} type:
  13001. \begin{lstlisting}
  13002. (struct point ([x : Integer] [y : Integer]) #:mutable)
  13003. \end{lstlisting}
  13004. \newcommand{\LstructGrammarRacket}{
  13005. \begin{array}{lcl}
  13006. \Type &::=& \Var \\
  13007. \Exp &::=& (\Var\;\Exp \ldots)\\
  13008. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  13009. \end{array}
  13010. }
  13011. \newcommand{\LstructASTRacket}{
  13012. \begin{array}{lcl}
  13013. \Type &::=& \VAR{\Var} \\
  13014. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  13015. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  13016. \end{array}
  13017. }
  13018. \begin{figure}[tbp]
  13019. \centering
  13020. \begin{tcolorbox}[colback=white]
  13021. \[
  13022. \begin{array}{l}
  13023. \gray{\LintGrammarRacket{}} \\ \hline
  13024. \gray{\LvarGrammarRacket{}} \\ \hline
  13025. \gray{\LifGrammarRacket{}} \\ \hline
  13026. \gray{\LwhileGrammarRacket} \\ \hline
  13027. \gray{\LtupGrammarRacket} \\ \hline
  13028. \LstructGrammarRacket \\
  13029. \begin{array}{lcl}
  13030. \LangStruct{} &::=& \Def \ldots \; \Exp
  13031. \end{array}
  13032. \end{array}
  13033. \]
  13034. \end{tcolorbox}
  13035. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  13036. (figure~\ref{fig:Lvec-concrete-syntax}).}
  13037. \label{fig:Lstruct-concrete-syntax}
  13038. \index{subject}{Lstruct@\LangStruct{} concrete syntax}
  13039. \end{figure}
  13040. \begin{figure}[tbp]
  13041. \centering
  13042. \begin{tcolorbox}[colback=white]
  13043. \small
  13044. \[
  13045. \begin{array}{l}
  13046. \gray{\LintASTRacket{}} \\ \hline
  13047. \gray{\LvarASTRacket{}} \\ \hline
  13048. \gray{\LifASTRacket{}} \\ \hline
  13049. \gray{\LwhileASTRacket} \\ \hline
  13050. \gray{\LtupASTRacket} \\ \hline
  13051. \LstructASTRacket \\
  13052. \begin{array}{lcl}
  13053. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13054. \end{array}
  13055. \end{array}
  13056. \]
  13057. \end{tcolorbox}
  13058. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  13059. (figure~\ref{fig:Lvec-syntax}).}
  13060. \label{fig:Lstruct-syntax}
  13061. \index{subject}{Lstruct@\LangStruct{} abstract syntax}
  13062. \end{figure}
  13063. An instance of a structure is created using function-call syntax, with
  13064. the name of the structure in the function position, as follows:
  13065. \begin{lstlisting}
  13066. (point 7 12)
  13067. \end{lstlisting}
  13068. Function-call syntax is also used to read a field of a structure. The
  13069. function name is formed by the structure name, a dash, and the field
  13070. name. The following example uses \code{point-x} and \code{point-y} to
  13071. access the \code{x} and \code{y} fields of two point instances:
  13072. \begin{center}
  13073. \begin{lstlisting}
  13074. (let ([pt1 (point 7 12)])
  13075. (let ([pt2 (point 4 3)])
  13076. (+ (- (point-x pt1) (point-x pt2))
  13077. (- (point-y pt1) (point-y pt2)))))
  13078. \end{lstlisting}
  13079. \end{center}
  13080. Similarly, to write to a field of a structure, use its set function,
  13081. whose name starts with \code{set-}, followed by the structure name,
  13082. then a dash, then the field name, and finally with an exclamation
  13083. mark. The following example uses \code{set-point-x!} to change the
  13084. \code{x} field from \code{7} to \code{42}:
  13085. \begin{center}
  13086. \begin{lstlisting}
  13087. (let ([pt (point 7 12)])
  13088. (let ([_ (set-point-x! pt 42)])
  13089. (point-x pt)))
  13090. \end{lstlisting}
  13091. \end{center}
  13092. \begin{exercise}\normalfont\normalsize
  13093. Create a type checker for \LangStruct{} by extending the type
  13094. checker for \LangVec{}. Extend your compiler with support for simple
  13095. structures, compiling \LangStruct{} to x86 assembly code. Create
  13096. five new test cases that use structures, and test your compiler.
  13097. \end{exercise}
  13098. % TODO: create an interpreter for L_struct
  13099. \clearpage
  13100. \fi}
  13101. \section{Challenge: Arrays}
  13102. \label{sec:arrays}
  13103. % TODO mention trapped-error
  13104. In this chapter we have studied tuples, that is, heterogeneous
  13105. sequences of elements whose length is determined at compile time. This
  13106. challenge is also about sequences, but this time the length is
  13107. determined at runtime and all the elements have the same type (they
  13108. are homogeneous). We use the traditional term \emph{array} for this
  13109. latter kind of sequence.
  13110. %
  13111. \racket{
  13112. The Racket language does not distinguish between tuples and arrays;
  13113. they are both represented by vectors. However, Typed Racket
  13114. distinguishes between tuples and arrays: the \code{Vector} type is for
  13115. tuples, and the \code{Vectorof} type is for arrays.}%
  13116. \python{Arrays correspond to the \code{list} type in the Python language.}
  13117. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13118. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13119. presents the definition of the abstract syntax, extending \LangVec{}
  13120. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13121. \racket{\code{make-vector} primitive operator for creating an array,
  13122. whose arguments are the length of the array and an initial value for
  13123. all the elements in the array.}%
  13124. \python{bracket notation for creating an array literal.}
  13125. \racket{The \code{vector-length},
  13126. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13127. for tuples become overloaded for use with arrays.}
  13128. \python{
  13129. The subscript operator becomes overloaded for use with arrays and tuples
  13130. and now may appear on the left-hand side of an assignment.
  13131. Note that the index of the subscript, when applied to an array, may be an
  13132. arbitrary expression and not exclusively a constant integer.
  13133. The \code{len} function is also applicable to arrays.
  13134. }
  13135. %
  13136. We include integer multiplication in \LangArray{} because it is
  13137. useful in many examples involving arrays such as computing the
  13138. inner product of two arrays (figure~\ref{fig:inner_product}).
  13139. \newcommand{\LarrayGrammarRacket}{
  13140. \begin{array}{lcl}
  13141. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13142. \Exp &::=& \CMUL{\Exp}{\Exp}
  13143. \MID \CMAKEVEC{\Exp}{\Exp}
  13144. \end{array}
  13145. }
  13146. \newcommand{\LarrayASTRacket}{
  13147. \begin{array}{lcl}
  13148. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13149. \Exp &::=& \MUL{\Exp}{\Exp}
  13150. \MID \MAKEVEC{\Exp}{\Exp}
  13151. \end{array}
  13152. }
  13153. \newcommand{\LarrayGrammarPython}{
  13154. \begin{array}{lcl}
  13155. \Type &::=& \key{list}\LS\Type\RS \\
  13156. \Exp &::=& \CMUL{\Exp}{\Exp}
  13157. \MID \CGET{\Exp}{\Exp}
  13158. \MID \LS \Exp \code{,} \ldots \RS \\
  13159. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13160. \end{array}
  13161. }
  13162. \newcommand{\LarrayASTPython}{
  13163. \begin{array}{lcl}
  13164. \Type &::=& \key{ListType}\LP\Type\RP \\
  13165. \Exp &::=& \MUL{\Exp}{\Exp}
  13166. \MID \GET{\Exp}{\Exp} \\
  13167. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13168. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13169. \end{array}
  13170. }
  13171. \begin{figure}[tp]
  13172. \centering
  13173. \begin{tcolorbox}[colback=white]
  13174. \small
  13175. {\if\edition\racketEd
  13176. \[
  13177. \begin{array}{l}
  13178. \gray{\LintGrammarRacket{}} \\ \hline
  13179. \gray{\LvarGrammarRacket{}} \\ \hline
  13180. \gray{\LifGrammarRacket{}} \\ \hline
  13181. \gray{\LwhileGrammarRacket} \\ \hline
  13182. \gray{\LtupGrammarRacket} \\ \hline
  13183. \LarrayGrammarRacket \\
  13184. \begin{array}{lcl}
  13185. \LangArray{} &::=& \Exp
  13186. \end{array}
  13187. \end{array}
  13188. \]
  13189. \fi}
  13190. {\if\edition\pythonEd\pythonColor
  13191. \[
  13192. \begin{array}{l}
  13193. \gray{\LintGrammarPython{}} \\ \hline
  13194. \gray{\LvarGrammarPython{}} \\ \hline
  13195. \gray{\LifGrammarPython{}} \\ \hline
  13196. \gray{\LwhileGrammarPython} \\ \hline
  13197. \gray{\LtupGrammarPython} \\ \hline
  13198. \LarrayGrammarPython \\
  13199. \begin{array}{rcl}
  13200. \LangArrayM{} &::=& \Stmt^{*}
  13201. \end{array}
  13202. \end{array}
  13203. \]
  13204. \fi}
  13205. \end{tcolorbox}
  13206. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13207. \label{fig:Lvecof-concrete-syntax}
  13208. \index{subject}{Larray@\LangArray{} concrete syntax}
  13209. \end{figure}
  13210. \begin{figure}[tp]
  13211. \centering
  13212. \begin{tcolorbox}[colback=white]
  13213. \small
  13214. {\if\edition\racketEd
  13215. \[
  13216. \begin{array}{l}
  13217. \gray{\LintASTRacket{}} \\ \hline
  13218. \gray{\LvarASTRacket{}} \\ \hline
  13219. \gray{\LifASTRacket{}} \\ \hline
  13220. \gray{\LwhileASTRacket} \\ \hline
  13221. \gray{\LtupASTRacket} \\ \hline
  13222. \LarrayASTRacket \\
  13223. \begin{array}{lcl}
  13224. \LangArray{} &::=& \Exp
  13225. \end{array}
  13226. \end{array}
  13227. \]
  13228. \fi}
  13229. {\if\edition\pythonEd\pythonColor
  13230. \[
  13231. \begin{array}{l}
  13232. \gray{\LintASTPython{}} \\ \hline
  13233. \gray{\LvarASTPython{}} \\ \hline
  13234. \gray{\LifASTPython{}} \\ \hline
  13235. \gray{\LwhileASTPython} \\ \hline
  13236. \gray{\LtupASTPython} \\ \hline
  13237. \LarrayASTPython \\
  13238. \begin{array}{rcl}
  13239. \LangArrayM{} &::=& \Stmt^{*}
  13240. \end{array}
  13241. \end{array}
  13242. \]
  13243. \fi}
  13244. \end{tcolorbox}
  13245. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13246. \label{fig:Lvecof-syntax}
  13247. \index{subject}{Larray@\LangArray{} abstract syntax}
  13248. \end{figure}
  13249. \begin{figure}[tp]
  13250. \begin{tcolorbox}[colback=white]
  13251. {\if\edition\racketEd
  13252. \begin{lstlisting}
  13253. (let ([A (make-vector 2 2)])
  13254. (let ([B (make-vector 2 3)])
  13255. (let ([i 0])
  13256. (let ([prod 0])
  13257. (begin
  13258. (while (< i (vector-length A))
  13259. (begin
  13260. (set! prod (+ prod (* (vector-ref A i)
  13261. (vector-ref B i))))
  13262. (set! i (+ i 1))))
  13263. prod)))))
  13264. \end{lstlisting}
  13265. \fi}
  13266. {\if\edition\pythonEd\pythonColor
  13267. \begin{lstlisting}
  13268. A = [2, 2]
  13269. B = [3, 3]
  13270. i = 0
  13271. prod = 0
  13272. while i != len(A):
  13273. prod = prod + A[i] * B[i]
  13274. i = i + 1
  13275. print(prod)
  13276. \end{lstlisting}
  13277. \fi}
  13278. \end{tcolorbox}
  13279. \caption{Example program that computes the inner product.}
  13280. \label{fig:inner_product}
  13281. \end{figure}
  13282. {\if\edition\racketEd
  13283. %
  13284. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13285. checker for \LangArray{}. The result type of
  13286. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13287. of the initializing expression. The length expression is required to
  13288. have type \code{Integer}. The type checking of the operators
  13289. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13290. updated to handle the situation in which the vector has type
  13291. \code{Vectorof}. In these cases we translate the operators to their
  13292. \code{vectorof} form so that later passes can easily distinguish
  13293. between operations on tuples versus arrays. We override the
  13294. \code{operator-types} method to provide the type signature for
  13295. multiplication: it takes two integers and returns an integer.
  13296. \fi}
  13297. %
  13298. {\if\edition\pythonEd\pythonColor
  13299. %
  13300. The type checker for \LangArray{} is defined in
  13301. figures~\ref{fig:type-check-Lvecof} and
  13302. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13303. is \code{list[T]}, where \code{T} is the type of the initializing
  13304. expressions. The type checking of the \code{len} function and the
  13305. subscript operator are updated to handle lists. The type checker now
  13306. also handles a subscript on the left-hand side of an assignment.
  13307. Regarding multiplication, it takes two integers and returns an
  13308. integer.
  13309. %
  13310. \fi}
  13311. \begin{figure}[tbp]
  13312. \begin{tcolorbox}[colback=white]
  13313. {\if\edition\racketEd
  13314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13315. (define type-check-Lvecof-class
  13316. (class type-check-Lvec-class
  13317. (super-new)
  13318. (inherit check-type-equal?)
  13319. (define/override (operator-types)
  13320. (append '((* . ((Integer Integer) . Integer)))
  13321. (super operator-types)))
  13322. (define/override (type-check-exp env)
  13323. (lambda (e)
  13324. (define recur (type-check-exp env))
  13325. (match e
  13326. [(Prim 'make-vector (list e1 e2))
  13327. (define-values (e1^ t1) (recur e1))
  13328. (define-values (e2^ elt-type) (recur e2))
  13329. (define vec-type `(Vectorof ,elt-type))
  13330. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13331. [(Prim 'vector-ref (list e1 e2))
  13332. (define-values (e1^ t1) (recur e1))
  13333. (define-values (e2^ t2) (recur e2))
  13334. (match* (t1 t2)
  13335. [(`(Vectorof ,elt-type) 'Integer)
  13336. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13337. [(other wise) ((super type-check-exp env) e)])]
  13338. [(Prim 'vector-set! (list e1 e2 e3) )
  13339. (define-values (e-vec t-vec) (recur e1))
  13340. (define-values (e2^ t2) (recur e2))
  13341. (define-values (e-arg^ t-arg) (recur e3))
  13342. (match t-vec
  13343. [`(Vectorof ,elt-type)
  13344. (check-type-equal? elt-type t-arg e)
  13345. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13346. [else ((super type-check-exp env) e)])]
  13347. [(Prim 'vector-length (list e1))
  13348. (define-values (e1^ t1) (recur e1))
  13349. (match t1
  13350. [`(Vectorof ,t)
  13351. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13352. [else ((super type-check-exp env) e)])]
  13353. [else ((super type-check-exp env) e)])))
  13354. ))
  13355. (define (type-check-Lvecof p)
  13356. (send (new type-check-Lvecof-class) type-check-program p))
  13357. \end{lstlisting}
  13358. \fi}
  13359. {\if\edition\pythonEd\pythonColor
  13360. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13361. class TypeCheckLarray(TypeCheckLtup):
  13362. def type_check_exp(self, e, env):
  13363. match e:
  13364. case ast.List(es, Load()):
  13365. ts = [self.type_check_exp(e, env) for e in es]
  13366. elt_ty = ts[0]
  13367. for (ty, elt) in zip(ts, es):
  13368. self.check_type_equal(elt_ty, ty, elt)
  13369. e.has_type = ListType(elt_ty)
  13370. return e.has_type
  13371. case Call(Name('len'), [tup]):
  13372. tup_t = self.type_check_exp(tup, env)
  13373. tup.has_type = tup_t
  13374. match tup_t:
  13375. case TupleType(ts):
  13376. return IntType()
  13377. case ListType(ty):
  13378. return IntType()
  13379. case _:
  13380. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13381. case Subscript(tup, index, Load()):
  13382. tup_ty = self.type_check_exp(tup, env)
  13383. tup.has_type = tup_ty
  13384. index_ty = self.type_check_exp(index, env)
  13385. self.check_type_equal(index_ty, IntType(), index)
  13386. match tup_ty:
  13387. case TupleType(ts):
  13388. match index:
  13389. case Constant(i):
  13390. return ts[i]
  13391. case _:
  13392. raise Exception('subscript required constant integer index')
  13393. case ListType(ty):
  13394. return ty
  13395. case _:
  13396. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13397. case BinOp(left, Mult(), right):
  13398. l = self.type_check_exp(left, env)
  13399. self.check_type_equal(l, IntType(), left)
  13400. r = self.type_check_exp(right, env)
  13401. self.check_type_equal(r, IntType(), right)
  13402. return IntType()
  13403. case _:
  13404. return super().type_check_exp(e, env)
  13405. \end{lstlisting}
  13406. \fi}
  13407. \end{tcolorbox}
  13408. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13409. \label{fig:type-check-Lvecof}
  13410. \end{figure}
  13411. {\if\edition\pythonEd
  13412. \begin{figure}[tbp]
  13413. \begin{tcolorbox}[colback=white]
  13414. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13415. def type_check_stmts(self, ss, env):
  13416. if len(ss) == 0:
  13417. return VoidType()
  13418. match ss[0]:
  13419. case Assign([Subscript(tup, index, Store())], value):
  13420. tup_t = self.type_check_exp(tup, env)
  13421. tup.has_type = tup_t
  13422. value_t = self.type_check_exp(value, env)
  13423. index_ty = self.type_check_exp(index, env)
  13424. self.check_type_equal(index_ty, IntType(), index)
  13425. match tup_t:
  13426. case ListType(ty):
  13427. self.check_type_equal(ty, value_t, ss[0])
  13428. case TupleType(ts):
  13429. return self.type_check_stmts(ss, env)
  13430. case _:
  13431. raise Exception('type_check_stmts: '
  13432. 'expected tuple or list, not ' + repr(tup_t))
  13433. return self.type_check_stmts(ss[1:], env)
  13434. case _:
  13435. return super().type_check_stmts(ss, env)
  13436. \end{lstlisting}
  13437. \end{tcolorbox}
  13438. \caption{Type checker for the \LangArray{} language, part 2.}
  13439. \label{fig:type-check-Lvecof-part2}
  13440. \end{figure}
  13441. \fi}
  13442. The definition of the interpreter for \LangArray{} is shown in
  13443. \racket{figure~\ref{fig:interp-Lvecof}}
  13444. \python{figure~\ref{fig:interp-Lvecof}}.
  13445. \racket{The \code{make-vector} operator is
  13446. interpreted using Racket's \code{make-vector} function,
  13447. and multiplication is interpreted using \code{fx*},
  13448. which is multiplication for \code{fixnum} integers.
  13449. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13450. we translate array access operations
  13451. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13452. which we interpret using \code{vector} operations with additional
  13453. bounds checks that signal a \code{trapped-error}.
  13454. }
  13455. %
  13456. \python{We implement array creation with a Python list comprehension,
  13457. and multiplication is implemented with 64-bit multiplication. We
  13458. add a case for a subscript on the left-hand side of
  13459. assignment. Other uses of subscript can be handled by the existing
  13460. code for tuples.}
  13461. \begin{figure}[tbp]
  13462. \begin{tcolorbox}[colback=white]
  13463. {\if\edition\racketEd
  13464. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13465. (define interp-Lvecof-class
  13466. (class interp-Lvec-class
  13467. (super-new)
  13468. (define/override (interp-op op)
  13469. (match op
  13470. ['make-vector make-vector]
  13471. ['vectorof-length vector-length]
  13472. ['vectorof-ref
  13473. (lambda (v i)
  13474. (if (< i (vector-length v))
  13475. (vector-ref v i)
  13476. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13477. ['vectorof-set!
  13478. (lambda (v i e)
  13479. (if (< i (vector-length v))
  13480. (vector-set! v i e)
  13481. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13482. [else (super interp-op op)]))
  13483. ))
  13484. (define (interp-Lvecof p)
  13485. (send (new interp-Lvecof-class) interp-program p))
  13486. \end{lstlisting}
  13487. \fi}
  13488. {\if\edition\pythonEd\pythonColor
  13489. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13490. class InterpLarray(InterpLtup):
  13491. def interp_exp(self, e, env):
  13492. match e:
  13493. case ast.List(es, Load()):
  13494. return [self.interp_exp(e, env) for e in es]
  13495. case BinOp(left, Mult(), right):
  13496. l = self.interp_exp(left, env)
  13497. r = self.interp_exp(right, env)
  13498. return mul64(l, r)
  13499. case Subscript(tup, index, Load()):
  13500. t = self.interp_exp(tup, env)
  13501. n = self.interp_exp(index, env)
  13502. if n < len(t):
  13503. return t[n]
  13504. else:
  13505. raise TrappedError('array index out of bounds')
  13506. case _:
  13507. return super().interp_exp(e, env)
  13508. def interp_stmt(self, s, env, cont):
  13509. match s:
  13510. case Assign([Subscript(tup, index)], value):
  13511. t = self.interp_exp(tup, env)
  13512. n = self.interp_exp(index, env)
  13513. if n < len(t):
  13514. t[n] = self.interp_exp(value, env)
  13515. else:
  13516. raise TrappedError('array index out of bounds')
  13517. return self.interp_stmts(cont, env)
  13518. case _:
  13519. return super().interp_stmt(s, env, cont)
  13520. \end{lstlisting}
  13521. \fi}
  13522. \end{tcolorbox}
  13523. \caption{Interpreter for \LangArray{}.}
  13524. \label{fig:interp-Lvecof}
  13525. \end{figure}
  13526. \subsection{Data Representation}
  13527. \label{sec:array-rep}
  13528. Just as with tuples, we store arrays on the heap, which means that the
  13529. garbage collector will need to inspect arrays. An immediate thought is
  13530. to use the same representation for arrays that we use for tuples.
  13531. However, we limit tuples to a length of fifty so that their length and
  13532. pointer mask can fit into the 64-bit tag at the beginning of each
  13533. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13534. millions of elements, so we need more bits to store the length.
  13535. However, because arrays are homogeneous, we need only 1 bit for the
  13536. pointer mask instead of 1 bit per array element. Finally, the
  13537. garbage collector must be able to distinguish between tuples
  13538. and arrays, so we need to reserve one bit for that purpose. We
  13539. arrive at the following layout for the 64-bit tag at the beginning of
  13540. an array:
  13541. \begin{itemize}
  13542. \item The right-most bit is the forwarding bit, just as in a tuple.
  13543. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13544. that it is not.
  13545. \item The next bit to the left is the pointer mask. A $0$ indicates
  13546. that none of the elements are pointers, and a $1$ indicates that all
  13547. the elements are pointers.
  13548. \item The next $60$ bits store the length of the array.
  13549. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13550. and an array ($1$).
  13551. \item The left-most bit is reserved as explained in
  13552. chapter~\ref{ch:Lgrad}.
  13553. \end{itemize}
  13554. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13555. %% differentiate the kinds of values that have been injected into the
  13556. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13557. %% to indicate that the value is an array.
  13558. In the following subsections we provide hints regarding how to update
  13559. the passes to handle arrays.
  13560. \subsection{Overload Resolution}
  13561. \label{sec:array-resolution}
  13562. As noted previously, with the addition of arrays, several operators
  13563. have become \emph{overloaded}; that is, they can be applied to values
  13564. of more than one type. In this case, the element access and length
  13565. operators can be applied to both tuples and arrays. This kind of
  13566. overloading is quite common in programming languages, so many
  13567. compilers perform \emph{overload resolution}\index{subject}{overload
  13568. resolution} to handle it. The idea is to translate each overloaded
  13569. operator into different operators for the different types.
  13570. Implement a new pass named \code{resolve}.
  13571. Translate the reading of an array element to
  13572. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13573. and the writing of an array element to
  13574. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13575. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13576. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13577. When these operators are applied to tuples, leave them as is.
  13578. %
  13579. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13580. field, which can be inspected to determine whether the operator
  13581. is applied to a tuple or an array.}
  13582. \subsection{Bounds Checking}
  13583. Recall that the interpreter for \LangArray{} signals a
  13584. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13585. when there is an array access that is out of
  13586. bounds. Therefore your compiler is obliged to also catch these errors
  13587. during execution and halt, signaling an error. We recommend inserting
  13588. a new pass named \code{check\_bounds} that inserts code around each
  13589. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13590. \python{subscript} operation to ensure that the index is greater than
  13591. or equal to zero and less than the array's length. If not, the program
  13592. should halt, for which we recommend using a new primitive operation
  13593. named \code{exit}.
  13594. %% \subsection{Reveal Casts}
  13595. %% The array-access operators \code{vectorof-ref} and
  13596. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13597. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13598. %% that the type checker cannot tell whether the index will be in bounds,
  13599. %% so the bounds check must be performed at run time. Recall that the
  13600. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13601. %% an \code{If} around a vector reference for update to check whether
  13602. %% the index is less than the length. You should do the same for
  13603. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13604. %% In addition, the handling of the \code{any-vector} operators in
  13605. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13606. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13607. %% generated code should test whether the tag is for tuples (\code{010})
  13608. %% or arrays (\code{110}) and then dispatch to either
  13609. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13610. %% we add a case in \code{select\_instructions} to generate the
  13611. %% appropriate instructions for accessing the array length from the
  13612. %% header of an array.
  13613. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13614. %% the generated code needs to check that the index is less than the
  13615. %% vector length, so like the code for \code{any-vector-length}, check
  13616. %% the tag to determine whether to use \code{any-vector-length} or
  13617. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13618. %% is complete, the generated code can use \code{any-vector-ref} and
  13619. %% \code{any-vector-set!} for both tuples and arrays because the
  13620. %% instructions used for those operators do not look at the tag at the
  13621. %% front of the tuple or array.
  13622. \subsection{Expose Allocation}
  13623. % TODO: add figure for C_array
  13624. This pass should translate array creation into lower-level
  13625. operations. In particular, the new AST node \ALLOCARRAY{\Int}{\Type}
  13626. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13627. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13628. array. The \code{AllocateArray} AST node allocates an array of the
  13629. length specified by the $\Exp$ (of type \INTTY), but does not
  13630. initialize the elements of the array. Generate code in this pass to
  13631. initialize the elements analogous to the case for tuples.
  13632. {\if\edition\racketEd
  13633. \subsection{Uncover \texttt{get!}}
  13634. \label{sec:uncover-get-bang-vecof}
  13635. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13636. \code{uncover-get!-exp}.
  13637. \fi}
  13638. \subsection{Remove Complex Operands}
  13639. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13640. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13641. complex, and its subexpression must be atomic.
  13642. \subsection{Explicate Control}
  13643. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13644. \code{explicate\_assign}.
  13645. \subsection{Select Instructions}
  13646. \index{subject}{select instructions}
  13647. Generate instructions for \code{AllocateArray} similar to those for
  13648. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13649. except that the tag at the front of the array should instead use the
  13650. representation discussed in section~\ref{sec:array-rep}.
  13651. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13652. extract the length from the tag.
  13653. The instructions generated for accessing an element of an array differ
  13654. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13655. that the index is not a constant so you need to generate instructions
  13656. that compute the offset at runtime.
  13657. Compile the \code{exit} primitive into a call to the \code{exit}
  13658. function of the C standard library, with an argument of $255$.
  13659. %% Also, note that assignment to an array element may appear in
  13660. %% as a stand-alone statement, so make sure to handle that situation in
  13661. %% this pass.
  13662. %% Finally, the instructions for \code{any-vectorof-length} should be
  13663. %% similar to those for \code{vectorof-length}, except that one must
  13664. %% first project the array by writing zeroes into the $3$-bit tag
  13665. \begin{exercise}\normalfont\normalsize
  13666. Implement a compiler for the \LangArray{} language by extending your
  13667. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13668. programs, including the one shown in figure~\ref{fig:inner_product}
  13669. and also a program that multiplies two matrices. Note that although
  13670. matrices are two-dimensional arrays, they can be encoded into
  13671. one-dimensional arrays by laying out each row in the array, one after
  13672. the next.
  13673. \end{exercise}
  13674. {\if\edition\racketEd
  13675. \section{Challenge: Generational Collection}
  13676. The copying collector described in section~\ref{sec:GC} can incur
  13677. significant runtime overhead because the call to \code{collect} takes
  13678. time proportional to all the live data. One way to reduce this
  13679. overhead is to reduce how much data is inspected in each call to
  13680. \code{collect}. In particular, researchers have observed that recently
  13681. allocated data is more likely to become garbage then data that has
  13682. survived one or more previous calls to \code{collect}. This insight
  13683. motivated the creation of \emph{generational garbage collectors}
  13684. \index{subject}{generational garbage collector} that
  13685. (1) segregate data according to its age into two or more generations;
  13686. (2) allocate less space for younger generations, so collecting them is
  13687. faster, and more space for the older generations; and (3) perform
  13688. collection on the younger generations more frequently than on older
  13689. generations~\citep{Wilson:1992fk}.
  13690. For this challenge assignment, the goal is to adapt the copying
  13691. collector implemented in \code{runtime.c} to use two generations, one
  13692. for young data and one for old data. Each generation consists of a
  13693. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13694. \code{collect} function to use the two generations:
  13695. \begin{enumerate}
  13696. \item Copy the young generation's FromSpace to its ToSpace and then
  13697. switch the role of the ToSpace and FromSpace.
  13698. \item If there is enough space for the requested number of bytes in
  13699. the young FromSpace, then return from \code{collect}.
  13700. \item If there is not enough space in the young FromSpace for the
  13701. requested bytes, then move the data from the young generation to the
  13702. old one with the following steps:
  13703. \begin{enumerate}
  13704. \item[a.] If there is enough room in the old FromSpace, copy the young
  13705. FromSpace to the old FromSpace and then return.
  13706. \item[b.] If there is not enough room in the old FromSpace, then collect
  13707. the old generation by copying the old FromSpace to the old ToSpace
  13708. and swap the roles of the old FromSpace and ToSpace.
  13709. \item[c.] If there is enough room now, copy the young FromSpace to the
  13710. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13711. and ToSpace for the old generation. Copy the young FromSpace and
  13712. the old FromSpace into the larger FromSpace for the old
  13713. generation and then return.
  13714. \end{enumerate}
  13715. \end{enumerate}
  13716. We recommend that you generalize the \code{cheney} function so that it
  13717. can be used for all the copies mentioned: between the young FromSpace
  13718. and ToSpace, between the old FromSpace and ToSpace, and between the
  13719. young FromSpace and old FromSpace. This can be accomplished by adding
  13720. parameters to \code{cheney} that replace its use of the global
  13721. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13722. \code{tospace\_begin}, and \code{tospace\_end}.
  13723. Note that the collection of the young generation does not traverse the
  13724. old generation. This introduces a potential problem: there may be
  13725. young data that is reachable only through pointers in the old
  13726. generation. If these pointers are not taken into account, the
  13727. collector could throw away young data that is live! One solution,
  13728. called \emph{pointer recording}, is to maintain a set of all the
  13729. pointers from the old generation into the new generation and consider
  13730. this set as part of the root set. To maintain this set, the compiler
  13731. must insert extra instructions around every \code{vector-set!}. If the
  13732. vector being modified is in the old generation, and if the value being
  13733. written is a pointer into the new generation, then that pointer must
  13734. be added to the set. Also, if the value being overwritten was a
  13735. pointer into the new generation, then that pointer should be removed
  13736. from the set.
  13737. \begin{exercise}\normalfont\normalsize
  13738. Adapt the \code{collect} function in \code{runtime.c} to implement
  13739. generational garbage collection, as outlined in this section.
  13740. Update the code generation for \code{vector-set!} to implement
  13741. pointer recording. Make sure that your new compiler and runtime
  13742. execute without error on your test suite.
  13743. \end{exercise}
  13744. \fi}
  13745. \section{Further Reading}
  13746. \citet{Appel90} describes many data representation approaches
  13747. including the ones used in the compilation of Standard ML.
  13748. There are many alternatives to copying collectors (and their bigger
  13749. siblings, the generational collectors) with regard to garbage
  13750. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13751. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13752. collectors are that allocation is fast (just a comparison and pointer
  13753. increment), there is no fragmentation, cyclic garbage is collected,
  13754. and the time complexity of collection depends only on the amount of
  13755. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13756. main disadvantages of a two-space copying collector is that it uses a
  13757. lot of extra space and takes a long time to perform the copy, though
  13758. these problems are ameliorated in generational collectors.
  13759. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13760. small objects and generate a lot of garbage, so copying and
  13761. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13762. Garbage collection is an active research topic, especially concurrent
  13763. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13764. developing new techniques and revisiting old
  13765. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13766. meet every year at the International Symposium on Memory Management to
  13767. present these findings.
  13768. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13769. \chapter{Functions}
  13770. \label{ch:Lfun}
  13771. \index{subject}{function}
  13772. \setcounter{footnote}{0}
  13773. This chapter studies the compilation of a subset of \racket{Typed
  13774. Racket}\python{Python} in which only top-level function definitions
  13775. are allowed. This kind of function appears in the C programming
  13776. language, and it serves as an important stepping-stone to implementing
  13777. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13778. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13779. \section{The \LangFun{} Language}
  13780. The concrete syntax and abstract syntax for function definitions and
  13781. function application are shown in
  13782. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13783. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13784. with zero or more function definitions. The function names from these
  13785. definitions are in scope for the entire program, including all the
  13786. function definitions, and therefore the ordering of function
  13787. definitions does not matter.
  13788. %
  13789. \python{The abstract syntax for function parameters in
  13790. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13791. consists of a parameter name and its type. This design differs from
  13792. Python's \code{ast} module, which has a more complex structure for
  13793. function parameters to handle keyword parameters,
  13794. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13795. complex Python abstract syntax into the simpler syntax shown in
  13796. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13797. \code{FunctionDef} constructor are for decorators and a type
  13798. comment, neither of which are used by our compiler. We recommend
  13799. replacing them with \code{None} in the \code{shrink} pass.
  13800. }
  13801. %
  13802. The concrete syntax for function application
  13803. \index{subject}{function application}
  13804. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13805. where the first expression
  13806. must evaluate to a function and the remaining expressions are the arguments. The
  13807. abstract syntax for function application is
  13808. $\APPLY{\Exp}{\Exp^*}$.
  13809. %% The syntax for function application does not include an explicit
  13810. %% keyword, which is error prone when using \code{match}. To alleviate
  13811. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13812. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13813. Functions are first-class in the sense that a function pointer
  13814. \index{subject}{function pointer} is data and can be stored in memory or passed
  13815. as a parameter to another function. Thus, there is a function
  13816. type, written
  13817. {\if\edition\racketEd
  13818. \begin{lstlisting}
  13819. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13820. \end{lstlisting}
  13821. \fi}
  13822. {\if\edition\pythonEd\pythonColor
  13823. \begin{lstlisting}
  13824. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13825. \end{lstlisting}
  13826. \fi}
  13827. %
  13828. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13829. through $\Type_n$ and whose return type is $\Type_R$. The main
  13830. limitation of these functions (with respect to
  13831. \racket{Racket}\python{Python} functions) is that they are not
  13832. lexically scoped. That is, the only external entities that can be
  13833. referenced from inside a function body are other globally defined
  13834. functions. The syntax of \LangFun{} prevents function definitions from
  13835. being nested inside each other.
  13836. \newcommand{\LfunGrammarRacket}{
  13837. \begin{array}{lcl}
  13838. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13839. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13840. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13841. \end{array}
  13842. }
  13843. \newcommand{\LfunASTRacket}{
  13844. \begin{array}{lcl}
  13845. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13846. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13847. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13848. \end{array}
  13849. }
  13850. \newcommand{\LfunGrammarPython}{
  13851. \begin{array}{lcl}
  13852. \Type &::=& \key{int}
  13853. \MID \key{bool} \MID \key{void}
  13854. \MID \key{tuple}\LS \Type^+ \RS
  13855. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13856. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13857. \Stmt &::=& \CRETURN{\Exp} \\
  13858. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13859. \end{array}
  13860. }
  13861. \newcommand{\LfunASTPython}{
  13862. \begin{array}{lcl}
  13863. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13864. \MID \key{TupleType}\LS\Type^+\RS\\
  13865. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13866. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13867. \Stmt &::=& \RETURN{\Exp} \\
  13868. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13869. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13870. \end{array}
  13871. }
  13872. \begin{figure}[tp]
  13873. \centering
  13874. \begin{tcolorbox}[colback=white]
  13875. \small
  13876. {\if\edition\racketEd
  13877. \[
  13878. \begin{array}{l}
  13879. \gray{\LintGrammarRacket{}} \\ \hline
  13880. \gray{\LvarGrammarRacket{}} \\ \hline
  13881. \gray{\LifGrammarRacket{}} \\ \hline
  13882. \gray{\LwhileGrammarRacket} \\ \hline
  13883. \gray{\LtupGrammarRacket} \\ \hline
  13884. \LfunGrammarRacket \\
  13885. \begin{array}{lcl}
  13886. \LangFunM{} &::=& \Def \ldots \; \Exp
  13887. \end{array}
  13888. \end{array}
  13889. \]
  13890. \fi}
  13891. {\if\edition\pythonEd\pythonColor
  13892. \[
  13893. \begin{array}{l}
  13894. \gray{\LintGrammarPython{}} \\ \hline
  13895. \gray{\LvarGrammarPython{}} \\ \hline
  13896. \gray{\LifGrammarPython{}} \\ \hline
  13897. \gray{\LwhileGrammarPython} \\ \hline
  13898. \gray{\LtupGrammarPython} \\ \hline
  13899. \LfunGrammarPython \\
  13900. \begin{array}{rcl}
  13901. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13902. \end{array}
  13903. \end{array}
  13904. \]
  13905. \fi}
  13906. \end{tcolorbox}
  13907. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13908. \label{fig:Lfun-concrete-syntax}
  13909. \index{subject}{Lfun@\LangFun{} concrete syntax}
  13910. \end{figure}
  13911. \begin{figure}[tp]
  13912. \centering
  13913. \begin{tcolorbox}[colback=white]
  13914. \small
  13915. {\if\edition\racketEd
  13916. \[
  13917. \begin{array}{l}
  13918. \gray{\LintOpAST} \\ \hline
  13919. \gray{\LvarASTRacket{}} \\ \hline
  13920. \gray{\LifASTRacket{}} \\ \hline
  13921. \gray{\LwhileASTRacket{}} \\ \hline
  13922. \gray{\LtupASTRacket{}} \\ \hline
  13923. \LfunASTRacket \\
  13924. \begin{array}{lcl}
  13925. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13926. \end{array}
  13927. \end{array}
  13928. \]
  13929. \fi}
  13930. {\if\edition\pythonEd\pythonColor
  13931. \[
  13932. \begin{array}{l}
  13933. \gray{\LintASTPython{}} \\ \hline
  13934. \gray{\LvarASTPython{}} \\ \hline
  13935. \gray{\LifASTPython{}} \\ \hline
  13936. \gray{\LwhileASTPython} \\ \hline
  13937. \gray{\LtupASTPython} \\ \hline
  13938. \LfunASTPython \\
  13939. \begin{array}{rcl}
  13940. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13941. \end{array}
  13942. \end{array}
  13943. \]
  13944. \fi}
  13945. \end{tcolorbox}
  13946. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13947. \label{fig:Lfun-syntax}
  13948. \index{subject}{Lfun@\LangFun{} abstract syntax}
  13949. \end{figure}
  13950. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13951. representative example of defining and using functions in \LangFun{}.
  13952. We define a function \code{map} that applies some other function
  13953. \code{f} to both elements of a tuple and returns a new tuple
  13954. containing the results. We also define a function \code{inc}. The
  13955. program applies \code{map} to \code{inc} and
  13956. %
  13957. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13958. %
  13959. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13960. %
  13961. from which we return \code{42}.
  13962. \begin{figure}[tbp]
  13963. \begin{tcolorbox}[colback=white]
  13964. {\if\edition\racketEd
  13965. \begin{lstlisting}
  13966. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13967. : (Vector Integer Integer)
  13968. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13969. (define (inc [x : Integer]) : Integer
  13970. (+ x 1))
  13971. (vector-ref (map inc (vector 0 41)) 1)
  13972. \end{lstlisting}
  13973. \fi}
  13974. {\if\edition\pythonEd\pythonColor
  13975. \begin{lstlisting}
  13976. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13977. return f(v[0]), f(v[1])
  13978. def inc(x : int) -> int:
  13979. return x + 1
  13980. print(map(inc, (0, 41))[1])
  13981. \end{lstlisting}
  13982. \fi}
  13983. \end{tcolorbox}
  13984. \caption{Example of using functions in \LangFun{}.}
  13985. \label{fig:Lfun-function-example}
  13986. \end{figure}
  13987. The definitional interpreter for \LangFun{} is shown in
  13988. figure~\ref{fig:interp-Lfun}. The case for the
  13989. %
  13990. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13991. %
  13992. AST is responsible for setting up the mutual recursion between the
  13993. top-level function definitions.
  13994. %
  13995. \racket{We use the classic back-patching
  13996. \index{subject}{back-patching} approach that uses mutable variables
  13997. and makes two passes over the function
  13998. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13999. top-level environment using a mutable cons cell for each function
  14000. definition. Note that the \code{lambda}\index{subject}{lambda} value
  14001. for each function is incomplete; it does not yet include the environment.
  14002. Once the top-level environment has been constructed, we iterate over it and
  14003. update the \code{lambda} values to use the top-level environment.}
  14004. %
  14005. \python{We create a dictionary named \code{env} and fill it in
  14006. by mapping each function name to a new \code{Function} value,
  14007. each of which stores a reference to the \code{env}.
  14008. (We define the class \code{Function} for this purpose.)}
  14009. %
  14010. To interpret a function \racket{application}\python{call}, we match
  14011. the result of the function expression to obtain a function value. We
  14012. then extend the function's environment with the mapping of parameters to
  14013. argument values. Finally, we interpret the body of the function in
  14014. this extended environment.
  14015. \begin{figure}[tp]
  14016. \begin{tcolorbox}[colback=white]
  14017. {\if\edition\racketEd
  14018. \begin{lstlisting}
  14019. (define interp-Lfun-class
  14020. (class interp-Lvec-class
  14021. (super-new)
  14022. (define/override ((interp-exp env) e)
  14023. (define recur (interp-exp env))
  14024. (match e
  14025. [(Apply fun args)
  14026. (define fun-val (recur fun))
  14027. (define arg-vals (for/list ([e args]) (recur e)))
  14028. (match fun-val
  14029. [`(function (,xs ...) ,body ,fun-env)
  14030. (define params-args (for/list ([x xs] [arg arg-vals])
  14031. (cons x (box arg))))
  14032. (define new-env (append params-args fun-env))
  14033. ((interp-exp new-env) body)]
  14034. [else
  14035. (error 'interp-exp "expected function, not ~a" fun-val)])]
  14036. [else ((super interp-exp env) e)]
  14037. ))
  14038. (define/public (interp-def d)
  14039. (match d
  14040. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  14041. (cons f (box `(function ,xs ,body ())))]))
  14042. (define/override (interp-program p)
  14043. (match p
  14044. [(ProgramDefsExp info ds body)
  14045. (let ([top-level (for/list ([d ds]) (interp-def d))])
  14046. (for/list ([f (in-dict-values top-level)])
  14047. (set-box! f (match (unbox f)
  14048. [`(function ,xs ,body ())
  14049. `(function ,xs ,body ,top-level)])))
  14050. ((interp-exp top-level) body))]))
  14051. ))
  14052. (define (interp-Lfun p)
  14053. (send (new interp-Lfun-class) interp-program p))
  14054. \end{lstlisting}
  14055. \fi}
  14056. {\if\edition\pythonEd\pythonColor
  14057. \begin{lstlisting}
  14058. class InterpLfun(InterpLtup):
  14059. def apply_fun(self, fun, args, e):
  14060. match fun:
  14061. case Function(name, xs, body, env):
  14062. new_env = env.copy().update(zip(xs, args))
  14063. return self.interp_stmts(body, new_env)
  14064. case _:
  14065. raise Exception('apply_fun: unexpected: ' + repr(fun))
  14066. def interp_exp(self, e, env):
  14067. match e:
  14068. case Call(Name('input_int'), []):
  14069. return super().interp_exp(e, env)
  14070. case Call(func, args):
  14071. f = self.interp_exp(func, env)
  14072. vs = [self.interp_exp(arg, env) for arg in args]
  14073. return self.apply_fun(f, vs, e)
  14074. case _:
  14075. return super().interp_exp(e, env)
  14076. def interp_stmt(self, s, env, cont):
  14077. match s:
  14078. case Return(value):
  14079. return self.interp_exp(value, env)
  14080. case FunctionDef(name, params, bod, dl, returns, comment):
  14081. if isinstance(params, ast.arguments):
  14082. ps = [p.arg for p in params.args]
  14083. else:
  14084. ps = [x for (x,t) in params]
  14085. env[name] = Function(name, ps, bod, env)
  14086. return self.interp_stmts(cont, env)
  14087. case _:
  14088. return super().interp_stmt(s, env, cont)
  14089. def interp(self, p):
  14090. match p:
  14091. case Module(ss):
  14092. env = {}
  14093. self.interp_stmts(ss, env)
  14094. if 'main' in env.keys():
  14095. self.apply_fun(env['main'], [], None)
  14096. case _:
  14097. raise Exception('interp: unexpected ' + repr(p))
  14098. \end{lstlisting}
  14099. \fi}
  14100. \end{tcolorbox}
  14101. \caption{Interpreter for the \LangFun{} language.}
  14102. \label{fig:interp-Lfun}
  14103. \end{figure}
  14104. %\margincomment{TODO: explain type checker}
  14105. The type checker for \LangFun{} is shown in
  14106. figure~\ref{fig:type-check-Lfun}.
  14107. %
  14108. \python{(We omit the code that parses function parameters into the
  14109. simpler abstract syntax.)}
  14110. %
  14111. Similarly to the interpreter, the case for the
  14112. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14113. %
  14114. AST is responsible for setting up the mutual recursion between the
  14115. top-level function definitions. We begin by creating a mapping
  14116. \code{env} from every function name to its type. We then type check
  14117. the program using this mapping.
  14118. %
  14119. \python{To check a function definition, we copy and extend the
  14120. \code{env} with the parameters of the function. We then type check
  14121. the body of the function and obtain the actual return type
  14122. \code{rt}, which is either the type of the expression in a
  14123. \code{return} statement or the \code{VoidType} if control reaches
  14124. the end of the function without a \code{return} statement. (If
  14125. there are multiple \code{return} statements, the types of their
  14126. expressions must agree.) Finally, we check that the actual return
  14127. type \code{rt} is equal to the declared return type \code{returns}.}
  14128. %
  14129. To check a function \racket{application}\python{call}, we match
  14130. the type of the function expression to a function type and check that
  14131. the types of the argument expressions are equal to the function's
  14132. parameter types. The type of the \racket{application}\python{call} as
  14133. a whole is the return type from the function type.
  14134. \begin{figure}[tp]
  14135. \begin{tcolorbox}[colback=white]
  14136. {\if\edition\racketEd
  14137. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14138. (define type-check-Lfun-class
  14139. (class type-check-Lvec-class
  14140. (super-new)
  14141. (inherit check-type-equal?)
  14142. (define/public (type-check-apply env e es)
  14143. (define-values (e^ ty) ((type-check-exp env) e))
  14144. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14145. ((type-check-exp env) e)))
  14146. (match ty
  14147. [`(,ty^* ... -> ,rt)
  14148. (for ([arg-ty ty*] [param-ty ty^*])
  14149. (check-type-equal? arg-ty param-ty (Apply e es)))
  14150. (values e^ e* rt)]))
  14151. (define/override (type-check-exp env)
  14152. (lambda (e)
  14153. (match e
  14154. [(FunRef f n)
  14155. (values (FunRef f n) (dict-ref env f))]
  14156. [(Apply e es)
  14157. (define-values (e^ es^ rt) (type-check-apply env e es))
  14158. (values (Apply e^ es^) rt)]
  14159. [(Call e es)
  14160. (define-values (e^ es^ rt) (type-check-apply env e es))
  14161. (values (Call e^ es^) rt)]
  14162. [else ((super type-check-exp env) e)])))
  14163. (define/public (type-check-def env)
  14164. (lambda (e)
  14165. (match e
  14166. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14167. (define new-env (append (map cons xs ps) env))
  14168. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14169. (check-type-equal? ty^ rt body)
  14170. (Def f p:t* rt info body^)])))
  14171. (define/public (fun-def-type d)
  14172. (match d
  14173. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14174. (define/override (type-check-program e)
  14175. (match e
  14176. [(ProgramDefsExp info ds body)
  14177. (define env (for/list ([d ds])
  14178. (cons (Def-name d) (fun-def-type d))))
  14179. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14180. (define-values (body^ ty) ((type-check-exp env) body))
  14181. (check-type-equal? ty 'Integer body)
  14182. (ProgramDefsExp info ds^ body^)]))))
  14183. (define (type-check-Lfun p)
  14184. (send (new type-check-Lfun-class) type-check-program p))
  14185. \end{lstlisting}
  14186. \fi}
  14187. {\if\edition\pythonEd\pythonColor
  14188. \begin{lstlisting}
  14189. class TypeCheckLfun(TypeCheckLtup):
  14190. def type_check_exp(self, e, env):
  14191. match e:
  14192. case Call(Name('input_int'), []):
  14193. return super().type_check_exp(e, env)
  14194. case Call(func, args):
  14195. func_t = self.type_check_exp(func, env)
  14196. args_t = [self.type_check_exp(arg, env) for arg in args]
  14197. match func_t:
  14198. case FunctionType(params_t, return_t):
  14199. for (arg_t, param_t) in zip(args_t, params_t):
  14200. check_type_equal(param_t, arg_t, e)
  14201. return return_t
  14202. case _:
  14203. raise Exception('type_check_exp: in call, unexpected ' +
  14204. repr(func_t))
  14205. case _:
  14206. return super().type_check_exp(e, env)
  14207. def type_check_stmts(self, ss, env):
  14208. if len(ss) == 0:
  14209. return VoidType()
  14210. match ss[0]:
  14211. case FunctionDef(name, params, body, dl, returns, comment):
  14212. new_env = env.copy().update(params)
  14213. rt = self.type_check_stmts(body, new_env)
  14214. check_type_equal(returns, rt, ss[0])
  14215. return self.type_check_stmts(ss[1:], env)
  14216. case Return(value):
  14217. return self.type_check_exp(value, env)
  14218. case _:
  14219. return super().type_check_stmts(ss, env)
  14220. def type_check(self, p):
  14221. match p:
  14222. case Module(body):
  14223. env = {}
  14224. for s in body:
  14225. match s:
  14226. case FunctionDef(name, params, bod, dl, returns, comment):
  14227. if name in env:
  14228. raise Exception('type_check: function ' +
  14229. repr(name) + ' defined twice')
  14230. params_t = [t for (x,t) in params]
  14231. env[name] = FunctionType(params_t, returns)
  14232. self.type_check_stmts(body, env)
  14233. case _:
  14234. raise Exception('type_check: unexpected ' + repr(p))
  14235. \end{lstlisting}
  14236. \fi}
  14237. \end{tcolorbox}
  14238. \caption{Type checker for the \LangFun{} language.}
  14239. \label{fig:type-check-Lfun}
  14240. \end{figure}
  14241. \clearpage
  14242. \section{Functions in x86}
  14243. \label{sec:fun-x86}
  14244. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14245. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14246. %% \margincomment{\tiny Talk about the return address on the
  14247. %% stack and what callq and retq does.\\ --Jeremy }
  14248. The x86 architecture provides a few features to support the
  14249. implementation of functions. We have already seen that there are
  14250. labels in x86 so that one can refer to the location of an instruction,
  14251. as is needed for jump instructions. Labels can also be used to mark
  14252. the beginning of the instructions for a function. Going further, we
  14253. can obtain the address of a label by using the \key{leaq}
  14254. instruction. For example, the following puts the address of the
  14255. \code{inc} label into the \code{rbx} register:
  14256. \begin{lstlisting}
  14257. leaq inc(%rip), %rbx
  14258. \end{lstlisting}
  14259. Recall from section~\ref{sec:select-instructions-gc} that
  14260. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14261. addressing.
  14262. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14263. to functions whose locations were given by a label, such as
  14264. \code{read\_int}. To support function calls in this chapter we instead
  14265. jump to functions whose location are given by an address in
  14266. a register; that is, we use \emph{indirect function calls}. The
  14267. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14268. before the register name.\index{subject}{indirect function call}
  14269. \begin{lstlisting}
  14270. callq *%rbx
  14271. \end{lstlisting}
  14272. \subsection{Calling Conventions}
  14273. \label{sec:calling-conventions-fun}
  14274. \index{subject}{calling conventions}
  14275. The \code{callq} instruction provides partial support for implementing
  14276. functions: it pushes the return address on the stack and it jumps to
  14277. the target. However, \code{callq} does not handle
  14278. \begin{enumerate}
  14279. \item parameter passing,
  14280. \item pushing frames on the procedure call stack and popping them off,
  14281. or
  14282. \item determining how registers are shared by different functions.
  14283. \end{enumerate}
  14284. Regarding parameter passing, recall that the x86-64 calling
  14285. convention for Unix-based systems uses the following six registers to
  14286. pass arguments to a function, in the given order:
  14287. \begin{lstlisting}
  14288. rdi rsi rdx rcx r8 r9
  14289. \end{lstlisting}
  14290. If there are more than six arguments, then the calling convention
  14291. mandates using space on the frame of the caller for the rest of the
  14292. arguments. However, to ease the implementation of efficient tail calls
  14293. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14294. arguments.
  14295. %
  14296. The return value of the function is stored in register \code{rax}.
  14297. Regarding frames \index{subject}{frame} and the procedure call stack,
  14298. \index{subject}{procedure call stack} recall from
  14299. section~\ref{sec:x86} that the stack grows down and each function call
  14300. uses a chunk of space on the stack called a frame. The caller sets the
  14301. stack pointer, register \code{rsp}, to the last data item in its
  14302. frame. The callee must not change anything in the caller's frame, that
  14303. is, anything that is at or above the stack pointer. The callee is free
  14304. to use locations that are below the stack pointer.
  14305. Recall that we store variables of tuple type on the root stack. So,
  14306. the prelude\index{subject}{prelude} of a function needs to move the
  14307. root stack pointer \code{r15} up according to the number of variables
  14308. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14309. move the root stack pointer back down. Also, the prelude must
  14310. initialize to \code{0} this frame's slots in the root stack to signal
  14311. to the garbage collector that those slots do not yet contain a valid
  14312. pointer. Otherwise the garbage collector will interpret the garbage
  14313. bits in those slots as memory addresses and try to traverse them,
  14314. causing serious mayhem!
  14315. Regarding the sharing of registers between different functions, recall
  14316. from section~\ref{sec:calling-conventions} that the registers are
  14317. divided into two groups, the caller-saved registers and the
  14318. callee-saved registers. The caller should assume that all the
  14319. caller-saved registers are overwritten with arbitrary values by the
  14320. callee. For that reason we recommend in
  14321. section~\ref{sec:calling-conventions} that variables that are live
  14322. during a function call should not be assigned to caller-saved
  14323. registers.
  14324. On the flip side, if the callee wants to use a callee-saved register,
  14325. the callee must save the contents of those registers on their stack
  14326. frame and then put them back prior to returning to the caller. For
  14327. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14328. the register allocator assigns a variable to a callee-saved register,
  14329. then the prelude of the \code{main} function must save that register
  14330. to the stack and the conclusion of \code{main} must restore it. This
  14331. recommendation now generalizes to all functions.
  14332. Recall that the base pointer, register \code{rbp}, is used as a
  14333. point of reference within a frame, so that each local variable can be
  14334. accessed at a fixed offset from the base pointer
  14335. (section~\ref{sec:x86}).
  14336. %
  14337. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14338. frames.
  14339. \begin{figure}[tbp]
  14340. \centering
  14341. \begin{tcolorbox}[colback=white]
  14342. \begin{tabular}{r|r|l|l} \hline
  14343. Caller View & Callee View & Contents & Frame \\ \hline
  14344. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14345. 0(\key{\%rbp}) & & old \key{rbp} \\
  14346. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14347. \ldots & & \ldots \\
  14348. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14349. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14350. \ldots & & \ldots \\
  14351. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14352. %% & & \\
  14353. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14354. %% & \ldots & \ldots \\
  14355. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14356. \hline
  14357. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14358. & 0(\key{\%rbp}) & old \key{rbp} \\
  14359. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14360. & \ldots & \ldots \\
  14361. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14362. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14363. & \ldots & \ldots \\
  14364. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14365. \end{tabular}
  14366. \end{tcolorbox}
  14367. \caption{Memory layout of caller and callee frames.}
  14368. \label{fig:call-frames}
  14369. \end{figure}
  14370. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14371. %% local variables and for storing the values of callee-saved registers
  14372. %% (we shall refer to all of these collectively as ``locals''), and that
  14373. %% at the beginning of a function we move the stack pointer \code{rsp}
  14374. %% down to make room for them.
  14375. %% We recommend storing the local variables
  14376. %% first and then the callee-saved registers, so that the local variables
  14377. %% can be accessed using \code{rbp} the same as before the addition of
  14378. %% functions.
  14379. %% To make additional room for passing arguments, we shall
  14380. %% move the stack pointer even further down. We count how many stack
  14381. %% arguments are needed for each function call that occurs inside the
  14382. %% body of the function and find their maximum. Adding this number to the
  14383. %% number of locals gives us how much the \code{rsp} should be moved at
  14384. %% the beginning of the function. In preparation for a function call, we
  14385. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14386. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14387. %% so on.
  14388. %% Upon calling the function, the stack arguments are retrieved by the
  14389. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14390. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14391. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14392. %% the layout of the caller and callee frames. Notice how important it is
  14393. %% that we correctly compute the maximum number of arguments needed for
  14394. %% function calls; if that number is too small then the arguments and
  14395. %% local variables will smash into each other!
  14396. \subsection{Efficient Tail Calls}
  14397. \label{sec:tail-call}
  14398. In general, the amount of stack space used by a program is determined
  14399. by the longest chain of nested function calls. That is, if function
  14400. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14401. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14402. large if functions are recursive. However, in some cases we can
  14403. arrange to use only a constant amount of space for a long chain of
  14404. nested function calls.
  14405. A \emph{tail call}\index{subject}{tail call} is a function call that
  14406. happens as the last action in a function body. For example, in the
  14407. following program, the recursive call to \code{tail\_sum} is a tail
  14408. call:
  14409. \begin{center}
  14410. {\if\edition\racketEd
  14411. \begin{lstlisting}
  14412. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14413. (if (eq? n 0)
  14414. r
  14415. (tail_sum (- n 1) (+ n r))))
  14416. (+ (tail_sum 3 0) 36)
  14417. \end{lstlisting}
  14418. \fi}
  14419. {\if\edition\pythonEd\pythonColor
  14420. \begin{lstlisting}
  14421. def tail_sum(n : int, r : int) -> int:
  14422. if n == 0:
  14423. return r
  14424. else:
  14425. return tail_sum(n - 1, n + r)
  14426. print(tail_sum(3, 0) + 36)
  14427. \end{lstlisting}
  14428. \fi}
  14429. \end{center}
  14430. At a tail call, the frame of the caller is no longer needed, so we can
  14431. pop the caller's frame before making the tail
  14432. call. \index{subject}{frame} With this approach, a recursive function
  14433. that makes only tail calls ends up using a constant amount of stack
  14434. space. \racket{Functional languages like Racket rely heavily on
  14435. recursive functions, so the definition of Racket \emph{requires}
  14436. that all tail calls be optimized in this way.}
  14437. Some care is needed with regard to argument passing in tail calls. As
  14438. mentioned, for arguments beyond the sixth, the convention is to use
  14439. space in the caller's frame for passing arguments. However, for a
  14440. tail call we pop the caller's frame and can no longer use it. An
  14441. alternative is to use space in the callee's frame for passing
  14442. arguments. However, this option is also problematic because the caller
  14443. and callee's frames overlap in memory. As we begin to copy the
  14444. arguments from their sources in the caller's frame, the target
  14445. locations in the callee's frame might collide with the sources for
  14446. later arguments! We solve this problem by using the heap instead of
  14447. the stack for passing more than six arguments
  14448. (section~\ref{sec:limit-functions-r4}).
  14449. As mentioned, for a tail call we pop the caller's frame prior to
  14450. making the tail call. The instructions for popping a frame are the
  14451. instructions that we usually place in the conclusion of a
  14452. function. Thus, we also need to place such code immediately before
  14453. each tail call. These instructions include restoring the callee-saved
  14454. registers, so it is fortunate that the argument passing registers are
  14455. all caller-saved registers.
  14456. One note remains regarding which instruction to use to make the tail
  14457. call. When the callee is finished, it should not return to the current
  14458. function but instead return to the function that called the current
  14459. one. Thus, the return address that is already on the stack is the
  14460. right one, and we should not use \key{callq} to make the tail call
  14461. because that would overwrite the return address. Instead we simply use
  14462. the \key{jmp} instruction. As with the indirect function call, we write
  14463. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14464. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14465. jump target because the conclusion can overwrite just about everything
  14466. else.
  14467. \begin{lstlisting}
  14468. jmp *%rax
  14469. \end{lstlisting}
  14470. \section{Shrink \LangFun{}}
  14471. \label{sec:shrink-r4}
  14472. The \code{shrink} pass performs a minor modification to ease the
  14473. later passes. This pass introduces an explicit \code{main} function
  14474. that gobbles up all the top-level statements of the module.
  14475. %
  14476. \racket{It also changes the top \code{ProgramDefsExp} form to
  14477. \code{ProgramDefs}.}
  14478. {\if\edition\racketEd
  14479. \begin{lstlisting}
  14480. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14481. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14482. \end{lstlisting}
  14483. where $\itm{mainDef}$ is
  14484. \begin{lstlisting}
  14485. (Def 'main '() 'Integer '() |$\Exp'$|)
  14486. \end{lstlisting}
  14487. \fi}
  14488. {\if\edition\pythonEd\pythonColor
  14489. \begin{lstlisting}
  14490. Module(|$\Def\ldots\Stmt\ldots$|)
  14491. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14492. \end{lstlisting}
  14493. where $\itm{mainDef}$ is
  14494. \begin{lstlisting}
  14495. FunctionDef('main', [], |$\Stmt\ldots$|Return(Constant(0)), None, IntType(), None)
  14496. \end{lstlisting}
  14497. \fi}
  14498. \section{Reveal Functions and the \LangFunRef{} Language}
  14499. \label{sec:reveal-functions-r4}
  14500. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14501. in that it conflates the use of function names and local
  14502. variables. This is a problem because we need to compile the use of a
  14503. function name differently from the use of a local variable. In
  14504. particular, we use \code{leaq} to convert the function name (a label
  14505. in x86) to an address in a register. Thus, we create a new pass that
  14506. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14507. $n$ is the arity of the function.\python{\footnote{The arity is not
  14508. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14509. This pass is named \code{reveal\_functions} and the output language
  14510. is \LangFunRef{}\index{subject}{Lfunref@\LangFunRef{}}.
  14511. %is defined in figure~\ref{fig:f1-syntax}.
  14512. %% The concrete syntax for a
  14513. %% function reference is $\CFUNREF{f}$.
  14514. %% \begin{figure}[tp]
  14515. %% \centering
  14516. %% \fbox{
  14517. %% \begin{minipage}{0.96\textwidth}
  14518. %% {\if\edition\racketEd
  14519. %% \[
  14520. %% \begin{array}{lcl}
  14521. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14522. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14523. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14524. %% \end{array}
  14525. %% \]
  14526. %% \fi}
  14527. %% {\if\edition\pythonEd\pythonColor
  14528. %% \[
  14529. %% \begin{array}{lcl}
  14530. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14531. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14532. %% \end{array}
  14533. %% \]
  14534. %% \fi}
  14535. %% \end{minipage}
  14536. %% }
  14537. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14538. %% (figure~\ref{fig:Lfun-syntax}).}
  14539. %% \label{fig:f1-syntax}
  14540. %% \end{figure}
  14541. %% Distinguishing between calls in tail position and non-tail position
  14542. %% requires the pass to have some notion of context. We recommend using
  14543. %% two mutually recursive functions, one for processing expressions in
  14544. %% tail position and another for the rest.
  14545. \racket{Placing this pass after \code{uniquify} will make sure that
  14546. there are no local variables and functions that share the same
  14547. name.}
  14548. %
  14549. The \code{reveal\_functions} pass should come before the
  14550. \code{remove\_complex\_operands} pass because function references
  14551. should be categorized as complex expressions.
  14552. \section{Limit Functions}
  14553. \label{sec:limit-functions-r4}
  14554. Recall that we wish to limit the number of function parameters to six
  14555. so that we do not need to use the stack for argument passing, which
  14556. makes it easier to implement efficient tail calls. However, because
  14557. the input language \LangFun{} supports arbitrary numbers of function
  14558. arguments, we have some work to do! The \code{limit\_functions} pass
  14559. transforms functions and function calls that involve more than six
  14560. arguments to pass the first five arguments as usual, but it packs the
  14561. rest of the arguments into a tuple and passes it as the sixth
  14562. argument.\footnote{The implementation this pass can be postponed to
  14563. last because you can test the rest of the passes on functions with
  14564. six or fewer parameters.}
  14565. Each function definition with seven or more parameters is transformed as
  14566. follows:
  14567. {\if\edition\racketEd
  14568. \begin{lstlisting}
  14569. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14570. |$\Rightarrow$|
  14571. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14572. \end{lstlisting}
  14573. \fi}
  14574. {\if\edition\pythonEd\pythonColor
  14575. \begin{lstlisting}
  14576. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14577. |$\Rightarrow$|
  14578. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14579. |$T_r$|, None, |$\itm{body}'$|, None)
  14580. \end{lstlisting}
  14581. \fi}
  14582. %
  14583. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14584. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14585. the $k$th element of the tuple, where $k = i - 6$.
  14586. %
  14587. {\if\edition\racketEd
  14588. \begin{lstlisting}
  14589. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14590. \end{lstlisting}
  14591. \fi}
  14592. {\if\edition\pythonEd\pythonColor
  14593. \begin{lstlisting}
  14594. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14595. \end{lstlisting}
  14596. \fi}
  14597. For function calls with too many arguments, the \code{limit\_functions}
  14598. pass transforms them in the following way:
  14599. \begin{tabular}{lll}
  14600. \begin{minipage}{0.3\textwidth}
  14601. {\if\edition\racketEd
  14602. \begin{lstlisting}
  14603. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14604. \end{lstlisting}
  14605. \fi}
  14606. {\if\edition\pythonEd\pythonColor
  14607. \begin{lstlisting}
  14608. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14609. \end{lstlisting}
  14610. \fi}
  14611. \end{minipage}
  14612. &
  14613. $\Rightarrow$
  14614. &
  14615. \begin{minipage}{0.5\textwidth}
  14616. {\if\edition\racketEd
  14617. \begin{lstlisting}
  14618. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14619. \end{lstlisting}
  14620. \fi}
  14621. {\if\edition\pythonEd\pythonColor
  14622. \begin{lstlisting}
  14623. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14624. \end{lstlisting}
  14625. \fi}
  14626. \end{minipage}
  14627. \end{tabular}
  14628. \section{Remove Complex Operands}
  14629. \label{sec:rco-r4}
  14630. The primary decisions to make for this pass are whether to classify
  14631. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14632. atomic or complex expressions. Recall that an atomic expression
  14633. ends up as an immediate argument of an x86 instruction. Function
  14634. application translates to a sequence of instructions, so
  14635. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14636. a complex expression. On the other hand, the arguments of
  14637. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14638. expressions.
  14639. %
  14640. Regarding \code{FunRef}, as discussed previously, the function label
  14641. needs to be converted to an address using the \code{leaq}
  14642. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14643. needs to be classified as a complex expression so that we generate an
  14644. assignment statement with a left-hand side that can serve as the
  14645. target of the \code{leaq}.
  14646. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14647. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14648. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14649. and augments programs to include a list of function definitions.
  14650. %
  14651. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14652. \newcommand{\LfunMonadASTRacket}{
  14653. \begin{array}{lcl}
  14654. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14655. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14656. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14657. \end{array}
  14658. }
  14659. \newcommand{\LfunMonadASTPython}{
  14660. \begin{array}{lcl}
  14661. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14662. \MID \key{TupleType}\LS\Type^+\RS\\
  14663. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14664. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14665. \Stmt &::=& \RETURN{\Exp} \\
  14666. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14667. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14668. \end{array}
  14669. }
  14670. \begin{figure}[tp]
  14671. \centering
  14672. \begin{tcolorbox}[colback=white]
  14673. \footnotesize
  14674. {\if\edition\racketEd
  14675. \[
  14676. \begin{array}{l}
  14677. \gray{\LvarMonadASTRacket} \\ \hline
  14678. \gray{\LifMonadASTRacket} \\ \hline
  14679. \gray{\LwhileMonadASTRacket} \\ \hline
  14680. \gray{\LtupMonadASTRacket} \\ \hline
  14681. \LfunMonadASTRacket \\
  14682. \begin{array}{rcl}
  14683. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14684. \end{array}
  14685. \end{array}
  14686. \]
  14687. \fi}
  14688. {\if\edition\pythonEd\pythonColor
  14689. \[
  14690. \begin{array}{l}
  14691. \gray{\LvarMonadASTPython} \\ \hline
  14692. \gray{\LifMonadASTPython} \\ \hline
  14693. \gray{\LwhileMonadASTPython} \\ \hline
  14694. \gray{\LtupMonadASTPython} \\ \hline
  14695. \LfunMonadASTPython \\
  14696. \begin{array}{rcl}
  14697. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14698. \end{array}
  14699. \end{array}
  14700. \]
  14701. \fi}
  14702. \end{tcolorbox}
  14703. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14704. \label{fig:Lfun-anf-syntax}
  14705. \index{subject}{Lfunmon@\LangFunANF{} abstract syntax}
  14706. \end{figure}
  14707. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14708. %% \LangFunANF{} of this pass.
  14709. %% \begin{figure}[tp]
  14710. %% \centering
  14711. %% \fbox{
  14712. %% \begin{minipage}{0.96\textwidth}
  14713. %% \small
  14714. %% \[
  14715. %% \begin{array}{rcl}
  14716. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14717. %% \MID \VOID{} } \\
  14718. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14719. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14720. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14721. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14722. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14723. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14724. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14725. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14726. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14727. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14728. %% \end{array}
  14729. %% \]
  14730. %% \end{minipage}
  14731. %% }
  14732. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14733. %% \label{fig:Lfun-anf-syntax}
  14734. %% \end{figure}
  14735. \section{Explicate Control and the \LangCFun{} Language}
  14736. \label{sec:explicate-control-r4}
  14737. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14738. output of \code{explicate\_control}.
  14739. %
  14740. %% \racket{(The concrete syntax is given in
  14741. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14742. %
  14743. \racket{The auxiliary functions for assignment and tail contexts should
  14744. be updated with cases for \code{Apply} and \code{FunRef}.}
  14745. The auxiliary function for predicate context should be updated for
  14746. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14747. \code{FunRef} cannot be a Boolean.)
  14748. %
  14749. \racket{In assignment and predicate contexts,
  14750. \code{Apply} becomes \code{Call}, whereas
  14751. in tail position \code{Apply} becomes \code{TailCall}.}
  14752. %
  14753. We recommend defining a new auxiliary function for processing function
  14754. definitions. This code is similar to the case for \code{Program} in
  14755. \LangVec{}. The top-level \code{explicate\_control} function that
  14756. handles the \code{ProgramDefs} form of \LangFun{} can apply this
  14757. new function to all function definitions.
  14758. {\if\edition\pythonEd\pythonColor
  14759. The translation of \code{Return} statements requires a new auxiliary
  14760. function to handle expressions in tail context, called
  14761. \code{explicate\_tail}. The function should take an expression and the
  14762. dictionary of basic blocks and produce a list of statements in the
  14763. \LangCFun{} language. The \code{explicate\_tail} function should
  14764. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14765. and a default case for other kinds of expressions. The default case
  14766. should produce a \code{Return} statement. The case for \code{Call}
  14767. should change it into \code{TailCall}. The other cases should
  14768. recursively process their subexpressions and statements, choosing the
  14769. appropriate explicate functions for the various contexts.
  14770. \fi}
  14771. \newcommand{\CfunASTRacket}{
  14772. \begin{array}{lcl}
  14773. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14774. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14775. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14776. \end{array}
  14777. }
  14778. \newcommand{\CfunASTPython}{
  14779. \begin{array}{lcl}
  14780. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14781. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14782. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14783. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14784. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14785. \end{array}
  14786. }
  14787. \begin{figure}[tp]
  14788. \begin{tcolorbox}[colback=white]
  14789. \footnotesize
  14790. {\if\edition\racketEd
  14791. \[
  14792. \begin{array}{l}
  14793. \gray{\CvarASTRacket} \\ \hline
  14794. \gray{\CifASTRacket} \\ \hline
  14795. \gray{\CloopASTRacket} \\ \hline
  14796. \gray{\CtupASTRacket} \\ \hline
  14797. \CfunASTRacket \\
  14798. \begin{array}{lcl}
  14799. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14800. \end{array}
  14801. \end{array}
  14802. \]
  14803. \fi}
  14804. {\if\edition\pythonEd\pythonColor
  14805. \[
  14806. \begin{array}{l}
  14807. \gray{\CifASTPython} \\ \hline
  14808. \gray{\CtupASTPython} \\ \hline
  14809. \CfunASTPython \\
  14810. \begin{array}{lcl}
  14811. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14812. \end{array}
  14813. \end{array}
  14814. \]
  14815. \fi}
  14816. \end{tcolorbox}
  14817. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14818. \label{fig:c3-syntax}
  14819. \index{subject}{Cfun@\LangCFun{} abstract syntax}
  14820. \end{figure}
  14821. \clearpage
  14822. \section{Select Instructions and the \LangXIndCall{} Language}
  14823. \label{sec:select-r4}
  14824. \index{subject}{select instructions}
  14825. The output of select instructions is a program in the \LangXIndCall{}
  14826. language; the definition of its concrete syntax is shown in
  14827. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14828. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14829. directive on the labels of function definitions to make sure the
  14830. bottom three bits are zero, which we put to use in
  14831. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14832. this section. \index{subject}{x86}
  14833. \newcommand{\GrammarXIndCall}{
  14834. \begin{array}{lcl}
  14835. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14836. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14837. \Block &::= & \Instr^{+} \\
  14838. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14839. \end{array}
  14840. }
  14841. \newcommand{\ASTXIndCallRacket}{
  14842. \begin{array}{lcl}
  14843. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14844. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14845. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14846. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14847. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14848. \end{array}
  14849. }
  14850. \begin{figure}[tp]
  14851. \begin{tcolorbox}[colback=white]
  14852. \small
  14853. {\if\edition\racketEd
  14854. \[
  14855. \begin{array}{l}
  14856. \gray{\GrammarXIntRacket} \\ \hline
  14857. \gray{\GrammarXIfRacket} \\ \hline
  14858. \gray{\GrammarXGlobal} \\ \hline
  14859. \GrammarXIndCall \\
  14860. \begin{array}{lcl}
  14861. \LangXIndCallM{} &::= & \Def^{*}
  14862. \end{array}
  14863. \end{array}
  14864. \]
  14865. \fi}
  14866. {\if\edition\pythonEd
  14867. \[
  14868. \begin{array}{l}
  14869. \gray{\GrammarXIntPython} \\ \hline
  14870. \gray{\GrammarXIfPython} \\ \hline
  14871. \gray{\GrammarXGlobal} \\ \hline
  14872. \GrammarXIndCall \\
  14873. \begin{array}{lcl}
  14874. \LangXIndCallM{} &::= & \Def^{*}
  14875. \end{array}
  14876. \end{array}
  14877. \]
  14878. \fi}
  14879. \end{tcolorbox}
  14880. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14881. \label{fig:x86-3-concrete}
  14882. \end{figure}
  14883. \begin{figure}[tp]
  14884. \begin{tcolorbox}[colback=white]
  14885. \small
  14886. {\if\edition\racketEd
  14887. \[\arraycolsep=3pt
  14888. \begin{array}{l}
  14889. \gray{\ASTXIntRacket} \\ \hline
  14890. \gray{\ASTXIfRacket} \\ \hline
  14891. \gray{\ASTXGlobalRacket} \\ \hline
  14892. \ASTXIndCallRacket \\
  14893. \begin{array}{lcl}
  14894. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14895. \end{array}
  14896. \end{array}
  14897. \]
  14898. \fi}
  14899. {\if\edition\pythonEd\pythonColor
  14900. \[
  14901. \begin{array}{lcl}
  14902. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14903. \MID \BYTEREG{\Reg} } \\
  14904. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14905. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14906. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14907. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14908. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14909. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14910. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14911. \end{array}
  14912. \]
  14913. \fi}
  14914. \end{tcolorbox}
  14915. \caption{The abstract syntax of \LangXIndCall{} (extends
  14916. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14917. \label{fig:x86-3}
  14918. \end{figure}
  14919. An assignment of a function reference to a variable becomes a
  14920. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14921. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14922. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14923. node, whose concrete syntax is instruction-pointer-relative
  14924. addressing.
  14925. \begin{center}
  14926. \begin{tabular}{lcl}
  14927. \begin{minipage}{0.35\textwidth}
  14928. {\if\edition\racketEd
  14929. \begin{lstlisting}
  14930. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14931. \end{lstlisting}
  14932. \fi}
  14933. {\if\edition\pythonEd\pythonColor
  14934. \begin{lstlisting}
  14935. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14936. \end{lstlisting}
  14937. \fi}
  14938. \end{minipage}
  14939. &
  14940. $\Rightarrow$\qquad\qquad
  14941. &
  14942. \begin{minipage}{0.3\textwidth}
  14943. \begin{lstlisting}
  14944. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14945. \end{lstlisting}
  14946. \end{minipage}
  14947. \end{tabular}
  14948. \end{center}
  14949. Regarding function definitions, we need to remove the parameters and
  14950. instead perform parameter passing using the conventions discussed in
  14951. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14952. registers. We recommend turning the parameters into local variables
  14953. and generating instructions at the beginning of the function to move
  14954. from the argument-passing registers
  14955. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14956. {\if\edition\racketEd
  14957. \begin{lstlisting}
  14958. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14959. |$\Rightarrow$|
  14960. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14961. \end{lstlisting}
  14962. \fi}
  14963. {\if\edition\pythonEd\pythonColor
  14964. \begin{lstlisting}
  14965. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14966. |$\Rightarrow$|
  14967. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14968. \end{lstlisting}
  14969. \fi}
  14970. The basic blocks $B'$ are the same as $B$ except that the
  14971. \code{start} block is modified to add the instructions for moving from
  14972. the argument registers to the parameter variables. So the \code{start}
  14973. block of $B$ shown on the left of the following is changed to the code
  14974. on the right:
  14975. \begin{center}
  14976. \begin{minipage}{0.3\textwidth}
  14977. \begin{lstlisting}
  14978. start:
  14979. |$\itm{instr}_1$|
  14980. |$\cdots$|
  14981. |$\itm{instr}_n$|
  14982. \end{lstlisting}
  14983. \end{minipage}
  14984. $\Rightarrow$
  14985. \begin{minipage}{0.3\textwidth}
  14986. \begin{lstlisting}
  14987. |$f$|start:
  14988. movq %rdi, |$x_1$|
  14989. movq %rsi, |$x_2$|
  14990. |$\cdots$|
  14991. |$\itm{instr}_1$|
  14992. |$\cdots$|
  14993. |$\itm{instr}_n$|
  14994. \end{lstlisting}
  14995. \end{minipage}
  14996. \end{center}
  14997. Recall that we use the label \code{start} for the initial block of a
  14998. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14999. the conclusion of the program with \code{conclusion}, so that
  15000. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  15001. by a jump to \code{conclusion}. With the addition of function
  15002. definitions, there is a start block and conclusion for each function,
  15003. but their labels need to be unique. We recommend prepending the
  15004. function's name to \code{start} and \code{conclusion}, respectively,
  15005. to obtain unique labels.
  15006. \racket{The interpreter for \LangXIndCall{} needs to be given the
  15007. number of parameters the function expects, but the parameters are no
  15008. longer in the syntax of function definitions. Instead, add an entry
  15009. to $\itm{info}$ that maps \code{num-params} to the number of
  15010. parameters to construct $\itm{info}'$.}
  15011. By changing the parameters to local variables, we are giving the
  15012. register allocator control over which registers or stack locations to
  15013. use for them. If you implement the move-biasing challenge
  15014. (section~\ref{sec:move-biasing}), the register allocator will try to
  15015. assign the parameter variables to the corresponding argument register,
  15016. in which case the \code{patch\_instructions} pass will remove the
  15017. \code{movq} instruction. This happens in the example translation given
  15018. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  15019. the \code{add} function.
  15020. %
  15021. Also, note that the register allocator will perform liveness analysis
  15022. on this sequence of move instructions and build the interference
  15023. graph. So, for example, $x_1$ will be marked as interfering with
  15024. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  15025. which is good because otherwise the first \code{movq} would overwrite
  15026. the argument in \code{rsi} that is needed for $x_2$.
  15027. Next, consider the compilation of function calls. In the mirror image
  15028. of the handling of parameters in function definitions, the arguments
  15029. are moved to the argument-passing registers. Note that the function
  15030. is not given as a label, but its address is produced by the argument
  15031. $\itm{arg}_0$. So, we translate the call into an indirect function
  15032. call. The return value from the function is stored in \code{rax}, so
  15033. it needs to be moved into the \itm{lhs}.
  15034. \begin{lstlisting}
  15035. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  15036. |$\Rightarrow$|
  15037. movq |$\itm{arg}_1$|, %rdi
  15038. movq |$\itm{arg}_2$|, %rsi
  15039. |$\vdots$|
  15040. callq *|$\itm{arg}_0$|
  15041. movq %rax, |$\itm{lhs}$|
  15042. \end{lstlisting}
  15043. The \code{IndirectCallq} AST node includes an integer for the arity of
  15044. the function, that is, the number of parameters. That information is
  15045. useful in the \code{uncover\_live} pass for determining which
  15046. argument-passing registers are potentially read during the call.
  15047. For tail calls, the parameter passing is the same as non-tail calls:
  15048. generate instructions to move the arguments into the argument-passing
  15049. registers. After that we need to pop the frame from the procedure
  15050. call stack. However, we do not yet know how big the frame is; that
  15051. gets determined during register allocation. So, instead of generating
  15052. those instructions here, we invent a new instruction that means ``pop
  15053. the frame and then do an indirect jump,'' which we name
  15054. \code{TailJmp}. The abstract syntax for this instruction includes an
  15055. argument that specifies where to jump and an integer that represents
  15056. the arity of the function being called.
  15057. \section{Register Allocation}
  15058. \label{sec:register-allocation-r4}
  15059. The addition of functions requires some changes to all three aspects
  15060. of register allocation, which we discuss in the following subsections.
  15061. \subsection{Liveness Analysis}
  15062. \label{sec:liveness-analysis-r4}
  15063. \index{subject}{liveness analysis}
  15064. %% The rest of the passes need only minor modifications to handle the new
  15065. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  15066. %% \code{leaq}.
  15067. The \code{IndirectCallq} instruction should be treated like
  15068. \code{Callq} regarding its written locations $W$, in that they should
  15069. include all the caller-saved registers. Recall that the reason for
  15070. that is to force variables that are live across a function call to be assigned to callee-saved
  15071. registers or to be spilled to the stack.
  15072. Regarding the set of read locations $R$, the arity fields of
  15073. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  15074. argument-passing registers should be considered as read by those
  15075. instructions. Also, the target field of \code{TailJmp} and
  15076. \code{IndirectCallq} should be included in the set of read locations
  15077. $R$.
  15078. \subsection{Build Interference Graph}
  15079. \label{sec:build-interference-r4}
  15080. With the addition of function definitions, we compute a separate interference
  15081. graph for each function (not just one for the whole program).
  15082. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  15083. spill tuple-typed variables that are live during a call to
  15084. \code{collect}, the garbage collector. With the addition of functions
  15085. to our language, we need to revisit this issue. Functions that perform
  15086. allocation contain calls to the collector. Thus, we should not only
  15087. spill a tuple-typed variable when it is live during a call to
  15088. \code{collect}, but we should spill the variable if it is live during
  15089. a call to any user-defined function. Thus, in the
  15090. \code{build\_interference} pass, we recommend adding interference
  15091. edges between call-live tuple-typed variables and the callee-saved
  15092. registers (in addition to creating edges between
  15093. call-live variables and the caller-saved registers).
  15094. \subsection{Allocate Registers}
  15095. The primary change to the \code{allocate\_registers} pass is adding an
  15096. auxiliary function for handling definitions (the \Def{} nonterminal
  15097. shown in figure~\ref{fig:x86-3}) with one case for function
  15098. definitions. The logic is the same as described in
  15099. chapter~\ref{ch:register-allocation-Lvar} except that now register
  15100. allocation is performed many times, once for each function definition,
  15101. instead of just once for the whole program.
  15102. \section{Patch Instructions}
  15103. In \code{patch\_instructions}, you should deal with the x86
  15104. idiosyncrasy that the destination argument of \code{leaq} must be a
  15105. register. Additionally, you should ensure that the argument of
  15106. \code{TailJmp} is \itm{rax}, our reserved register---because we
  15107. trample many other registers before the tail call, as explained in the
  15108. next section.
  15109. \section{Generate Prelude and Conclusion}
  15110. Now that register allocation is complete, we can translate the
  15111. \code{TailJmp} into a sequence of instructions. A naive translation of
  15112. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15113. before the jump we need to pop the current frame to achieve efficient
  15114. tail calls. This sequence of instructions is the same as the code for
  15115. the conclusion of a function, except that the \code{retq} is replaced with
  15116. \code{jmp *$\itm{arg}$}.
  15117. Regarding function definitions, we generate a prelude and conclusion
  15118. for each one. This code is similar to the prelude and conclusion
  15119. generated for the \code{main} function presented in
  15120. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15121. carry out the following steps:
  15122. % TODO: .align the functions!
  15123. \begin{enumerate}
  15124. %% \item Start with \code{.global} and \code{.align} directives followed
  15125. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15126. %% example.)
  15127. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15128. pointer.
  15129. \item Push to the stack all the callee-saved registers that were
  15130. used for register allocation.
  15131. \item Move the stack pointer \code{rsp} down to make room for the
  15132. regular spills (aligned to 16 bytes).
  15133. \item Move the root stack pointer \code{r15} up by the size of the
  15134. root-stack frame for this function, which depends on the number of
  15135. spilled tuple-typed variables. \label{root-stack-init}
  15136. \item Initialize to zero all new entries in the root-stack frame.
  15137. \item Jump to the start block.
  15138. \end{enumerate}
  15139. The prelude of the \code{main} function has an additional task: call
  15140. the \code{initialize} function to set up the garbage collector, and
  15141. then move the value of the global \code{rootstack\_begin} in
  15142. \code{r15}. This initialization should happen before step
  15143. \ref{root-stack-init}, which depends on \code{r15}.
  15144. The conclusion of every function should do the following:
  15145. \begin{enumerate}
  15146. \item Move the stack pointer back up past the regular spills.
  15147. \item Restore the callee-saved registers by popping them from the
  15148. stack.
  15149. \item Move the root stack pointer back down by the size of the
  15150. root-stack frame for this function.
  15151. \item Restore \code{rbp} by popping it from the stack.
  15152. \item Return to the caller with the \code{retq} instruction.
  15153. \end{enumerate}
  15154. The output of this pass is \LangXIndCallFlat{}, which differs from
  15155. \LangXIndCall{} in that there is no longer an AST node for function
  15156. definitions. Instead, a program is just
  15157. \racket{an association list}\python{a dictionary}
  15158. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15159. {\if\edition\racketEd
  15160. \[
  15161. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15162. \]
  15163. \fi}
  15164. {\if\edition\pythonEd
  15165. \[
  15166. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15167. \]
  15168. \fi}
  15169. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15170. compiling \LangFun{} to x86.
  15171. \begin{exercise}\normalfont\normalsize
  15172. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15173. Create eight new programs that use functions including examples that
  15174. pass functions and return functions from other functions, recursive
  15175. functions, functions that create tuples, and functions that make tail
  15176. calls. Test your compiler on these new programs and all your
  15177. previously created test programs.
  15178. \end{exercise}
  15179. \begin{figure}[tbp]
  15180. \begin{tcolorbox}[colback=white]
  15181. {\if\edition\racketEd
  15182. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15183. \node (Lfun) at (0,2) {\large \LangFun{}};
  15184. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15185. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15186. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15187. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15188. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15189. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15190. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15191. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15192. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15193. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15194. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15195. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15196. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15197. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15198. \path[->,bend left=15] (Lfun) edge [above] node
  15199. {\ttfamily\footnotesize shrink} (Lfun-1);
  15200. \path[->,bend left=15] (Lfun-1) edge [above] node
  15201. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15202. \path[->,bend left=15] (Lfun-2) edge [above] node
  15203. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15204. \path[->,bend left=15] (F1-1) edge [left] node
  15205. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15206. \path[->,bend left=15] (F1-2) edge [below] node
  15207. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15208. \path[->,bend left=15] (F1-3) edge [below] node
  15209. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15210. \path[->,bend right=15] (F1-4) edge [above] node
  15211. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15212. \path[->,bend right=15] (F1-5) edge [right] node
  15213. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15214. \path[->,bend right=15] (C3-2) edge [right] node
  15215. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15216. \path[->,bend left=15] (x86-2) edge [right] node
  15217. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15218. \path[->,bend right=15] (x86-2-1) edge [below] node
  15219. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15220. \path[->,bend right=15] (x86-2-2) edge [right] node
  15221. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15222. \path[->,bend left=15] (x86-3) edge [above] node
  15223. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15224. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15225. \end{tikzpicture}
  15226. \fi}
  15227. {\if\edition\pythonEd\pythonColor
  15228. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15229. \node (Lfun) at (0,2) {\large \LangFun{}};
  15230. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15231. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15232. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15233. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15234. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15235. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15236. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15237. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15238. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15239. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15240. \path[->,bend left=15] (Lfun) edge [above] node
  15241. {\ttfamily\footnotesize shrink} (Lfun-2);
  15242. \path[->,bend left=15] (Lfun-2) edge [above] node
  15243. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15244. \path[->,bend left=15] (F1-1) edge [above] node
  15245. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15246. \path[->,bend left=15] (F1-2) edge [right] node
  15247. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15248. \path[->,bend right=15] (F1-4) edge [above] node
  15249. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15250. \path[->,bend right=15] (F1-5) edge [right] node
  15251. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15252. \path[->,bend left=15] (C3-2) edge [right] node
  15253. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15254. \path[->,bend right=15] (x86-2) edge [below] node
  15255. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15256. \path[->,bend left=15] (x86-3) edge [above] node
  15257. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15258. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15259. \end{tikzpicture}
  15260. \fi}
  15261. \end{tcolorbox}
  15262. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15263. \label{fig:Lfun-passes}
  15264. \end{figure}
  15265. \section{An Example Translation}
  15266. \label{sec:functions-example}
  15267. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15268. function in \LangFun{} to x86. The figure includes the results of
  15269. \code{explicate\_control} and \code{select\_instructions}.
  15270. \begin{figure}[hbtp]
  15271. \begin{tcolorbox}[colback=white]
  15272. \begin{tabular}{ll}
  15273. \begin{minipage}{0.4\textwidth}
  15274. % s3_2.rkt
  15275. {\if\edition\racketEd
  15276. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15277. (define (add [x : Integer]
  15278. [y : Integer])
  15279. : Integer
  15280. (+ x y))
  15281. (add 40 2)
  15282. \end{lstlisting}
  15283. \fi}
  15284. {\if\edition\pythonEd\pythonColor
  15285. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15286. def add(x:int, y:int) -> int:
  15287. return x + y
  15288. print(add(40, 2))
  15289. \end{lstlisting}
  15290. \fi}
  15291. $\Downarrow$
  15292. {\if\edition\racketEd
  15293. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15294. (define (add86 [x87 : Integer]
  15295. [y88 : Integer])
  15296. : Integer
  15297. add86start:
  15298. return (+ x87 y88);
  15299. )
  15300. (define (main) : Integer ()
  15301. mainstart:
  15302. tmp89 = (fun-ref add86 2);
  15303. (tail-call tmp89 40 2)
  15304. )
  15305. \end{lstlisting}
  15306. \fi}
  15307. {\if\edition\pythonEd\pythonColor
  15308. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15309. def add(x:int, y:int) -> int:
  15310. addstart:
  15311. return x + y
  15312. def main() -> int:
  15313. mainstart:
  15314. fun.0 = add
  15315. tmp.1 = fun.0(40, 2)
  15316. print(tmp.1)
  15317. return 0
  15318. \end{lstlisting}
  15319. \fi}
  15320. \end{minipage}
  15321. &
  15322. $\Rightarrow$
  15323. \begin{minipage}{0.5\textwidth}
  15324. {\if\edition\racketEd
  15325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15326. (define (add86) : Integer
  15327. add86start:
  15328. movq %rdi, x87
  15329. movq %rsi, y88
  15330. movq x87, %rax
  15331. addq y88, %rax
  15332. jmp inc1389conclusion
  15333. )
  15334. (define (main) : Integer
  15335. mainstart:
  15336. leaq (fun-ref add86 2), tmp89
  15337. movq $40, %rdi
  15338. movq $2, %rsi
  15339. tail-jmp tmp89
  15340. )
  15341. \end{lstlisting}
  15342. \fi}
  15343. {\if\edition\pythonEd\pythonColor
  15344. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15345. def add() -> int:
  15346. addstart:
  15347. movq %rdi, x
  15348. movq %rsi, y
  15349. movq x, %rax
  15350. addq y, %rax
  15351. jmp addconclusion
  15352. def main() -> int:
  15353. mainstart:
  15354. leaq add, fun.0
  15355. movq $40, %rdi
  15356. movq $2, %rsi
  15357. callq *fun.0
  15358. movq %rax, tmp.1
  15359. movq tmp.1, %rdi
  15360. callq print_int
  15361. movq $0, %rax
  15362. jmp mainconclusion
  15363. \end{lstlisting}
  15364. \fi}
  15365. $\Downarrow$
  15366. \end{minipage}
  15367. \end{tabular}
  15368. \begin{tabular}{ll}
  15369. \begin{minipage}{0.3\textwidth}
  15370. {\if\edition\racketEd
  15371. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15372. .globl add86
  15373. .align 8
  15374. add86:
  15375. pushq %rbp
  15376. movq %rsp, %rbp
  15377. jmp add86start
  15378. add86start:
  15379. movq %rdi, %rax
  15380. addq %rsi, %rax
  15381. jmp add86conclusion
  15382. add86conclusion:
  15383. popq %rbp
  15384. retq
  15385. \end{lstlisting}
  15386. \fi}
  15387. {\if\edition\pythonEd\pythonColor
  15388. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15389. .align 8
  15390. add:
  15391. pushq %rbp
  15392. movq %rsp, %rbp
  15393. subq $0, %rsp
  15394. jmp addstart
  15395. addstart:
  15396. movq %rdi, %rdx
  15397. movq %rsi, %rcx
  15398. movq %rdx, %rax
  15399. addq %rcx, %rax
  15400. jmp addconclusion
  15401. addconclusion:
  15402. subq $0, %r15
  15403. addq $0, %rsp
  15404. popq %rbp
  15405. retq
  15406. \end{lstlisting}
  15407. \fi}
  15408. \end{minipage}
  15409. &
  15410. \begin{minipage}{0.5\textwidth}
  15411. {\if\edition\racketEd
  15412. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15413. .globl main
  15414. .align 8
  15415. main:
  15416. pushq %rbp
  15417. movq %rsp, %rbp
  15418. movq $16384, %rdi
  15419. movq $16384, %rsi
  15420. callq initialize
  15421. movq rootstack_begin(%rip), %r15
  15422. jmp mainstart
  15423. mainstart:
  15424. leaq add86(%rip), %rcx
  15425. movq $40, %rdi
  15426. movq $2, %rsi
  15427. movq %rcx, %rax
  15428. popq %rbp
  15429. jmp *%rax
  15430. mainconclusion:
  15431. popq %rbp
  15432. retq
  15433. \end{lstlisting}
  15434. \fi}
  15435. {\if\edition\pythonEd\pythonColor
  15436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15437. .globl main
  15438. .align 8
  15439. main:
  15440. pushq %rbp
  15441. movq %rsp, %rbp
  15442. subq $0, %rsp
  15443. movq $65536, %rdi
  15444. movq $65536, %rsi
  15445. callq initialize
  15446. movq rootstack_begin(%rip), %r15
  15447. jmp mainstart
  15448. mainstart:
  15449. leaq add(%rip), %rcx
  15450. movq $40, %rdi
  15451. movq $2, %rsi
  15452. callq *%rcx
  15453. movq %rax, %rcx
  15454. movq %rcx, %rdi
  15455. callq print_int
  15456. movq $0, %rax
  15457. jmp mainconclusion
  15458. mainconclusion:
  15459. subq $0, %r15
  15460. addq $0, %rsp
  15461. popq %rbp
  15462. retq
  15463. \end{lstlisting}
  15464. \fi}
  15465. \end{minipage}
  15466. \end{tabular}
  15467. \end{tcolorbox}
  15468. \caption{Example compilation of a simple function to x86.}
  15469. \label{fig:add-fun}
  15470. \end{figure}
  15471. % Challenge idea: inlining! (simple version)
  15472. % Further Reading
  15473. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15474. \chapter{Lexically Scoped Functions}
  15475. \label{ch:Llambda}
  15476. \setcounter{footnote}{0}
  15477. This chapter studies lexically scoped functions. Lexical
  15478. scoping\index{subject}{lexical scoping} means that a function's body
  15479. may refer to variables whose binding site is outside of the function,
  15480. in an enclosing scope.
  15481. %
  15482. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15483. in \LangLam{}, which extends \LangFun{} with the
  15484. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15485. functions. The body of the \key{lambda} refers to three variables:
  15486. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15487. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15488. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15489. function \code{f}}, and \code{x} is a parameter of function
  15490. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15491. result value. The main expression of the program includes two calls to
  15492. \code{f} with different arguments for \code{x}: first \code{5} and
  15493. then \code{3}. The functions returned from \code{f} are bound to
  15494. variables \code{g} and \code{h}. Even though these two functions were
  15495. created by the same \code{lambda}, they are really different functions
  15496. because they use different values for \code{x}. Applying \code{g} to
  15497. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15498. produces \code{22}, so the result of the program is \code{42}.
  15499. \begin{figure}[btp]
  15500. \begin{tcolorbox}[colback=white]
  15501. {\if\edition\racketEd
  15502. % lambda_test_21.rkt
  15503. \begin{lstlisting}
  15504. (define (f [x : Integer]) : (Integer -> Integer)
  15505. (let ([y 4])
  15506. (lambda: ([z : Integer]) : Integer
  15507. (+ x (+ y z)))))
  15508. (let ([g (f 5)])
  15509. (let ([h (f 3)])
  15510. (+ (g 11) (h 15))))
  15511. \end{lstlisting}
  15512. \fi}
  15513. {\if\edition\pythonEd\pythonColor
  15514. \begin{lstlisting}
  15515. def f(x : int) -> Callable[[int], int]:
  15516. y = 4
  15517. return lambda z: x + y + z
  15518. g = f(5)
  15519. h = f(3)
  15520. print(g(11) + h(15))
  15521. \end{lstlisting}
  15522. \fi}
  15523. \end{tcolorbox}
  15524. \caption{Example of a lexically scoped function.}
  15525. \label{fig:lexical-scoping}
  15526. \end{figure}
  15527. The approach that we take for implementing lexically scoped functions
  15528. is to compile them into top-level function definitions, translating
  15529. from \LangLam{} into \LangFun{}. However, the compiler must give
  15530. special treatment to variable occurrences such as \code{x} and
  15531. \code{y} in the body of the \code{lambda} shown in
  15532. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15533. may not refer to variables defined outside of it. To identify such
  15534. variable occurrences, we review the standard notion of free variable.
  15535. \begin{definition}\normalfont
  15536. A variable is \emph{free in expression} $e$ if the variable occurs
  15537. inside $e$ but does not have an enclosing definition that is also in
  15538. $e$.\index{subject}{free variable}
  15539. \end{definition}
  15540. For example, in the expression
  15541. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15542. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15543. only \code{x} and \code{y} are free in the following expression,
  15544. because \code{z} is defined by the \code{lambda}
  15545. {\if\edition\racketEd
  15546. \begin{lstlisting}
  15547. (lambda: ([z : Integer]) : Integer
  15548. (+ x (+ y z)))
  15549. \end{lstlisting}
  15550. \fi}
  15551. {\if\edition\pythonEd\pythonColor
  15552. \begin{lstlisting}
  15553. lambda z: x + y + z
  15554. \end{lstlisting}
  15555. \fi}
  15556. %
  15557. \noindent Thus the free variables of a \code{lambda} are the ones that
  15558. need special treatment. We need to transport at runtime the values
  15559. of those variables from the point where the \code{lambda} was created
  15560. to the point where the \code{lambda} is applied. An efficient solution
  15561. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15562. values of the free variables together with a function pointer into a
  15563. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15564. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15565. closure}
  15566. %
  15567. By design, we have all the ingredients to make closures:
  15568. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15569. function pointers. The function pointer resides at index $0$, and the
  15570. values for the free variables fill in the rest of the tuple.
  15571. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15572. to see how closures work. It is a three-step dance. The program calls
  15573. function \code{f}, which creates a closure for the \code{lambda}. The
  15574. closure is a tuple whose first element is a pointer to the top-level
  15575. function that we will generate for the \code{lambda}; the second
  15576. element is the value of \code{x}, which is \code{5}; and the third
  15577. element is \code{4}, the value of \code{y}. The closure does not
  15578. contain an element for \code{z} because \code{z} is not a free
  15579. variable of the \code{lambda}. Creating the closure is step 1 of the
  15580. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15581. shown in figure~\ref{fig:closures}.
  15582. %
  15583. The second call to \code{f} creates another closure, this time with
  15584. \code{3} in the second slot (for \code{x}). This closure is also
  15585. returned from \code{f} but bound to \code{h}, which is also shown in
  15586. figure~\ref{fig:closures}.
  15587. \begin{figure}[tbp]
  15588. \centering
  15589. \begin{minipage}{0.65\textwidth}
  15590. \begin{tcolorbox}[colback=white]
  15591. \includegraphics[width=\textwidth]{figs/closures}
  15592. \end{tcolorbox}
  15593. \end{minipage}
  15594. \caption{Flat closure representations for the two functions
  15595. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15596. \label{fig:closures}
  15597. \end{figure}
  15598. Continuing with the example, consider the application of \code{g} to
  15599. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15600. closure, we obtain the function pointer from the first element of the
  15601. closure and call it, passing in the closure itself and then the
  15602. regular arguments, in this case \code{11}. This technique for applying
  15603. a closure is step 2 of the dance.
  15604. %
  15605. But doesn't this \code{lambda} take only one argument, for parameter
  15606. \code{z}? The third and final step of the dance is generating a
  15607. top-level function for a \code{lambda}. We add an additional
  15608. parameter for the closure and insert an initialization at the beginning
  15609. of the function for each free variable, to bind those variables to the
  15610. appropriate elements from the closure parameter.
  15611. %
  15612. This three-step dance is known as \emph{closure
  15613. conversion}\index{subject}{closure conversion}. We discuss the
  15614. details of closure conversion in section~\ref{sec:closure-conversion}
  15615. and show the code generated from the example in
  15616. section~\ref{sec:example-lambda}. First, we define the syntax and
  15617. semantics of \LangLam{} in section~\ref{sec:r5}.
  15618. \section{The \LangLam{} Language}
  15619. \label{sec:r5}
  15620. The definitions of the concrete syntax and abstract syntax for
  15621. \LangLam{}, a language with anonymous functions and lexical scoping,
  15622. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15623. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15624. for \LangFun{}, which already has syntax for function application.
  15625. %
  15626. \python{The syntax also includes an assignment statement that includes
  15627. a type annotation for the variable on the left-hand side, which
  15628. facilitates the type checking of \code{lambda} expressions that we
  15629. discuss later in this section.}
  15630. %
  15631. \racket{The \code{procedure-arity} operation returns the number of parameters
  15632. of a given function, an operation that we need for the translation
  15633. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15634. %
  15635. \python{The \code{arity} operation returns the number of parameters of
  15636. a given function, an operation that we need for the translation
  15637. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15638. The \code{arity} operation is not in Python, but the same functionality
  15639. is available in a more complex form. We include \code{arity} in the
  15640. \LangLam{} source language to enable testing.}
  15641. \newcommand{\LlambdaGrammarRacket}{
  15642. \begin{array}{lcl}
  15643. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15644. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15645. \end{array}
  15646. }
  15647. \newcommand{\LlambdaASTRacket}{
  15648. \begin{array}{lcl}
  15649. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15650. \itm{op} &::=& \code{procedure-arity}
  15651. \end{array}
  15652. }
  15653. \newcommand{\LlambdaGrammarPython}{
  15654. \begin{array}{lcl}
  15655. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15656. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15657. \end{array}
  15658. }
  15659. \newcommand{\LlambdaASTPython}{
  15660. \begin{array}{lcl}
  15661. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15662. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15663. \end{array}
  15664. }
  15665. % include AnnAssign in ASTPython
  15666. \begin{figure}[tp]
  15667. \centering
  15668. \begin{tcolorbox}[colback=white]
  15669. \small
  15670. {\if\edition\racketEd
  15671. \[
  15672. \begin{array}{l}
  15673. \gray{\LintGrammarRacket{}} \\ \hline
  15674. \gray{\LvarGrammarRacket{}} \\ \hline
  15675. \gray{\LifGrammarRacket{}} \\ \hline
  15676. \gray{\LwhileGrammarRacket} \\ \hline
  15677. \gray{\LtupGrammarRacket} \\ \hline
  15678. \gray{\LfunGrammarRacket} \\ \hline
  15679. \LlambdaGrammarRacket \\
  15680. \begin{array}{lcl}
  15681. \LangLamM{} &::=& \Def\ldots \; \Exp
  15682. \end{array}
  15683. \end{array}
  15684. \]
  15685. \fi}
  15686. {\if\edition\pythonEd\pythonColor
  15687. \[
  15688. \begin{array}{l}
  15689. \gray{\LintGrammarPython{}} \\ \hline
  15690. \gray{\LvarGrammarPython{}} \\ \hline
  15691. \gray{\LifGrammarPython{}} \\ \hline
  15692. \gray{\LwhileGrammarPython} \\ \hline
  15693. \gray{\LtupGrammarPython} \\ \hline
  15694. \gray{\LfunGrammarPython} \\ \hline
  15695. \LlambdaGrammarPython \\
  15696. \begin{array}{lcl}
  15697. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15698. \end{array}
  15699. \end{array}
  15700. \]
  15701. \fi}
  15702. \end{tcolorbox}
  15703. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15704. with \key{lambda}.}
  15705. \label{fig:Llam-concrete-syntax}
  15706. \index{subject}{Llambda@\LangLam{} concrete syntax}
  15707. \end{figure}
  15708. \begin{figure}[tp]
  15709. \centering
  15710. \begin{tcolorbox}[colback=white]
  15711. \small
  15712. {\if\edition\racketEd
  15713. \[\arraycolsep=3pt
  15714. \begin{array}{l}
  15715. \gray{\LintOpAST} \\ \hline
  15716. \gray{\LvarASTRacket{}} \\ \hline
  15717. \gray{\LifASTRacket{}} \\ \hline
  15718. \gray{\LwhileASTRacket{}} \\ \hline
  15719. \gray{\LtupASTRacket{}} \\ \hline
  15720. \gray{\LfunASTRacket} \\ \hline
  15721. \LlambdaASTRacket \\
  15722. \begin{array}{lcl}
  15723. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15724. \end{array}
  15725. \end{array}
  15726. \]
  15727. \fi}
  15728. {\if\edition\pythonEd\pythonColor
  15729. \[
  15730. \begin{array}{l}
  15731. \gray{\LintASTPython} \\ \hline
  15732. \gray{\LvarASTPython{}} \\ \hline
  15733. \gray{\LifASTPython{}} \\ \hline
  15734. \gray{\LwhileASTPython{}} \\ \hline
  15735. \gray{\LtupASTPython{}} \\ \hline
  15736. \gray{\LfunASTPython} \\ \hline
  15737. \LlambdaASTPython \\
  15738. \begin{array}{lcl}
  15739. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15740. \end{array}
  15741. \end{array}
  15742. \]
  15743. \fi}
  15744. \end{tcolorbox}
  15745. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15746. \label{fig:Llam-syntax}
  15747. \index{subject}{Llambda@\LangLam{} abstract syntax}
  15748. \end{figure}
  15749. Figure~\ref{fig:interp-Llambda} shows the definitional
  15750. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15751. \key{Lambda} saves the current environment inside the returned
  15752. function value. Recall that during function application, the
  15753. environment stored in the function value, extended with the mapping of
  15754. parameters to argument values, is used to interpret the body of the
  15755. function.
  15756. \begin{figure}[tbp]
  15757. \begin{tcolorbox}[colback=white]
  15758. {\if\edition\racketEd
  15759. \begin{lstlisting}
  15760. (define interp-Llambda-class
  15761. (class interp-Lfun-class
  15762. (super-new)
  15763. (define/override (interp-op op)
  15764. (match op
  15765. ['procedure-arity
  15766. (lambda (v)
  15767. (match v
  15768. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15769. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15770. [else (super interp-op op)]))
  15771. (define/override ((interp-exp env) e)
  15772. (define recur (interp-exp env))
  15773. (match e
  15774. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15775. `(function ,xs ,body ,env)]
  15776. [else ((super interp-exp env) e)]))
  15777. ))
  15778. (define (interp-Llambda p)
  15779. (send (new interp-Llambda-class) interp-program p))
  15780. \end{lstlisting}
  15781. \fi}
  15782. {\if\edition\pythonEd\pythonColor
  15783. \begin{lstlisting}
  15784. class InterpLlambda(InterpLfun):
  15785. def arity(self, v):
  15786. match v:
  15787. case Function(name, params, body, env):
  15788. return len(params)
  15789. case _:
  15790. raise Exception('Llambda arity unexpected ' + repr(v))
  15791. def interp_exp(self, e, env):
  15792. match e:
  15793. case Call(Name('arity'), [fun]):
  15794. f = self.interp_exp(fun, env)
  15795. return self.arity(f)
  15796. case Lambda(params, body):
  15797. return Function('lambda', params, [Return(body)], env)
  15798. case _:
  15799. return super().interp_exp(e, env)
  15800. def interp_stmt(self, s, env, cont):
  15801. match s:
  15802. case AnnAssign(lhs, typ, value, simple):
  15803. env[lhs.id] = self.interp_exp(value, env)
  15804. return self.interp_stmts(cont, env)
  15805. case Pass():
  15806. return self.interp_stmts(cont, env)
  15807. case _:
  15808. return super().interp_stmt(s, env, cont)
  15809. \end{lstlisting}
  15810. \fi}
  15811. \end{tcolorbox}
  15812. \caption{Interpreter for \LangLam{}.}
  15813. \label{fig:interp-Llambda}
  15814. \end{figure}
  15815. {\if\edition\racketEd
  15816. %
  15817. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15818. \key{lambda} form. The body of the \key{lambda} is checked in an
  15819. environment that includes the current environment (because it is
  15820. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15821. require the body's type to match the declared return type.
  15822. %
  15823. \fi}
  15824. {\if\edition\pythonEd\pythonColor
  15825. %
  15826. Figures~\ref{fig:type-check-Llambda} and
  15827. \ref{fig:type-check-Llambda-part2} define the type checker for
  15828. \LangLam{}, which is more complex than one might expect. The reason
  15829. for the added complexity is that the syntax of \key{lambda} does not
  15830. include type annotations for the parameters or return type. Instead
  15831. they must be inferred. There are many approaches to type inference
  15832. from which to choose, of varying degrees of complexity. We choose one
  15833. of the simpler approaches, bidirectional type
  15834. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15835. book is compilation, not type inference.
  15836. The main idea of bidirectional type inference is to add an auxiliary
  15837. function, here named \code{check\_exp}, that takes an expected type
  15838. and checks whether the given expression is of that type. Thus, in
  15839. \code{check\_exp}, type information flows in a top-down manner with
  15840. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15841. function, where type information flows in a primarily bottom-up
  15842. manner.
  15843. %
  15844. The idea then is to use \code{check\_exp} in all the places where we
  15845. already know what the type of an expression should be, such as in the
  15846. \code{return} statement of a top-level function definition or on the
  15847. right-hand side of an annotated assignment statement.
  15848. With regard to \code{lambda}, it is straightforward to check a
  15849. \code{lambda} inside \code{check\_exp} because the expected type
  15850. provides the parameter types and the return type. On the other hand,
  15851. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15852. that we do not allow \code{lambda} in contexts in which we don't already
  15853. know its type. This restriction does not incur a loss of
  15854. expressiveness for \LangLam{} because it is straightforward to modify
  15855. a program to sidestep the restriction, for example, by using an
  15856. annotated assignment statement to assign the \code{lambda} to a
  15857. temporary variable.
  15858. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15859. checker records their type in a \code{has\_type} field. This type
  15860. information is used further on in this chapter.
  15861. %
  15862. \fi}
  15863. \begin{figure}[tbp]
  15864. \begin{tcolorbox}[colback=white]
  15865. {\if\edition\racketEd
  15866. \begin{lstlisting}
  15867. (define (type-check-Llambda env)
  15868. (lambda (e)
  15869. (match e
  15870. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15871. (define-values (new-body bodyT)
  15872. ((type-check-exp (append (map cons xs Ts) env)) body))
  15873. (define ty `(,@Ts -> ,rT))
  15874. (cond
  15875. [(equal? rT bodyT)
  15876. (values (HasType (Lambda params rT new-body) ty) ty)]
  15877. [else
  15878. (error "mismatch in return type" bodyT rT)])]
  15879. ...
  15880. )))
  15881. \end{lstlisting}
  15882. \fi}
  15883. {\if\edition\pythonEd\pythonColor
  15884. \begin{lstlisting}
  15885. class TypeCheckLlambda(TypeCheckLfun):
  15886. def type_check_exp(self, e, env):
  15887. match e:
  15888. case Name(id):
  15889. e.has_type = env[id]
  15890. return env[id]
  15891. case Lambda(params, body):
  15892. raise Exception('cannot synthesize a type for a lambda')
  15893. case Call(Name('arity'), [func]):
  15894. func_t = self.type_check_exp(func, env)
  15895. match func_t:
  15896. case FunctionType(params_t, return_t):
  15897. return IntType()
  15898. case _:
  15899. raise Exception('in arity, unexpected ' + repr(func_t))
  15900. case _:
  15901. return super().type_check_exp(e, env)
  15902. def check_exp(self, e, ty, env):
  15903. match e:
  15904. case Lambda(params, body):
  15905. e.has_type = ty
  15906. match ty:
  15907. case FunctionType(params_t, return_t):
  15908. new_env = env.copy().update(zip(params, params_t))
  15909. self.check_exp(body, return_t, new_env)
  15910. case _:
  15911. raise Exception('lambda does not have type ' + str(ty))
  15912. case Call(func, args):
  15913. func_t = self.type_check_exp(func, env)
  15914. match func_t:
  15915. case FunctionType(params_t, return_t):
  15916. for (arg, param_t) in zip(args, params_t):
  15917. self.check_exp(arg, param_t, env)
  15918. self.check_type_equal(return_t, ty, e)
  15919. case _:
  15920. raise Exception('type_check_exp: in call, unexpected ' + \
  15921. repr(func_t))
  15922. case _:
  15923. t = self.type_check_exp(e, env)
  15924. self.check_type_equal(t, ty, e)
  15925. \end{lstlisting}
  15926. \fi}
  15927. \end{tcolorbox}
  15928. \caption{Type checking \LangLam{}\python{, part 1}.}
  15929. \label{fig:type-check-Llambda}
  15930. \end{figure}
  15931. {\if\edition\pythonEd\pythonColor
  15932. \begin{figure}[tbp]
  15933. \begin{tcolorbox}[colback=white]
  15934. \begin{lstlisting}
  15935. def check_stmts(self, ss, return_ty, env):
  15936. if len(ss) == 0:
  15937. return
  15938. match ss[0]:
  15939. case FunctionDef(name, params, body, dl, returns, comment):
  15940. new_env = env.copy().update(params)
  15941. rt = self.check_stmts(body, returns, new_env)
  15942. self.check_stmts(ss[1:], return_ty, env)
  15943. case Return(value):
  15944. self.check_exp(value, return_ty, env)
  15945. case Assign([Name(id)], value):
  15946. if id in env:
  15947. self.check_exp(value, env[id], env)
  15948. else:
  15949. env[id] = self.type_check_exp(value, env)
  15950. self.check_stmts(ss[1:], return_ty, env)
  15951. case Assign([Subscript(tup, Constant(index), Store())], value):
  15952. tup_t = self.type_check_exp(tup, env)
  15953. match tup_t:
  15954. case TupleType(ts):
  15955. self.check_exp(value, ts[index], env)
  15956. case _:
  15957. raise Exception('expected a tuple, not ' + repr(tup_t))
  15958. self.check_stmts(ss[1:], return_ty, env)
  15959. case AnnAssign(Name(id), ty_annot, value, simple):
  15960. ss[0].annotation = ty_annot
  15961. if id in env:
  15962. self.check_type_equal(env[id], ty_annot)
  15963. else:
  15964. env[id] = ty_annot
  15965. self.check_exp(value, ty_annot, env)
  15966. self.check_stmts(ss[1:], return_ty, env)
  15967. case _:
  15968. self.type_check_stmts(ss, env)
  15969. def type_check(self, p):
  15970. match p:
  15971. case Module(body):
  15972. env = {}
  15973. for s in body:
  15974. match s:
  15975. case FunctionDef(name, params, bod, dl, returns, comment):
  15976. params_t = [t for (x,t) in params]
  15977. env[name] = FunctionType(params_t, returns)
  15978. self.check_stmts(body, int, env)
  15979. \end{lstlisting}
  15980. \end{tcolorbox}
  15981. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15982. \label{fig:type-check-Llambda-part2}
  15983. \end{figure}
  15984. \fi}
  15985. \clearpage
  15986. \section{Assignment and Lexically Scoped Functions}
  15987. \label{sec:assignment-scoping}
  15988. The combination of lexically scoped functions and assignment to
  15989. variables raises a challenge with the flat-closure approach to
  15990. implementing lexically scoped functions. Consider the following
  15991. example in which function \code{f} has a free variable \code{x} that
  15992. is changed after \code{f} is created but before the call to \code{f}.
  15993. % loop_test_11.rkt
  15994. {\if\edition\racketEd
  15995. \begin{lstlisting}
  15996. (let ([x 0])
  15997. (let ([y 0])
  15998. (let ([z 20])
  15999. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16000. (begin
  16001. (set! x 10)
  16002. (set! y 12)
  16003. (f y))))))
  16004. \end{lstlisting}
  16005. \fi}
  16006. {\if\edition\pythonEd\pythonColor
  16007. % box_free_assign.py
  16008. \begin{lstlisting}
  16009. def g(z : int) -> int:
  16010. x = 0
  16011. y = 0
  16012. f : Callable[[int],int] = lambda a: a + x + z
  16013. x = 10
  16014. y = 12
  16015. return f(y)
  16016. print(g(20))
  16017. \end{lstlisting}
  16018. \fi} The correct output for this example is \code{42} because the call
  16019. to \code{f} is required to use the current value of \code{x} (which is
  16020. \code{10}). Unfortunately, the closure conversion pass
  16021. (section~\ref{sec:closure-conversion}) generates code for the
  16022. \code{lambda} that copies the old value of \code{x} into a
  16023. closure. Thus, if we naively applied closure conversion, the output of
  16024. this program would be \code{32}.
  16025. A first attempt at solving this problem would be to save a pointer to
  16026. \code{x} in the closure and change the occurrences of \code{x} inside
  16027. the lambda to dereference the pointer. Of course, this would require
  16028. assigning \code{x} to the stack and not to a register. However, the
  16029. problem goes a bit deeper.
  16030. Consider the following example that returns a function that refers to
  16031. a local variable of the enclosing function:
  16032. \begin{center}
  16033. \begin{minipage}{\textwidth}
  16034. {\if\edition\racketEd
  16035. \begin{lstlisting}
  16036. (define (f) : ( -> Integer)
  16037. (let ([x 0])
  16038. (let ([g (lambda: () : Integer x)])
  16039. (begin
  16040. (set! x 42)
  16041. g))))
  16042. ((f))
  16043. \end{lstlisting}
  16044. \fi}
  16045. {\if\edition\pythonEd\pythonColor
  16046. % counter.py
  16047. \begin{lstlisting}
  16048. def f():
  16049. x = 0
  16050. g = lambda: x
  16051. x = 42
  16052. return g
  16053. print(f()())
  16054. \end{lstlisting}
  16055. \fi}
  16056. \end{minipage}
  16057. \end{center}
  16058. In this example, the lifetime of \code{x} extends beyond the lifetime
  16059. of the call to \code{f}. Thus, if we were to store \code{x} on the
  16060. stack frame for the call to \code{f}, it would be gone by the time we
  16061. called \code{g}, leaving us with dangling pointers for
  16062. \code{x}. This example demonstrates that when a variable occurs free
  16063. inside a function, its lifetime becomes indefinite. Thus, the value of
  16064. the variable needs to live on the heap. The verb
  16065. \emph{box}\index{subject}{box} is often used for allocating a single
  16066. value on the heap, producing a pointer, and
  16067. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  16068. %
  16069. We introduce a new pass named \code{convert\_assignments} to address
  16070. this challenge.
  16071. %
  16072. \python{But before diving into that, we have one more
  16073. problem to discuss.}
  16074. {\if\edition\pythonEd\pythonColor
  16075. \section{Uniquify Variables}
  16076. \label{sec:uniquify-lambda}
  16077. With the addition of \code{lambda} we have a complication to deal
  16078. with: name shadowing. Consider the following program with a function
  16079. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  16080. \code{lambda} expressions. The first \code{lambda} has a parameter
  16081. that is also named \code{x}.
  16082. \begin{lstlisting}
  16083. def f(x:int, y:int) -> Callable[[int], int]:
  16084. g : Callable[[int],int] = (lambda x: x + y)
  16085. h : Callable[[int],int] = (lambda y: x + y)
  16086. x = input_int()
  16087. return g
  16088. print(f(0, 10)(32))
  16089. \end{lstlisting}
  16090. Many of our compiler passes rely on being able to connect variable
  16091. uses with their definitions using just the name of the
  16092. variable. However, in the example above, the name of the variable does
  16093. not uniquely determine its definition. To solve this problem we
  16094. recommend implementing a pass named \code{uniquify} that renames every
  16095. variable in the program to make sure that they are all unique.
  16096. The following shows the result of \code{uniquify} for the example
  16097. above. The \code{x} parameter of function \code{f} is renamed to
  16098. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  16099. renamed to \code{x\_4}.
  16100. \begin{lstlisting}
  16101. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  16102. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  16103. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  16104. x_0 = input_int()
  16105. return g_2
  16106. def main() -> int :
  16107. print(f(0, 10)(32))
  16108. return 0
  16109. \end{lstlisting}
  16110. \fi} % pythonEd
  16111. %% \section{Reveal Functions}
  16112. %% \label{sec:reveal-functions-r5}
  16113. %% \racket{To support the \code{procedure-arity} operator we need to
  16114. %% communicate the arity of a function to the point of closure
  16115. %% creation.}
  16116. %% %
  16117. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16118. %% function at runtime. Thus, we need to communicate the arity of a
  16119. %% function to the point of closure creation.}
  16120. %% %
  16121. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16122. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16123. %% \[
  16124. %% \begin{array}{lcl}
  16125. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16126. %% \end{array}
  16127. %% \]
  16128. \section{Assignment Conversion}
  16129. \label{sec:convert-assignments}
  16130. The purpose of the \code{convert\_assignments} pass is to address the
  16131. challenge regarding the interaction between variable assignments and
  16132. closure conversion. First we identify which variables need to be
  16133. boxed, and then we transform the program to box those variables. In
  16134. general, boxing introduces runtime overhead that we would like to
  16135. avoid, so we should box as few variables as possible. We recommend
  16136. boxing the variables in the intersection of the following two sets of
  16137. variables:
  16138. \begin{enumerate}
  16139. \item The variables that are free in a \code{lambda}.
  16140. \item The variables that appear on the left-hand side of an
  16141. assignment.
  16142. \end{enumerate}
  16143. The first condition is a must but the second condition is
  16144. conservative. It is possible to develop a more liberal condition using
  16145. static program analysis.
  16146. Consider again the first example from
  16147. section~\ref{sec:assignment-scoping}:
  16148. %
  16149. {\if\edition\racketEd
  16150. \begin{lstlisting}
  16151. (let ([x 0])
  16152. (let ([y 0])
  16153. (let ([z 20])
  16154. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16155. (begin
  16156. (set! x 10)
  16157. (set! y 12)
  16158. (f y))))))
  16159. \end{lstlisting}
  16160. \fi}
  16161. {\if\edition\pythonEd\pythonColor
  16162. \begin{lstlisting}
  16163. def g(z : int) -> int:
  16164. x = 0
  16165. y = 0
  16166. f : Callable[[int],int] = lambda a: a + x + z
  16167. x = 10
  16168. y = 12
  16169. return f(y)
  16170. print(g(20))
  16171. \end{lstlisting}
  16172. \fi}
  16173. %
  16174. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16175. side of assignments. The variables \code{x} and \code{z} occur free
  16176. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16177. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16178. three transformations: initialize \code{x} with a tuple whose element
  16179. is uninitialized, replace reads from \code{x} with tuple reads, and
  16180. replace each assignment to \code{x} with a tuple write. The output of
  16181. \code{convert\_assignments} for this example is as follows:
  16182. %
  16183. {\if\edition\racketEd
  16184. \begin{lstlisting}
  16185. (define (main) : Integer
  16186. (let ([x0 (vector 0)])
  16187. (let ([y1 0])
  16188. (let ([z2 20])
  16189. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16190. (+ a3 (+ (vector-ref x0 0) z2)))])
  16191. (begin
  16192. (vector-set! x0 0 10)
  16193. (set! y1 12)
  16194. (f4 y1)))))))
  16195. \end{lstlisting}
  16196. \fi}
  16197. %
  16198. {\if\edition\pythonEd\pythonColor
  16199. \begin{lstlisting}
  16200. def g(z : int)-> int:
  16201. x = (uninitialized(int),)
  16202. x[0] = 0
  16203. y = 0
  16204. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16205. x[0] = 10
  16206. y = 12
  16207. return f(y)
  16208. def main() -> int:
  16209. print(g(20))
  16210. return 0
  16211. \end{lstlisting}
  16212. \fi}
  16213. To compute the free variables of all the \code{lambda} expressions, we
  16214. recommend defining the following two auxiliary functions:
  16215. \begin{enumerate}
  16216. \item \code{free\_variables} computes the free variables of an expression, and
  16217. \item \code{free\_in\_lambda} collects all the variables that are
  16218. free in any of the \code{lambda} expressions, using
  16219. \code{free\_variables} in the case for each \code{lambda}.
  16220. \end{enumerate}
  16221. {\if\edition\racketEd
  16222. %
  16223. To compute the variables that are assigned to, we recommend updating
  16224. the \code{collect-set!} function that we introduced in
  16225. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16226. as \code{Lambda}.
  16227. %
  16228. \fi}
  16229. {\if\edition\pythonEd\pythonColor
  16230. %
  16231. To compute the variables that are assigned to, we recommend defining
  16232. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16233. the set of variables that occur in the left-hand side of an assignment
  16234. statement and otherwise returns the empty set.
  16235. %
  16236. \fi}
  16237. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16238. free in a \code{lambda} and that are assigned to in the enclosing
  16239. function definition.
  16240. Next we discuss the \code{convert\_assignments} pass. In the case for
  16241. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16242. $\VAR{x}$ to a tuple read.
  16243. %
  16244. {\if\edition\racketEd
  16245. \begin{lstlisting}
  16246. (Var |$x$|)
  16247. |$\Rightarrow$|
  16248. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16249. \end{lstlisting}
  16250. \fi}
  16251. %
  16252. {\if\edition\pythonEd\pythonColor
  16253. \begin{lstlisting}
  16254. Name(|$x$|)
  16255. |$\Rightarrow$|
  16256. Subscript(Name(|$x$|), Constant(0), Load())
  16257. \end{lstlisting}
  16258. \fi}
  16259. %
  16260. \noindent In the case for assignment, recursively process the
  16261. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16262. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16263. as follows:
  16264. %
  16265. {\if\edition\racketEd
  16266. \begin{lstlisting}
  16267. (SetBang |$x$| |$\itm{rhs}$|)
  16268. |$\Rightarrow$|
  16269. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16270. \end{lstlisting}
  16271. \fi}
  16272. {\if\edition\pythonEd\pythonColor
  16273. \begin{lstlisting}
  16274. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16275. |$\Rightarrow$|
  16276. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16277. \end{lstlisting}
  16278. \fi}
  16279. %
  16280. {\if\edition\racketEd
  16281. The case for \code{Lambda} is nontrivial, but it is similar to the
  16282. case for function definitions, which we discuss next.
  16283. \fi}
  16284. %
  16285. To translate a function definition, we first compute $\mathit{AF}$,
  16286. the intersection of the variables that are free in a \code{lambda} and
  16287. that are assigned to. We then apply assignment conversion to the body
  16288. of the function definition. Finally, we box the parameters of this
  16289. function definition that are in $\mathit{AF}$. For example,
  16290. the parameter \code{x} of the following function \code{g}
  16291. needs to be boxed:
  16292. {\if\edition\racketEd
  16293. \begin{lstlisting}
  16294. (define (g [x : Integer]) : Integer
  16295. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16296. (begin
  16297. (set! x 10)
  16298. (f 32))))
  16299. \end{lstlisting}
  16300. \fi}
  16301. %
  16302. {\if\edition\pythonEd\pythonColor
  16303. \begin{lstlisting}
  16304. def g(x : int) -> int:
  16305. f : Callable[[int],int] = lambda a: a + x
  16306. x = 10
  16307. return f(32)
  16308. \end{lstlisting}
  16309. \fi}
  16310. %
  16311. \noindent We box parameter \code{x} by creating a local variable named
  16312. \code{x} that is initialized to a tuple whose contents is the value of
  16313. the parameter, which is renamed to \code{x\_0}.
  16314. %
  16315. {\if\edition\racketEd
  16316. \begin{lstlisting}
  16317. (define (g [x_0 : Integer]) : Integer
  16318. (let ([x (vector x_0)])
  16319. (let ([f (lambda: ([a : Integer]) : Integer
  16320. (+ a (vector-ref x 0)))])
  16321. (begin
  16322. (vector-set! x 0 10)
  16323. (f 32)))))
  16324. \end{lstlisting}
  16325. \fi}
  16326. %
  16327. {\if\edition\pythonEd\pythonColor
  16328. \begin{lstlisting}
  16329. def g(x_0 : int)-> int:
  16330. x = (x_0,)
  16331. f : Callable[[int], int] = (lambda a: a + x[0])
  16332. x[0] = 10
  16333. return f(32)
  16334. \end{lstlisting}
  16335. \fi}
  16336. \section{Closure Conversion}
  16337. \label{sec:closure-conversion}
  16338. \index{subject}{closure conversion}
  16339. The compiling of lexically scoped functions into top-level function
  16340. definitions and flat closures is accomplished in the pass
  16341. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16342. and before \code{limit\_functions}.
  16343. As usual, we implement the pass as a recursive function over the
  16344. AST. The interesting cases are for \key{lambda} and function
  16345. application. We transform a \key{lambda} expression into an expression
  16346. that creates a closure, that is, a tuple for which the first element
  16347. is a function pointer and the rest of the elements are the values of
  16348. the free variables of the \key{lambda}.
  16349. %
  16350. However, we use the \code{Closure} AST node instead of using a tuple
  16351. so that we can record the arity.
  16352. %
  16353. In the generated code that follows, \itm{fvs} is the list of free
  16354. variables of the lambda and \itm{name} is a unique symbol generated to
  16355. identify the lambda.
  16356. %
  16357. \racket{The \itm{arity} is the number of parameters (the length of
  16358. \itm{ps}).}
  16359. %
  16360. {\if\edition\racketEd
  16361. \begin{lstlisting}
  16362. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16363. |$\Rightarrow$|
  16364. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16365. \end{lstlisting}
  16366. \fi}
  16367. %
  16368. {\if\edition\pythonEd\pythonColor
  16369. \begin{lstlisting}
  16370. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16371. |$\Rightarrow$|
  16372. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16373. \end{lstlisting}
  16374. \fi}
  16375. %
  16376. In addition to transforming each \key{Lambda} AST node into a
  16377. tuple, we create a top-level function definition for each
  16378. \key{Lambda}, as shown next.\\
  16379. \begin{minipage}{0.8\textwidth}
  16380. {\if\edition\racketEd
  16381. \begin{lstlisting}
  16382. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16383. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16384. ...
  16385. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16386. |\itm{body'}|)...))
  16387. \end{lstlisting}
  16388. \fi}
  16389. {\if\edition\pythonEd\pythonColor
  16390. \begin{lstlisting}
  16391. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16392. |$\itm{fvs}_1$| = clos[1]
  16393. |$\ldots$|
  16394. |$\itm{fvs}_m$| = clos[|$m$|]
  16395. |\itm{body'}|
  16396. \end{lstlisting}
  16397. \fi}
  16398. \end{minipage}\\
  16399. %
  16400. The \code{clos} parameter refers to the closure. The type
  16401. \itm{closTy} is a tuple type for which the first element type is
  16402. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16403. rest of the element types are the types of the free variables in the
  16404. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16405. is nontrivial to give a type to the function in the closure's
  16406. type.\footnote{To give an accurate type to a closure, we would need to
  16407. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16408. %
  16409. \racket{Translate the type
  16410. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16411. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16412. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16413. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16414. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16415. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16416. %% The dummy type is considered to be equal to any other type during type
  16417. %% checking.
  16418. The free variables become local variables that are initialized with
  16419. their values in the closure.
  16420. Closure conversion turns every function into a tuple, so the type
  16421. annotations in the program must also be translated. We recommend
  16422. defining an auxiliary recursive function for this purpose. Function
  16423. types should be translated as follows:
  16424. %
  16425. {\if\edition\racketEd
  16426. \begin{lstlisting}
  16427. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16428. |$\Rightarrow$|
  16429. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16430. \end{lstlisting}
  16431. \fi}
  16432. {\if\edition\pythonEd\pythonColor
  16433. \begin{lstlisting}
  16434. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16435. |$\Rightarrow$|
  16436. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16437. \end{lstlisting}
  16438. \fi}
  16439. %
  16440. This type indicates that the first thing in the tuple is a
  16441. function. The first parameter of the function is a tuple (a closure)
  16442. and the rest of the parameters are the ones from the original
  16443. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16444. omits the types of the free variables because (1) those types are not
  16445. available in this context, and (2) we do not need them in the code that
  16446. is generated for function application. So this type describes only the
  16447. first component of the closure tuple. At runtime the tuple may have
  16448. more components, but we ignore them at this point.
  16449. We transform function application into code that retrieves the
  16450. function from the closure and then calls the function, passing the
  16451. closure as the first argument. We place $e'$ in a temporary variable
  16452. to avoid code duplication.
  16453. \begin{center}
  16454. \begin{minipage}{\textwidth}
  16455. {\if\edition\racketEd
  16456. \begin{lstlisting}
  16457. (Apply |$e$| |$\itm{es}$|)
  16458. |$\Rightarrow$|
  16459. (Let |$\itm{tmp}$| |$e'$|
  16460. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16461. \end{lstlisting}
  16462. \fi}
  16463. %
  16464. {\if\edition\pythonEd\pythonColor
  16465. \begin{lstlisting}
  16466. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16467. |$\Rightarrow$|
  16468. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16469. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16470. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16471. \end{lstlisting}
  16472. \fi}
  16473. \end{minipage}
  16474. \end{center}
  16475. There is also the question of what to do with references to top-level
  16476. function definitions. To maintain a uniform translation of function
  16477. application, we turn function references into closures.
  16478. \begin{tabular}{lll}
  16479. \begin{minipage}{0.2\textwidth}
  16480. {\if\edition\racketEd
  16481. \begin{lstlisting}
  16482. (FunRef |$f$| |$n$|)
  16483. \end{lstlisting}
  16484. \fi}
  16485. {\if\edition\pythonEd\pythonColor
  16486. \begin{lstlisting}
  16487. FunRef(|$f$|, |$n$|)
  16488. \end{lstlisting}
  16489. \fi}
  16490. \end{minipage}
  16491. &
  16492. $\Rightarrow\qquad$
  16493. &
  16494. \begin{minipage}{0.5\textwidth}
  16495. {\if\edition\racketEd
  16496. \begin{lstlisting}
  16497. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16498. \end{lstlisting}
  16499. \fi}
  16500. {\if\edition\pythonEd\pythonColor
  16501. \begin{lstlisting}
  16502. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16503. \end{lstlisting}
  16504. \fi}
  16505. \end{minipage}
  16506. \end{tabular} \\
  16507. We no longer need the annotated assignment statement \code{AnnAssign}
  16508. to support the type checking of \code{lambda} expressions, so we
  16509. translate it to a regular \code{Assign} statement.
  16510. The top-level function definitions need to be updated to take an extra
  16511. closure parameter, but that parameter is ignored in the body of those
  16512. functions.
  16513. \subsection{An Example Translation}
  16514. \label{sec:example-lambda}
  16515. Figure~\ref{fig:lexical-functions-example} shows the result of
  16516. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16517. program demonstrating lexical scoping that we discussed at the
  16518. beginning of this chapter.
  16519. \begin{figure}[tbp]
  16520. \begin{tcolorbox}[colback=white]
  16521. \begin{minipage}{0.8\textwidth}
  16522. {\if\edition\racketEd
  16523. % tests/lambda_test_6.rkt
  16524. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16525. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16526. (let ([y8 4])
  16527. (lambda: ([z9 : Integer]) : Integer
  16528. (+ x7 (+ y8 z9)))))
  16529. (define (main) : Integer
  16530. (let ([g0 ((fun-ref f6 1) 5)])
  16531. (let ([h1 ((fun-ref f6 1) 3)])
  16532. (+ (g0 11) (h1 15)))))
  16533. \end{lstlisting}
  16534. $\Rightarrow$
  16535. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16536. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16537. (let ([y8 4])
  16538. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16539. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16540. (let ([x7 (vector-ref fvs3 1)])
  16541. (let ([y8 (vector-ref fvs3 2)])
  16542. (+ x7 (+ y8 z9)))))
  16543. (define (main) : Integer
  16544. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16545. ((vector-ref clos5 0) clos5 5))])
  16546. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16547. ((vector-ref clos6 0) clos6 3))])
  16548. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16549. \end{lstlisting}
  16550. \fi}
  16551. %
  16552. {\if\edition\pythonEd\pythonColor
  16553. % free_var.py
  16554. \begin{lstlisting}
  16555. def f(x: int) -> Callable[[int],int]:
  16556. y = 4
  16557. return lambda z: x + y + z
  16558. g = f(5)
  16559. h = f(3)
  16560. print(g(11) + h(15))
  16561. \end{lstlisting}
  16562. $\Rightarrow$
  16563. \begin{lstlisting}
  16564. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16565. x = fvs_1[1]
  16566. y = fvs_1[2]
  16567. return (x + y[0] + z)
  16568. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16569. y = (uninitialized(int),)
  16570. y[0] = 4
  16571. return closure{1}({lambda_0}, x, y)
  16572. def main() -> int:
  16573. g = (begin: clos_3 = closure{1}({f})
  16574. clos_3[0](clos_3, 5))
  16575. h = (begin: clos_4 = closure{1}({f})
  16576. clos_4[0](clos_4, 3))
  16577. print((begin: clos_5 = g
  16578. clos_5[0](clos_5, 11))
  16579. + (begin: clos_6 = h
  16580. clos_6[0](clos_6, 15)))
  16581. return 0
  16582. \end{lstlisting}
  16583. \fi}
  16584. \end{minipage}
  16585. \end{tcolorbox}
  16586. \caption{Example of closure conversion.}
  16587. \label{fig:lexical-functions-example}
  16588. \end{figure}
  16589. \begin{exercise}\normalfont\normalsize
  16590. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16591. Create five new programs that use \key{lambda} functions and make use of
  16592. lexical scoping. Test your compiler on these new programs and all
  16593. your previously created test programs.
  16594. \end{exercise}
  16595. \section{Expose Allocation}
  16596. \label{sec:expose-allocation-r5}
  16597. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16598. allocates and initializes a tuple, similar to the translation of the
  16599. tuple creation in section~\ref{sec:expose-allocation}. The main
  16600. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16601. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16602. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16603. type, but only a single element tuple type. The types of the tuple
  16604. elements that correspond to the free variables of the closure should
  16605. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16606. can be used to adjust the result type.
  16607. \section{Explicate Control and \LangCLam{}}
  16608. \label{sec:explicate-r5}
  16609. The output language of \code{explicate\_control} is \LangCLam{}; the
  16610. definition of its abstract syntax is shown in
  16611. figure~\ref{fig:Clam-syntax}.
  16612. %
  16613. \racket{The only differences with respect to \LangCFun{} are the
  16614. addition of the \code{AllocateClosure} form to the grammar for
  16615. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16616. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16617. similar to the handling of other expressions such as primitive
  16618. operators.}
  16619. %
  16620. \python{The differences with respect to \LangCFun{} are the
  16621. additions of \code{Uninitialized}, \code{AllocateClosure},
  16622. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16623. \code{explicate\_control} pass is similar to the handling of other
  16624. expressions such as primitive operators.}
  16625. \newcommand{\ClambdaASTRacket}{
  16626. \begin{array}{lcl}
  16627. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16628. \itm{op} &::= & \code{procedure-arity}
  16629. \end{array}
  16630. }
  16631. \newcommand{\ClambdaASTPython}{
  16632. \begin{array}{lcl}
  16633. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16634. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16635. &\MID& \ARITY{\Atm}
  16636. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16637. \end{array}
  16638. }
  16639. \begin{figure}[tp]
  16640. \begin{tcolorbox}[colback=white]
  16641. \small
  16642. {\if\edition\racketEd
  16643. \[
  16644. \begin{array}{l}
  16645. \gray{\CvarASTRacket} \\ \hline
  16646. \gray{\CifASTRacket} \\ \hline
  16647. \gray{\CloopASTRacket} \\ \hline
  16648. \gray{\CtupASTRacket} \\ \hline
  16649. \gray{\CfunASTRacket} \\ \hline
  16650. \ClambdaASTRacket \\
  16651. \begin{array}{lcl}
  16652. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16653. \end{array}
  16654. \end{array}
  16655. \]
  16656. \fi}
  16657. {\if\edition\pythonEd\pythonColor
  16658. \[
  16659. \begin{array}{l}
  16660. \gray{\CifASTPython} \\ \hline
  16661. \gray{\CtupASTPython} \\ \hline
  16662. \gray{\CfunASTPython} \\ \hline
  16663. \ClambdaASTPython \\
  16664. \begin{array}{lcl}
  16665. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16666. \end{array}
  16667. \end{array}
  16668. \]
  16669. \fi}
  16670. \end{tcolorbox}
  16671. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16672. \label{fig:Clam-syntax}
  16673. \index{subject}{Clambda@\LangCLam{} abstract syntax}
  16674. \end{figure}
  16675. \section{Select Instructions}
  16676. \label{sec:select-instructions-Llambda}
  16677. \index{subject}{select instructions}
  16678. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16679. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16680. (section~\ref{sec:select-instructions-gc}). The only difference is
  16681. that you should place the \itm{arity} in the tag that is stored at
  16682. position $0$ of the tuple. Recall that in
  16683. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16684. was not used. We store the arity in the $5$ bits starting at position
  16685. $58$.
  16686. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16687. instructions that access the tag from position $0$ of the vector and
  16688. extract the $5$ bits starting at position $58$ from the tag.}
  16689. %
  16690. \python{Compile a call to the \code{arity} operator to a sequence of
  16691. instructions that access the tag from position $0$ of the tuple
  16692. (representing a closure) and extract the $5$ bits starting at position
  16693. $58$ from the tag.}
  16694. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16695. needed for the compilation of \LangLam{}.
  16696. \begin{figure}[bthp]
  16697. \begin{tcolorbox}[colback=white]
  16698. {\if\edition\racketEd
  16699. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16700. \node (Lfun) at (0,2) {\large \LangLam{}};
  16701. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16702. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16703. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16704. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16705. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16706. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16707. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16708. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16709. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16710. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16711. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16712. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16713. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16714. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16715. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16716. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16717. \path[->,bend left=15] (Lfun) edge [above] node
  16718. {\ttfamily\footnotesize shrink} (Lfun-2);
  16719. \path[->,bend left=15] (Lfun-2) edge [above] node
  16720. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16721. \path[->,bend left=15] (Lfun-3) edge [above] node
  16722. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16723. \path[->,bend left=15] (F1-0) edge [left] node
  16724. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16725. \path[->,bend left=15] (F1-1) edge [below] node
  16726. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16727. \path[->,bend right=15] (F1-2) edge [above] node
  16728. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16729. \path[->,bend right=15] (F1-3) edge [above] node
  16730. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16731. \path[->,bend left=15] (F1-4) edge [right] node
  16732. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16733. \path[->,bend right=15] (F1-5) edge [below] node
  16734. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16735. \path[->,bend left=15] (F1-6) edge [above] node
  16736. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16737. \path[->] (C3-2) edge [right] node
  16738. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16739. \path[->,bend right=15] (x86-2) edge [right] node
  16740. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16741. \path[->,bend right=15] (x86-2-1) edge [below] node
  16742. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16743. \path[->,bend right=15] (x86-2-2) edge [right] node
  16744. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16745. \path[->,bend left=15] (x86-3) edge [above] node
  16746. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16747. \path[->,bend left=15] (x86-4) edge [right] node
  16748. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16749. \end{tikzpicture}
  16750. \fi}
  16751. {\if\edition\pythonEd\pythonColor
  16752. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16753. \node (Lfun) at (0,2) {\large \LangLam{}};
  16754. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16755. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16756. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16757. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16758. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16759. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16760. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16761. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16762. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16763. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16764. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16765. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16766. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16767. \path[->,bend left=15] (Lfun) edge [above] node
  16768. {\ttfamily\footnotesize shrink} (Lfun-2);
  16769. \path[->,bend left=15] (Lfun-2) edge [above] node
  16770. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16771. \path[->,bend left=15] (Lfun-3) edge [above] node
  16772. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16773. \path[->,bend left=15] (F1-0) edge [left] node
  16774. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16775. \path[->,bend left=15] (F1-1) edge [below] node
  16776. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16777. \path[->,bend left=15] (F1-2) edge [below] node
  16778. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16779. \path[->,bend right=15] (F1-3) edge [above] node
  16780. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16781. \path[->,bend right=15] (F1-5) edge [right] node
  16782. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16783. \path[->,bend left=15] (F1-6) edge [right] node
  16784. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16785. \path[->,bend right=15] (C3-2) edge [right] node
  16786. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16787. \path[->,bend right=15] (x86-2) edge [below] node
  16788. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16789. \path[->,bend right=15] (x86-3) edge [below] node
  16790. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16791. \path[->,bend left=15] (x86-4) edge [above] node
  16792. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16793. \end{tikzpicture}
  16794. \fi}
  16795. \end{tcolorbox}
  16796. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16797. functions.}
  16798. \label{fig:Llambda-passes}
  16799. \end{figure}
  16800. \clearpage
  16801. \section{Challenge: Optimize Closures}
  16802. \label{sec:optimize-closures}
  16803. In this chapter we compile lexically scoped functions into a
  16804. relatively efficient representation: flat closures. However, even this
  16805. representation comes with some overhead. For example, consider the
  16806. following program with a function \code{tail\_sum} that does not have
  16807. any free variables and where all the uses of \code{tail\_sum} are in
  16808. applications in which we know that only \code{tail\_sum} is being applied
  16809. (and not any other functions):
  16810. \begin{center}
  16811. \begin{minipage}{0.95\textwidth}
  16812. {\if\edition\racketEd
  16813. \begin{lstlisting}
  16814. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16815. (if (eq? n 0)
  16816. s
  16817. (tail_sum (- n 1) (+ n s))))
  16818. (+ (tail_sum 3 0) 36)
  16819. \end{lstlisting}
  16820. \fi}
  16821. {\if\edition\pythonEd\pythonColor
  16822. \begin{lstlisting}
  16823. def tail_sum(n : int, s : int) -> int:
  16824. if n == 0:
  16825. return s
  16826. else:
  16827. return tail_sum(n - 1, n + s)
  16828. print(tail_sum(3, 0) + 36)
  16829. \end{lstlisting}
  16830. \fi}
  16831. \end{minipage}
  16832. \end{center}
  16833. As described in this chapter, we uniformly apply closure conversion to
  16834. all functions, obtaining the following output for this program:
  16835. \begin{center}
  16836. \begin{minipage}{0.95\textwidth}
  16837. {\if\edition\racketEd
  16838. \begin{lstlisting}
  16839. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16840. (if (eq? n2 0)
  16841. s3
  16842. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16843. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16844. (define (main) : Integer
  16845. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16846. ((vector-ref clos6 0) clos6 3 0)) 27))
  16847. \end{lstlisting}
  16848. \fi}
  16849. {\if\edition\pythonEd\pythonColor
  16850. \begin{lstlisting}
  16851. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16852. if n_0 == 0:
  16853. return s_1
  16854. else:
  16855. return (begin: clos_2 = (tail_sum,)
  16856. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16857. def main() -> int :
  16858. print((begin: clos_4 = (tail_sum,)
  16859. clos_4[0](clos_4, 3, 0)) + 36)
  16860. return 0
  16861. \end{lstlisting}
  16862. \fi}
  16863. \end{minipage}
  16864. \end{center}
  16865. If this program were compiled according to the previous chapter, there
  16866. would be no allocation and the calls to \code{tail\_sum} would be
  16867. direct calls. In contrast, the program presented here allocates memory
  16868. for each closure and the calls to \code{tail\_sum} are indirect. These
  16869. two differences incur considerable overhead in a program such as this,
  16870. in which the allocations and indirect calls occur inside a tight loop.
  16871. One might think that this problem is trivial to solve: can't we just
  16872. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16873. and compile them to direct calls instead of treating it like a call to
  16874. a closure? We would also drop the new \code{fvs} parameter of
  16875. \code{tail\_sum}.
  16876. %
  16877. However, this problem is not so trivial, because a global function may
  16878. \emph{escape} and become involved in applications that also involve
  16879. closures. Consider the following example in which the application
  16880. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16881. application because the \code{lambda} may flow into \code{f}, but the
  16882. \code{inc} function might also flow into \code{f}:
  16883. \begin{center}
  16884. \begin{minipage}{\textwidth}
  16885. % lambda_test_30.rkt
  16886. {\if\edition\racketEd
  16887. \begin{lstlisting}
  16888. (define (inc [x : Integer]) : Integer
  16889. (+ x 1))
  16890. (let ([y (read)])
  16891. (let ([f (if (eq? (read) 0)
  16892. inc
  16893. (lambda: ([x : Integer]) : Integer (- x y)))])
  16894. (f 41)))
  16895. \end{lstlisting}
  16896. \fi}
  16897. {\if\edition\pythonEd\pythonColor
  16898. \begin{lstlisting}
  16899. def add1(x : int) -> int:
  16900. return x + 1
  16901. y = input_int()
  16902. g : Callable[[int], int] = lambda x: x - y
  16903. f = add1 if input_int() == 0 else g
  16904. print(f(41))
  16905. \end{lstlisting}
  16906. \fi}
  16907. \end{minipage}
  16908. \end{center}
  16909. If a global function name is used in any way other than as the
  16910. operator in a direct call, then we say that the function
  16911. \emph{escapes}. If a global function does not escape, then we do not
  16912. need to perform closure conversion on the function.
  16913. \begin{exercise}\normalfont\normalsize
  16914. Implement an auxiliary function for detecting which global
  16915. functions escape. Using that function, implement an improved version
  16916. of closure conversion that does not apply closure conversion to
  16917. global functions that do not escape but instead compiles them as
  16918. regular functions. Create several new test cases that check whether
  16919. your compiler properly detects whether global functions escape or not.
  16920. \end{exercise}
  16921. So far we have reduced the overhead of calling global functions, but
  16922. it would also be nice to reduce the overhead of calling a
  16923. \code{lambda} when we can determine at compile time which
  16924. \code{lambda} will be called. We refer to such calls as \emph{known
  16925. calls}. Consider the following example in which a \code{lambda} is
  16926. bound to \code{f} and then applied.
  16927. {\if\edition\racketEd
  16928. % lambda_test_9.rkt
  16929. \begin{lstlisting}
  16930. (let ([y (read)])
  16931. (let ([f (lambda: ([x : Integer]) : Integer
  16932. (+ x y))])
  16933. (f 21)))
  16934. \end{lstlisting}
  16935. \fi}
  16936. {\if\edition\pythonEd\pythonColor
  16937. \begin{lstlisting}
  16938. y = input_int()
  16939. f : Callable[[int],int] = lambda x: x + y
  16940. print(f(21))
  16941. \end{lstlisting}
  16942. \fi}
  16943. %
  16944. \noindent Closure conversion compiles the application
  16945. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16946. %
  16947. {\if\edition\racketEd
  16948. \begin{lstlisting}
  16949. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16950. (let ([y2 (vector-ref fvs6 1)])
  16951. (+ x3 y2)))
  16952. (define (main) : Integer
  16953. (let ([y2 (read)])
  16954. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16955. ((vector-ref f4 0) f4 21))))
  16956. \end{lstlisting}
  16957. \fi}
  16958. {\if\edition\pythonEd\pythonColor
  16959. \begin{lstlisting}
  16960. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16961. y_1 = fvs_4[1]
  16962. return x_2 + y_1[0]
  16963. def main() -> int:
  16964. y_1 = (777,)
  16965. y_1[0] = input_int()
  16966. f_0 = (lambda_3, y_1)
  16967. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16968. return 0
  16969. \end{lstlisting}
  16970. \fi}
  16971. %
  16972. \noindent However, we can instead compile the application
  16973. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16974. %
  16975. {\if\edition\racketEd
  16976. \begin{lstlisting}
  16977. (define (main) : Integer
  16978. (let ([y2 (read)])
  16979. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16980. ((fun-ref lambda5 1) f4 21))))
  16981. \end{lstlisting}
  16982. \fi}
  16983. {\if\edition\pythonEd\pythonColor
  16984. \begin{lstlisting}
  16985. def main() -> int:
  16986. y_1 = (777,)
  16987. y_1[0] = input_int()
  16988. f_0 = (lambda_3, y_1)
  16989. print(lambda_3(f_0, 21))
  16990. return 0
  16991. \end{lstlisting}
  16992. \fi}
  16993. The problem of determining which \code{lambda} will be called from a
  16994. particular application is quite challenging in general and the topic
  16995. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16996. following exercise we recommend that you compile an application to a
  16997. direct call when the operator is a variable and \racket{the variable
  16998. is \code{let}-bound to a closure}\python{the previous assignment to
  16999. the variable is a closure}. This can be accomplished by maintaining
  17000. an environment that maps variables to function names. Extend the
  17001. environment whenever you encounter a closure on the right-hand side of
  17002. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  17003. name of the global function for the closure. This pass should come
  17004. after closure conversion.
  17005. \begin{exercise}\normalfont\normalsize
  17006. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  17007. compiles known calls into direct calls. Verify that your compiler is
  17008. successful in this regard on several example programs.
  17009. \end{exercise}
  17010. These exercises only scratch the surface of closure optimization. A
  17011. good next step for the interested reader is to look at the work of
  17012. \citet{Keep:2012ab}.
  17013. \section{Further Reading}
  17014. The notion of lexically scoped functions predates modern computers by
  17015. about a decade. They were invented by \citet{Church:1932aa}, who
  17016. proposed the lambda calculus as a foundation for logic. Anonymous
  17017. functions were included in the LISP~\citep{McCarthy:1960dz}
  17018. programming language but were initially dynamically scoped. The Scheme
  17019. dialect of LISP adopted lexical scoping, and
  17020. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  17021. Scheme programs. However, environments were represented as linked
  17022. lists, so variable look-up was linear in the size of the
  17023. environment. \citet{Appel91} gives a detailed description of several
  17024. closure representations. In this chapter we represent environments
  17025. using flat closures, which were invented by
  17026. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  17027. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  17028. closures, variable look-up is constant time but the time to create a
  17029. closure is proportional to the number of its free variables. Flat
  17030. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  17031. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  17032. % todo: related work on assignment conversion (e.g. orbit and rabbit
  17033. % compilers)
  17034. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17035. \chapter{Dynamic Typing}
  17036. \label{ch:Ldyn}
  17037. \index{subject}{dynamic typing}
  17038. \setcounter{footnote}{0}
  17039. In this chapter we learn how to compile \LangDyn{}, a dynamically
  17040. typed language that is a subset of \racket{Racket}\python{Python}. The
  17041. focus on dynamic typing is in contrast to the previous chapters, which
  17042. have studied the compilation of statically typed languages. In
  17043. dynamically typed languages such as \LangDyn{}, a particular
  17044. expression may produce a value of a different type each time it is
  17045. executed. Consider the following example with a conditional \code{if}
  17046. expression that may return a Boolean or an integer depending on the
  17047. input to the program:
  17048. % part of dynamic_test_25.rkt
  17049. {\if\edition\racketEd
  17050. \begin{lstlisting}
  17051. (not (if (eq? (read) 1) #f 0))
  17052. \end{lstlisting}
  17053. \fi}
  17054. {\if\edition\pythonEd\pythonColor
  17055. \begin{lstlisting}
  17056. not (False if input_int() == 1 else 0)
  17057. \end{lstlisting}
  17058. \fi}
  17059. Languages that allow expressions to produce different kinds of values
  17060. are called \emph{polymorphic}, a word composed of the Greek roots
  17061. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  17062. There are several kinds of polymorphism in programming languages, such as
  17063. subtype polymorphism\index{subject}{subtype polymorphism} and
  17064. parametric polymorphism\index{subject}{parametric polymorphism}
  17065. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  17066. study in this chapter does not have a special name; it is the kind
  17067. that arises in dynamically typed languages.
  17068. Another characteristic of dynamically typed languages is that
  17069. their primitive operations, such as \code{not}, are often defined to operate
  17070. on many different types of values. In fact, in
  17071. \racket{Racket}\python{Python}, the \code{not} operator produces a
  17072. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  17073. given anything else it returns \FALSE{}.
  17074. Furthermore, even when primitive operations restrict their inputs to
  17075. values of a certain type, this restriction is enforced at runtime
  17076. instead of during compilation. For example, the tuple read
  17077. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  17078. results in a runtime error because the first argument must
  17079. be a tuple, not a Boolean.
  17080. \section{The \LangDyn{} Language}
  17081. \newcommand{\LdynGrammarRacket}{
  17082. \begin{array}{rcl}
  17083. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  17084. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  17085. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  17086. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  17087. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  17088. \end{array}
  17089. }
  17090. \newcommand{\LdynASTRacket}{
  17091. \begin{array}{lcl}
  17092. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17093. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  17094. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  17095. \end{array}
  17096. }
  17097. \begin{figure}[tp]
  17098. \centering
  17099. \begin{tcolorbox}[colback=white]
  17100. \small
  17101. {\if\edition\racketEd
  17102. \[
  17103. \begin{array}{l}
  17104. \gray{\LintGrammarRacket{}} \\ \hline
  17105. \gray{\LvarGrammarRacket{}} \\ \hline
  17106. \gray{\LifGrammarRacket{}} \\ \hline
  17107. \gray{\LwhileGrammarRacket} \\ \hline
  17108. \gray{\LtupGrammarRacket} \\ \hline
  17109. \LdynGrammarRacket \\
  17110. \begin{array}{rcl}
  17111. \LangDynM{} &::=& \Def\ldots\; \Exp
  17112. \end{array}
  17113. \end{array}
  17114. \]
  17115. \fi}
  17116. {\if\edition\pythonEd\pythonColor
  17117. \[
  17118. \begin{array}{rcl}
  17119. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17120. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17121. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17122. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17123. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17124. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17125. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17126. \MID \CLEN{\Exp} \\
  17127. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17128. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17129. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17130. \MID \Var\mathop{\key{=}}\Exp \\
  17131. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17132. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17133. &\MID& \CRETURN{\Exp} \\
  17134. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17135. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17136. \end{array}
  17137. \]
  17138. \fi}
  17139. \end{tcolorbox}
  17140. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17141. \label{fig:r7-concrete-syntax}
  17142. \index{subject}{Ldyn@\LangDyn{} concrete syntax}
  17143. \end{figure}
  17144. \begin{figure}[tp]
  17145. \centering
  17146. \begin{tcolorbox}[colback=white]
  17147. \small
  17148. {\if\edition\racketEd
  17149. \[
  17150. \begin{array}{l}
  17151. \gray{\LintASTRacket{}} \\ \hline
  17152. \gray{\LvarASTRacket{}} \\ \hline
  17153. \gray{\LifASTRacket{}} \\ \hline
  17154. \gray{\LwhileASTRacket} \\ \hline
  17155. \gray{\LtupASTRacket} \\ \hline
  17156. \LdynASTRacket \\
  17157. \begin{array}{lcl}
  17158. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17159. \end{array}
  17160. \end{array}
  17161. \]
  17162. \fi}
  17163. {\if\edition\pythonEd\pythonColor
  17164. \[
  17165. \begin{array}{rcl}
  17166. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17167. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17168. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17169. \MID \code{Is()} \\
  17170. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17171. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17172. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17173. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17174. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17175. &\MID& \VAR{\Var{}}
  17176. \MID \BOOL{\itm{bool}}
  17177. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17178. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17179. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17180. &\MID& \LEN{\Exp} \\
  17181. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17182. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17183. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17184. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17185. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17186. &\MID& \RETURN{\Exp} \\
  17187. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17188. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17189. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17190. \end{array}
  17191. \]
  17192. \fi}
  17193. \end{tcolorbox}
  17194. \caption{The abstract syntax of \LangDyn{}.}
  17195. \label{fig:r7-syntax}
  17196. \index{subject}{Ldyn@\LangDyn{} abstract syntax}
  17197. \end{figure}
  17198. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17199. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17200. %
  17201. There is no type checker for \LangDyn{} because it checks types only
  17202. at runtime.
  17203. The definitional interpreter for \LangDyn{} is presented in
  17204. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17205. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17206. \INT{n}. Instead of simply returning the integer \code{n} (as
  17207. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17208. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17209. value} that combines an underlying value with a tag that identifies
  17210. what kind of value it is. We define the following \racket{struct}\python{class}
  17211. to represent tagged values:
  17212. %
  17213. {\if\edition\racketEd
  17214. \begin{lstlisting}
  17215. (struct Tagged (value tag) #:transparent)
  17216. \end{lstlisting}
  17217. \fi}
  17218. {\if\edition\pythonEd\pythonColor
  17219. \begin{minipage}{\textwidth}
  17220. \begin{lstlisting}
  17221. @dataclass(eq=True)
  17222. class Tagged(Value):
  17223. value : Value
  17224. tag : str
  17225. def __str__(self):
  17226. return str(self.value)
  17227. \end{lstlisting}
  17228. \end{minipage}
  17229. \fi}
  17230. %
  17231. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17232. \code{Vector}, and \code{Procedure}.}
  17233. %
  17234. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17235. \skey{tuple}, and \skey{function}.}
  17236. %
  17237. Tags are closely related to types but do not always capture all the
  17238. information that a type does.
  17239. %
  17240. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17241. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17242. Any)} is tagged with \code{Procedure}.}
  17243. %
  17244. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17245. is tagged with \skey{tuple} and a function of type
  17246. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17247. is tagged with \skey{function}.}
  17248. Next consider the match case for accessing the element of a tuple.
  17249. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17250. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17251. argument is a tuple and the second is an integer.
  17252. \racket{
  17253. If they are not, a \code{trapped-error} is raised. Recall from
  17254. section~\ref{sec:interp_Lint} that when a definition interpreter
  17255. raises a \code{trapped-error} error, the compiled code must also
  17256. signal an error by exiting with return code \code{255}. A
  17257. \code{trapped-error} is also raised if the index is not less than the
  17258. length of the vector.
  17259. }
  17260. %
  17261. \python{If they are not, an exception is raised. The compiled code
  17262. must also signal an error by exiting with return code \code{255}. A
  17263. exception is also raised if the index is not less than the length of the
  17264. tuple or if it is negative.}
  17265. \begin{figure}[tbp]
  17266. \begin{tcolorbox}[colback=white]
  17267. {\if\edition\racketEd
  17268. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17269. (define ((interp-Ldyn-exp env) ast)
  17270. (define recur (interp-Ldyn-exp env))
  17271. (match ast
  17272. [(Var x) (unbox (lookup x env)]
  17273. [(Int n) (Tagged n 'Integer)]
  17274. [(Bool b) (Tagged b 'Boolean)]
  17275. [(Lambda xs rt body)
  17276. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17277. [(Prim 'vector es)
  17278. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17279. [(Prim 'vector-ref (list e1 e2))
  17280. (define vec (recur e1)) (define i (recur e2))
  17281. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17282. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17283. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17284. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17285. [(Prim 'vector-set! (list e1 e2 e3))
  17286. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17287. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17288. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17289. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17290. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17291. (Tagged (void) 'Void)]
  17292. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17293. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17294. [(Prim 'or (list e1 e2))
  17295. (define v1 (recur e1))
  17296. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17297. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17298. [(Prim op (list e1))
  17299. #:when (set-member? type-predicates op)
  17300. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17301. [(Prim op es)
  17302. (define args (map recur es))
  17303. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17304. (unless (for/or ([expected-tags (op-tags op)])
  17305. (equal? expected-tags tags))
  17306. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17307. (tag-value
  17308. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17309. [(If q t f)
  17310. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17311. [(Apply f es)
  17312. (define new-f (recur f)) (define args (map recur es))
  17313. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17314. (match f-val
  17315. [`(function ,xs ,body ,lam-env)
  17316. (unless (eq? (length xs) (length args))
  17317. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17318. (define new-env (append (map cons xs args) lam-env))
  17319. ((interp-Ldyn-exp new-env) body)]
  17320. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17321. \end{lstlisting}
  17322. \fi}
  17323. {\if\edition\pythonEd\pythonColor
  17324. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17325. class InterpLdyn(InterpLlambda):
  17326. def interp_exp(self, e, env):
  17327. match e:
  17328. case Constant(n):
  17329. return self.tag(super().interp_exp(e, env))
  17330. case Tuple(es, Load()):
  17331. return self.tag(super().interp_exp(e, env))
  17332. case Lambda(params, body):
  17333. return self.tag(super().interp_exp(e, env))
  17334. case Call(Name('input_int'), []):
  17335. return self.tag(super().interp_exp(e, env))
  17336. case BinOp(left, Add(), right):
  17337. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17338. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17339. case BinOp(left, Sub(), right):
  17340. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17341. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17342. case UnaryOp(USub(), e1):
  17343. v = self.interp_exp(e1, env)
  17344. return self.tag(- self.untag(v, 'int', e))
  17345. case IfExp(test, body, orelse):
  17346. v = self.interp_exp(test, env)
  17347. if self.untag(v, 'bool', e):
  17348. return self.interp_exp(body, env)
  17349. else:
  17350. return self.interp_exp(orelse, env)
  17351. case UnaryOp(Not(), e1):
  17352. v = self.interp_exp(e1, env)
  17353. return self.tag(not self.untag(v, 'bool', e))
  17354. case BoolOp(And(), values):
  17355. left = values[0]; right = values[1]
  17356. l = self.interp_exp(left, env)
  17357. if self.untag(l, 'bool', e):
  17358. return self.interp_exp(right, env)
  17359. else:
  17360. return self.tag(False)
  17361. case BoolOp(Or(), values):
  17362. left = values[0]; right = values[1]
  17363. l = self.interp_exp(left, env)
  17364. if self.untag(l, 'bool', e):
  17365. return self.tag(True)
  17366. else:
  17367. return self.interp_exp(right, env)
  17368. \end{lstlisting}
  17369. \fi}
  17370. \end{tcolorbox}
  17371. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17372. \label{fig:interp-Ldyn}
  17373. \end{figure}
  17374. {\if\edition\pythonEd\pythonColor
  17375. \begin{figure}[tbp]
  17376. \begin{tcolorbox}[colback=white]
  17377. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17378. # interp_exp continued
  17379. case Compare(left, [cmp], [right]):
  17380. l = self.interp_exp(left, env)
  17381. r = self.interp_exp(right, env)
  17382. if l.tag == r.tag:
  17383. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17384. else:
  17385. raise Exception('interp Compare unexpected '
  17386. + repr(l) + ' ' + repr(r))
  17387. case Subscript(tup, index, Load()):
  17388. t = self.interp_exp(tup, env)
  17389. n = self.interp_exp(index, env)
  17390. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17391. case Call(Name('len'), [tup]):
  17392. t = self.interp_exp(tup, env)
  17393. return self.tag(len(self.untag(t, 'tuple', e)))
  17394. case _:
  17395. return self.tag(super().interp_exp(e, env))
  17396. def interp_stmt(self, s, env, cont):
  17397. match s:
  17398. case If(test, body, orelse):
  17399. v = self.interp_exp(test, env)
  17400. match self.untag(v, 'bool', s):
  17401. case True:
  17402. return self.interp_stmts(body + cont, env)
  17403. case False:
  17404. return self.interp_stmts(orelse + cont, env)
  17405. case While(test, body, []):
  17406. v = self.interp_exp(test, env)
  17407. if self.untag(v, 'bool', test):
  17408. self.interp_stmts(body + [s] + cont, env)
  17409. else:
  17410. return self.interp_stmts(cont, env)
  17411. case Assign([Subscript(tup, index)], value):
  17412. tup = self.interp_exp(tup, env)
  17413. index = self.interp_exp(index, env)
  17414. tup_v = self.untag(tup, 'tuple', s)
  17415. index_v = self.untag(index, 'int', s)
  17416. tup_v[index_v] = self.interp_exp(value, env)
  17417. return self.interp_stmts(cont, env)
  17418. case FunctionDef(name, params, bod, dl, returns, comment):
  17419. if isinstance(params, ast.arguments):
  17420. ps = [p.arg for p in params.args]
  17421. else:
  17422. ps = [x for (x,t) in params]
  17423. env[name] = self.tag(Function(name, ps, bod, env))
  17424. return self.interp_stmts(cont, env)
  17425. case _:
  17426. return super().interp_stmt(s, env, cont)
  17427. \end{lstlisting}
  17428. \end{tcolorbox}
  17429. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17430. \label{fig:interp-Ldyn-2}
  17431. \end{figure}
  17432. \fi}
  17433. \begin{figure}[tbp]
  17434. \begin{tcolorbox}[colback=white]
  17435. {\if\edition\racketEd
  17436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17437. (define (interp-op op)
  17438. (match op
  17439. ['+ fx+]
  17440. ['- fx-]
  17441. ['read read-fixnum]
  17442. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17443. ['< (lambda (v1 v2)
  17444. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17445. ['<= (lambda (v1 v2)
  17446. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17447. ['> (lambda (v1 v2)
  17448. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17449. ['>= (lambda (v1 v2)
  17450. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17451. ['boolean? boolean?]
  17452. ['integer? fixnum?]
  17453. ['void? void?]
  17454. ['vector? vector?]
  17455. ['vector-length vector-length]
  17456. ['procedure? (match-lambda
  17457. [`(functions ,xs ,body ,env) #t] [else #f])]
  17458. [else (error 'interp-op "unknown operator" op)]))
  17459. (define (op-tags op)
  17460. (match op
  17461. ['+ '((Integer Integer))]
  17462. ['- '((Integer Integer) (Integer))]
  17463. ['read '(())]
  17464. ['not '((Boolean))]
  17465. ['< '((Integer Integer))]
  17466. ['<= '((Integer Integer))]
  17467. ['> '((Integer Integer))]
  17468. ['>= '((Integer Integer))]
  17469. ['vector-length '((Vector))]))
  17470. (define type-predicates
  17471. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17472. (define (tag-value v)
  17473. (cond [(boolean? v) (Tagged v 'Boolean)]
  17474. [(fixnum? v) (Tagged v 'Integer)]
  17475. [(procedure? v) (Tagged v 'Procedure)]
  17476. [(vector? v) (Tagged v 'Vector)]
  17477. [(void? v) (Tagged v 'Void)]
  17478. [else (error 'tag-value "unidentified value ~a" v)]))
  17479. (define (check-tag val expected ast)
  17480. (define tag (Tagged-tag val))
  17481. (unless (eq? tag expected)
  17482. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17483. \end{lstlisting}
  17484. \fi}
  17485. {\if\edition\pythonEd\pythonColor
  17486. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17487. class InterpLdyn(InterpLlambda):
  17488. def tag(self, v):
  17489. if v is True or v is False:
  17490. return Tagged(v, 'bool')
  17491. elif isinstance(v, int):
  17492. return Tagged(v, 'int')
  17493. elif isinstance(v, Function):
  17494. return Tagged(v, 'function')
  17495. elif isinstance(v, tuple):
  17496. return Tagged(v, 'tuple')
  17497. elif isinstance(v, type(None)):
  17498. return Tagged(v, 'none')
  17499. else:
  17500. raise Exception('tag: unexpected ' + repr(v))
  17501. def untag(self, v, expected_tag, ast):
  17502. match v:
  17503. case Tagged(val, tag) if tag == expected_tag:
  17504. return val
  17505. case _:
  17506. raise TrappedError('expected Tagged value with '
  17507. + expected_tag + ', not ' + ' ' + repr(v))
  17508. def apply_fun(self, fun, args, e):
  17509. f = self.untag(fun, 'function', e)
  17510. return super().apply_fun(f, args, e)
  17511. \end{lstlisting}
  17512. \fi}
  17513. \end{tcolorbox}
  17514. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17515. \label{fig:interp-Ldyn-aux}
  17516. \end{figure}
  17517. %\clearpage
  17518. \section{Representation of Tagged Values}
  17519. The interpreter for \LangDyn{} introduced a new kind of value: the
  17520. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17521. represent tagged values at the bit level. Because almost every
  17522. operation in \LangDyn{} involves manipulating tagged values, the
  17523. representation must be efficient. Recall that all our values are 64
  17524. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17525. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17526. $011$ for procedures, and $101$ for the void value\python{,
  17527. \key{None}}. We define the following auxiliary function for mapping
  17528. types to tag codes:
  17529. %
  17530. {\if\edition\racketEd
  17531. \begin{align*}
  17532. \itm{tagof}(\key{Integer}) &= 001 \\
  17533. \itm{tagof}(\key{Boolean}) &= 100 \\
  17534. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17535. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17536. \itm{tagof}(\key{Void}) &= 101
  17537. \end{align*}
  17538. \fi}
  17539. {\if\edition\pythonEd\pythonColor
  17540. \begin{align*}
  17541. \itm{tagof}(\key{IntType()}) &= 001 \\
  17542. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17543. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17544. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17545. \itm{tagof}(\key{type(None)}) &= 101
  17546. \end{align*}
  17547. \fi}
  17548. %
  17549. This stealing of 3 bits comes at some price: integers are now restricted
  17550. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17551. affect tuples and procedures because those values are addresses, and
  17552. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17553. they are always $000$. Thus, we do not lose information by overwriting
  17554. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17555. to recover the original address.
  17556. To make tagged values into first-class entities, we can give them a
  17557. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17558. operations such as \code{Inject} and \code{Project} for creating and
  17559. using them, yielding the statically typed \LangAny{} intermediate
  17560. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17561. section~\ref{sec:compile-r7}; in the next section we describe the
  17562. \LangAny{} language in greater detail.
  17563. \section{The \LangAny{} Language}
  17564. \label{sec:Rany-lang}
  17565. \newcommand{\LanyASTRacket}{
  17566. \begin{array}{lcl}
  17567. \Type &::= & \ANYTY \\
  17568. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17569. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17570. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17571. \itm{op} &::= & \code{any-vector-length}
  17572. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17573. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17574. \MID \code{procedure?} \MID \code{void?} \\
  17575. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17576. \end{array}
  17577. }
  17578. \newcommand{\LanyASTPython}{
  17579. \begin{array}{lcl}
  17580. \Type &::= & \key{AnyType()} \\
  17581. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17582. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17583. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17584. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17585. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17586. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17587. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17588. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17589. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17590. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17591. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17592. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17593. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17594. \end{array}
  17595. }
  17596. \begin{figure}[tp]
  17597. \centering
  17598. \begin{tcolorbox}[colback=white]
  17599. \small
  17600. {\if\edition\racketEd
  17601. \[
  17602. \begin{array}{l}
  17603. \gray{\LintOpAST} \\ \hline
  17604. \gray{\LvarASTRacket{}} \\ \hline
  17605. \gray{\LifASTRacket{}} \\ \hline
  17606. \gray{\LwhileASTRacket{}} \\ \hline
  17607. \gray{\LtupASTRacket{}} \\ \hline
  17608. \gray{\LfunASTRacket} \\ \hline
  17609. \gray{\LlambdaASTRacket} \\ \hline
  17610. \LanyASTRacket \\
  17611. \begin{array}{lcl}
  17612. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17613. \end{array}
  17614. \end{array}
  17615. \]
  17616. \fi}
  17617. {\if\edition\pythonEd\pythonColor
  17618. \[
  17619. \begin{array}{l}
  17620. \gray{\LintASTPython} \\ \hline
  17621. \gray{\LvarASTPython{}} \\ \hline
  17622. \gray{\LifASTPython{}} \\ \hline
  17623. \gray{\LwhileASTPython{}} \\ \hline
  17624. \gray{\LtupASTPython{}} \\ \hline
  17625. \gray{\LfunASTPython} \\ \hline
  17626. \gray{\LlambdaASTPython} \\ \hline
  17627. \LanyASTPython \\
  17628. \begin{array}{lcl}
  17629. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17630. \end{array}
  17631. \end{array}
  17632. \]
  17633. \fi}
  17634. \end{tcolorbox}
  17635. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17636. \label{fig:Lany-syntax}
  17637. \index{subject}{Lany@\LangAny{} abstract syntax}
  17638. \end{figure}
  17639. The definition of the abstract syntax of \LangAny{} is given in
  17640. figure~\ref{fig:Lany-syntax}.
  17641. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17642. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17643. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17644. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17645. converts the tagged value produced by expression $e$ into a value of
  17646. type $T$ or halts the program if the type tag does not match $T$.
  17647. %
  17648. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17649. restricted to be a flat type (the nonterminal $\FType$) which
  17650. simplifies the implementation and complies with the needs for
  17651. compiling \LangDyn{}.
  17652. The \racket{\code{any-vector}} operators
  17653. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17654. operations so that they can be applied to a value of type
  17655. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17656. tuple operations in that the index is not restricted to a literal
  17657. integer in the grammar but is allowed to be any expression.
  17658. \racket{The type predicates such as
  17659. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17660. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17661. the predicate and return {\FALSE} otherwise.}
  17662. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17663. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17664. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17665. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17666. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17667. \begin{figure}[btp]
  17668. \begin{tcolorbox}[colback=white]
  17669. {\if\edition\racketEd
  17670. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17671. (define type-check-Lany-class
  17672. (class type-check-Llambda-class
  17673. (super-new)
  17674. (inherit check-type-equal?)
  17675. (define/override (type-check-exp env)
  17676. (lambda (e)
  17677. (define recur (type-check-exp env))
  17678. (match e
  17679. [(Inject e1 ty)
  17680. (unless (flat-ty? ty)
  17681. (error 'type-check "may only inject from flat type, not ~a" ty))
  17682. (define-values (new-e1 e-ty) (recur e1))
  17683. (check-type-equal? e-ty ty e)
  17684. (values (Inject new-e1 ty) 'Any)]
  17685. [(Project e1 ty)
  17686. (unless (flat-ty? ty)
  17687. (error 'type-check "may only project to flat type, not ~a" ty))
  17688. (define-values (new-e1 e-ty) (recur e1))
  17689. (check-type-equal? e-ty 'Any e)
  17690. (values (Project new-e1 ty) ty)]
  17691. [(Prim 'any-vector-length (list e1))
  17692. (define-values (e1^ t1) (recur e1))
  17693. (check-type-equal? t1 'Any e)
  17694. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17695. [(Prim 'any-vector-ref (list e1 e2))
  17696. (define-values (e1^ t1) (recur e1))
  17697. (define-values (e2^ t2) (recur e2))
  17698. (check-type-equal? t1 'Any e)
  17699. (check-type-equal? t2 'Integer e)
  17700. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17701. [(Prim 'any-vector-set! (list e1 e2 e3))
  17702. (define-values (e1^ t1) (recur e1))
  17703. (define-values (e2^ t2) (recur e2))
  17704. (define-values (e3^ t3) (recur e3))
  17705. (check-type-equal? t1 'Any e)
  17706. (check-type-equal? t2 'Integer e)
  17707. (check-type-equal? t3 'Any e)
  17708. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17709. [(Prim pred (list e1))
  17710. #:when (set-member? (type-predicates) pred)
  17711. (define-values (new-e1 e-ty) (recur e1))
  17712. (check-type-equal? e-ty 'Any e)
  17713. (values (Prim pred (list new-e1)) 'Boolean)]
  17714. [(Prim 'eq? (list arg1 arg2))
  17715. (define-values (e1 t1) (recur arg1))
  17716. (define-values (e2 t2) (recur arg2))
  17717. (match* (t1 t2)
  17718. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17719. [(other wise) (check-type-equal? t1 t2 e)])
  17720. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17721. [else ((super type-check-exp env) e)])))
  17722. ))
  17723. \end{lstlisting}
  17724. \fi}
  17725. {\if\edition\pythonEd\pythonColor
  17726. \begin{lstlisting}
  17727. class TypeCheckLany(TypeCheckLlambda):
  17728. def type_check_exp(self, e, env):
  17729. match e:
  17730. case Inject(value, typ):
  17731. self.check_exp(value, typ, env)
  17732. return AnyType()
  17733. case Project(value, typ):
  17734. self.check_exp(value, AnyType(), env)
  17735. return typ
  17736. case Call(Name('any_tuple_load'), [tup, index]):
  17737. self.check_exp(tup, AnyType(), env)
  17738. self.check_exp(index, IntType(), env)
  17739. return AnyType()
  17740. case Call(Name('any_len'), [tup]):
  17741. self.check_exp(tup, AnyType(), env)
  17742. return IntType()
  17743. case Call(Name('arity'), [fun]):
  17744. ty = self.type_check_exp(fun, env)
  17745. match ty:
  17746. case FunctionType(ps, rt):
  17747. return IntType()
  17748. case TupleType([FunctionType(ps,rs)]):
  17749. return IntType()
  17750. case _:
  17751. raise Exception('type check arity unexpected ' + repr(ty))
  17752. case Call(Name('make_any'), [value, tag]):
  17753. self.type_check_exp(value, env)
  17754. self.check_exp(tag, IntType(), env)
  17755. return AnyType()
  17756. case AnnLambda(params, returns, body):
  17757. new_env = {x:t for (x,t) in env.items()}
  17758. for (x,t) in params:
  17759. new_env[x] = t
  17760. return_t = self.type_check_exp(body, new_env)
  17761. self.check_type_equal(returns, return_t, e)
  17762. return FunctionType([t for (x,t) in params], return_t)
  17763. case _:
  17764. return super().type_check_exp(e, env)
  17765. \end{lstlisting}
  17766. \fi}
  17767. \end{tcolorbox}
  17768. \caption{Type checker for the \LangAny{} language.}
  17769. \label{fig:type-check-Lany}
  17770. \end{figure}
  17771. {\if\edition\racketEd
  17772. \begin{figure}[tbp]
  17773. \begin{tcolorbox}[colback=white]
  17774. \begin{lstlisting}
  17775. (define/override (operator-types)
  17776. (append
  17777. '((integer? . ((Any) . Boolean))
  17778. (vector? . ((Any) . Boolean))
  17779. (procedure? . ((Any) . Boolean))
  17780. (void? . ((Any) . Boolean)))
  17781. (super operator-types)))
  17782. (define/public (type-predicates)
  17783. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17784. (define/public (flat-ty? ty)
  17785. (match ty
  17786. [(or `Integer `Boolean `Void) #t]
  17787. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17788. [`(,ts ... -> ,rt)
  17789. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17790. [else #f]))
  17791. \end{lstlisting}
  17792. \end{tcolorbox}
  17793. \caption{Auxiliary methods for type checking \LangAny{}.}
  17794. \label{fig:type-check-Lany-aux}
  17795. \end{figure}
  17796. \fi}
  17797. \begin{figure}[tbp]
  17798. \begin{tcolorbox}[colback=white]
  17799. {\if\edition\racketEd
  17800. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17801. (define interp-Lany-class
  17802. (class interp-Llambda-class
  17803. (super-new)
  17804. (define/override (interp-op op)
  17805. (match op
  17806. ['boolean? (match-lambda
  17807. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17808. [else #f])]
  17809. ['integer? (match-lambda
  17810. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17811. [else #f])]
  17812. ['vector? (match-lambda
  17813. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17814. [else #f])]
  17815. ['procedure? (match-lambda
  17816. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17817. [else #f])]
  17818. ['eq? (match-lambda*
  17819. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17820. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17821. [ls (apply (super interp-op op) ls)])]
  17822. ['any-vector-ref (lambda (v i)
  17823. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17824. ['any-vector-set! (lambda (v i a)
  17825. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17826. ['any-vector-length (lambda (v)
  17827. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17828. [else (super interp-op op)]))
  17829. (define/override ((interp-exp env) e)
  17830. (define recur (interp-exp env))
  17831. (match e
  17832. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17833. [(Project e ty2) (apply-project (recur e) ty2)]
  17834. [else ((super interp-exp env) e)]))
  17835. ))
  17836. (define (interp-Lany p)
  17837. (send (new interp-Lany-class) interp-program p))
  17838. \end{lstlisting}
  17839. \fi}
  17840. {\if\edition\pythonEd\pythonColor
  17841. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17842. class InterpLany(InterpLlambda):
  17843. def interp_exp(self, e, env):
  17844. match e:
  17845. case Inject(value, typ):
  17846. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17847. case Project(value, typ):
  17848. match self.interp_exp(value, env):
  17849. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17850. return val
  17851. case _:
  17852. raise Exception('failed project to ' + self.type_to_tag(typ))
  17853. case Call(Name('any_tuple_load'), [tup, index]):
  17854. match self.interp_exp(tup, env):
  17855. case Tagged(v, tag):
  17856. return v[self.interp_exp(index, env)]
  17857. case _:
  17858. raise Exception('in any_tuple_load untagged value')
  17859. case Call(Name('any_len'), [value]):
  17860. match self.interp_exp(value, env):
  17861. case Tagged(value, tag):
  17862. return len(value)
  17863. case _:
  17864. raise Exception('interp any_len untagged value')
  17865. case Call(Name('arity'), [fun]):
  17866. return self.arity(self.interp_exp(fun, env))
  17867. case _:
  17868. return super().interp_exp(e, env)
  17869. \end{lstlisting}
  17870. \fi}
  17871. \end{tcolorbox}
  17872. \caption{Interpreter for \LangAny{}.}
  17873. \label{fig:interp-Lany}
  17874. \end{figure}
  17875. \begin{figure}[btp]
  17876. \begin{tcolorbox}[colback=white]
  17877. {\if\edition\racketEd
  17878. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17879. (define/public (apply-inject v tg) (Tagged v tg))
  17880. (define/public (apply-project v ty2)
  17881. (define tag2 (any-tag ty2))
  17882. (match v
  17883. [(Tagged v1 tag1)
  17884. (cond
  17885. [(eq? tag1 tag2)
  17886. (match ty2
  17887. [`(Vector ,ts ...)
  17888. (define l1 ((interp-op 'vector-length) v1))
  17889. (cond
  17890. [(eq? l1 (length ts)) v1]
  17891. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17892. l1 (length ts))])]
  17893. [`(,ts ... -> ,rt)
  17894. (match v1
  17895. [`(function ,xs ,body ,env)
  17896. (cond [(eq? (length xs) (length ts)) v1]
  17897. [else
  17898. (error 'apply-project "arity mismatch ~a != ~a"
  17899. (length xs) (length ts))])]
  17900. [else (error 'apply-project "expected function not ~a" v1)])]
  17901. [else v1])]
  17902. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17903. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17904. \end{lstlisting}
  17905. \fi}
  17906. {\if\edition\pythonEd\pythonColor
  17907. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17908. class InterpLany(InterpLlambda):
  17909. def type_to_tag(self, typ):
  17910. match typ:
  17911. case FunctionType(params, rt):
  17912. return 'function'
  17913. case TupleType(fields):
  17914. return 'tuple'
  17915. case IntType():
  17916. return 'int'
  17917. case BoolType():
  17918. return 'bool'
  17919. case _:
  17920. raise Exception('type_to_tag unexpected ' + repr(typ))
  17921. def arity(self, v):
  17922. match v:
  17923. case Function(name, params, body, env):
  17924. return len(params)
  17925. case _:
  17926. raise Exception('Lany arity unexpected ' + repr(v))
  17927. \end{lstlisting}
  17928. \fi}
  17929. \end{tcolorbox}
  17930. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17931. \label{fig:interp-Lany-aux}
  17932. \end{figure}
  17933. \clearpage
  17934. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17935. \label{sec:compile-r7}
  17936. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17937. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17938. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17939. is that given any subexpression $e$ in the \LangDyn{} program, the
  17940. pass will produce an expression $e'$ in \LangAny{} that has type
  17941. \ANYTY{}. For example, the first row in
  17942. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17943. \TRUE{}, which must be injected to produce an expression of type
  17944. \ANYTY{}.
  17945. %
  17946. The compilation of addition is shown in the second row of
  17947. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17948. representative of many primitive operations: the arguments have type
  17949. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17950. be performed.
  17951. The compilation of \key{lambda} (third row of
  17952. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17953. produce type annotations: we simply use \ANYTY{}.
  17954. %
  17955. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17956. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17957. this pass has to account for some differences in behavior between
  17958. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17959. permissive than \LangAny{} regarding what kind of values can be used
  17960. in various places. For example, the condition of an \key{if} does
  17961. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17962. of the same type (in that case the result is \code{\#f}).}
  17963. \begin{figure}[btp]
  17964. \centering
  17965. \begin{tcolorbox}[colback=white]
  17966. {\if\edition\racketEd
  17967. \begin{tabular}{lll}
  17968. \begin{minipage}{0.27\textwidth}
  17969. \begin{lstlisting}
  17970. #t
  17971. \end{lstlisting}
  17972. \end{minipage}
  17973. &
  17974. $\Rightarrow$
  17975. &
  17976. \begin{minipage}{0.65\textwidth}
  17977. \begin{lstlisting}
  17978. (inject #t Boolean)
  17979. \end{lstlisting}
  17980. \end{minipage}
  17981. \\[2ex]\hline
  17982. \begin{minipage}{0.27\textwidth}
  17983. \begin{lstlisting}
  17984. (+ |$e_1$| |$e_2$|)
  17985. \end{lstlisting}
  17986. \end{minipage}
  17987. &
  17988. $\Rightarrow$
  17989. &
  17990. \begin{minipage}{0.65\textwidth}
  17991. \begin{lstlisting}
  17992. (inject
  17993. (+ (project |$e'_1$| Integer)
  17994. (project |$e'_2$| Integer))
  17995. Integer)
  17996. \end{lstlisting}
  17997. \end{minipage}
  17998. \\[2ex]\hline
  17999. \begin{minipage}{0.27\textwidth}
  18000. \begin{lstlisting}
  18001. (lambda (|$x_1 \ldots$|) |$e$|)
  18002. \end{lstlisting}
  18003. \end{minipage}
  18004. &
  18005. $\Rightarrow$
  18006. &
  18007. \begin{minipage}{0.65\textwidth}
  18008. \begin{lstlisting}
  18009. (inject
  18010. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  18011. (Any|$\ldots$|Any -> Any))
  18012. \end{lstlisting}
  18013. \end{minipage}
  18014. \\[2ex]\hline
  18015. \begin{minipage}{0.27\textwidth}
  18016. \begin{lstlisting}
  18017. (|$e_0$| |$e_1 \ldots e_n$|)
  18018. \end{lstlisting}
  18019. \end{minipage}
  18020. &
  18021. $\Rightarrow$
  18022. &
  18023. \begin{minipage}{0.65\textwidth}
  18024. \begin{lstlisting}
  18025. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  18026. \end{lstlisting}
  18027. \end{minipage}
  18028. \\[2ex]\hline
  18029. \begin{minipage}{0.27\textwidth}
  18030. \begin{lstlisting}
  18031. (vector-ref |$e_1$| |$e_2$|)
  18032. \end{lstlisting}
  18033. \end{minipage}
  18034. &
  18035. $\Rightarrow$
  18036. &
  18037. \begin{minipage}{0.65\textwidth}
  18038. \begin{lstlisting}
  18039. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  18040. \end{lstlisting}
  18041. \end{minipage}
  18042. \\[2ex]\hline
  18043. \begin{minipage}{0.27\textwidth}
  18044. \begin{lstlisting}
  18045. (if |$e_1$| |$e_2$| |$e_3$|)
  18046. \end{lstlisting}
  18047. \end{minipage}
  18048. &
  18049. $\Rightarrow$
  18050. &
  18051. \begin{minipage}{0.65\textwidth}
  18052. \begin{lstlisting}
  18053. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18054. \end{lstlisting}
  18055. \end{minipage}
  18056. \\[2ex]\hline
  18057. \begin{minipage}{0.27\textwidth}
  18058. \begin{lstlisting}
  18059. (eq? |$e_1$| |$e_2$|)
  18060. \end{lstlisting}
  18061. \end{minipage}
  18062. &
  18063. $\Rightarrow$
  18064. &
  18065. \begin{minipage}{0.65\textwidth}
  18066. \begin{lstlisting}
  18067. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18068. \end{lstlisting}
  18069. \end{minipage}
  18070. \\[2ex]\hline
  18071. \begin{minipage}{0.27\textwidth}
  18072. \begin{lstlisting}
  18073. (not |$e_1$|)
  18074. \end{lstlisting}
  18075. \end{minipage}
  18076. &
  18077. $\Rightarrow$
  18078. &
  18079. \begin{minipage}{0.65\textwidth}
  18080. \begin{lstlisting}
  18081. (if (eq? |$e'_1$| (inject #f Boolean))
  18082. (inject #t Boolean) (inject #f Boolean))
  18083. \end{lstlisting}
  18084. \end{minipage}
  18085. \end{tabular}
  18086. \fi}
  18087. {\if\edition\pythonEd\pythonColor
  18088. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  18089. \begin{minipage}{0.23\textwidth}
  18090. \begin{lstlisting}
  18091. True
  18092. \end{lstlisting}
  18093. \end{minipage}
  18094. &
  18095. $\Rightarrow$
  18096. &
  18097. \begin{minipage}{0.7\textwidth}
  18098. \begin{lstlisting}
  18099. Inject(True, BoolType())
  18100. \end{lstlisting}
  18101. \end{minipage}
  18102. \\[2ex]\hline
  18103. \begin{minipage}{0.23\textwidth}
  18104. \begin{lstlisting}
  18105. |$e_1$| + |$e_2$|
  18106. \end{lstlisting}
  18107. \end{minipage}
  18108. &
  18109. $\Rightarrow$
  18110. &
  18111. \begin{minipage}{0.7\textwidth}
  18112. \begin{lstlisting}
  18113. Inject(Project(|$e'_1$|, IntType())
  18114. + Project(|$e'_2$|, IntType()),
  18115. IntType())
  18116. \end{lstlisting}
  18117. \end{minipage}
  18118. \\[2ex]\hline
  18119. \begin{minipage}{0.23\textwidth}
  18120. \begin{lstlisting}
  18121. lambda |$x_1 \ldots$|: |$e$|
  18122. \end{lstlisting}
  18123. \end{minipage}
  18124. &
  18125. $\Rightarrow$
  18126. &
  18127. \begin{minipage}{0.7\textwidth}
  18128. \begin{lstlisting}
  18129. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18130. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18131. \end{lstlisting}
  18132. \end{minipage}
  18133. \\[2ex]\hline
  18134. \begin{minipage}{0.23\textwidth}
  18135. \begin{lstlisting}
  18136. |$e_0$|(|$e_1 \ldots e_n$|)
  18137. \end{lstlisting}
  18138. \end{minipage}
  18139. &
  18140. $\Rightarrow$
  18141. &
  18142. \begin{minipage}{0.7\textwidth}
  18143. \begin{lstlisting}
  18144. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18145. AnyType())), |$e'_1, \ldots, e'_n$|)
  18146. \end{lstlisting}
  18147. \end{minipage}
  18148. \\[2ex]\hline
  18149. \begin{minipage}{0.23\textwidth}
  18150. \begin{lstlisting}
  18151. |$e_1$|[|$e_2$|]
  18152. \end{lstlisting}
  18153. \end{minipage}
  18154. &
  18155. $\Rightarrow$
  18156. &
  18157. \begin{minipage}{0.7\textwidth}
  18158. \begin{lstlisting}
  18159. Call(Name('any_tuple_load'),
  18160. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18161. \end{lstlisting}
  18162. \end{minipage}
  18163. %% \begin{minipage}{0.23\textwidth}
  18164. %% \begin{lstlisting}
  18165. %% |$e_2$| if |$e_1$| else |$e_3$|
  18166. %% \end{lstlisting}
  18167. %% \end{minipage}
  18168. %% &
  18169. %% $\Rightarrow$
  18170. %% &
  18171. %% \begin{minipage}{0.7\textwidth}
  18172. %% \begin{lstlisting}
  18173. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18174. %% \end{lstlisting}
  18175. %% \end{minipage}
  18176. %% \\[2ex]\hline
  18177. %% \begin{minipage}{0.23\textwidth}
  18178. %% \begin{lstlisting}
  18179. %% (eq? |$e_1$| |$e_2$|)
  18180. %% \end{lstlisting}
  18181. %% \end{minipage}
  18182. %% &
  18183. %% $\Rightarrow$
  18184. %% &
  18185. %% \begin{minipage}{0.7\textwidth}
  18186. %% \begin{lstlisting}
  18187. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18188. %% \end{lstlisting}
  18189. %% \end{minipage}
  18190. %% \\[2ex]\hline
  18191. %% \begin{minipage}{0.23\textwidth}
  18192. %% \begin{lstlisting}
  18193. %% (not |$e_1$|)
  18194. %% \end{lstlisting}
  18195. %% \end{minipage}
  18196. %% &
  18197. %% $\Rightarrow$
  18198. %% &
  18199. %% \begin{minipage}{0.7\textwidth}
  18200. %% \begin{lstlisting}
  18201. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18202. %% (inject #t Boolean) (inject #f Boolean))
  18203. %% \end{lstlisting}
  18204. %% \end{minipage}
  18205. %% \\[2ex]\hline
  18206. \\\hline
  18207. \end{tabular}
  18208. \fi}
  18209. \end{tcolorbox}
  18210. \caption{Cast insertion.}
  18211. \label{fig:compile-r7-Lany}
  18212. \end{figure}
  18213. \section{Reveal Casts}
  18214. \label{sec:reveal-casts-Lany}
  18215. % TODO: define R'_6
  18216. In the \code{reveal\_casts} pass, we recommend compiling
  18217. \code{Project} into a conditional expression that checks whether the
  18218. value's tag matches the target type; if it does, the value is
  18219. converted to a value of the target type by removing the tag; if it
  18220. does not, the program exits.
  18221. %
  18222. {\if\edition\racketEd
  18223. %
  18224. To perform these actions we need a new primitive operation,
  18225. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18226. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18227. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18228. underlying value from a tagged value. The \code{ValueOf} form
  18229. includes the type for the underlying value that is used by the type
  18230. checker.
  18231. %
  18232. \fi}
  18233. %
  18234. {\if\edition\pythonEd\pythonColor
  18235. %
  18236. To perform these actions we need two new AST classes: \code{TagOf} and
  18237. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18238. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18239. the underlying value from a tagged value. The \code{ValueOf}
  18240. operation includes the type for the underlying value that is used by
  18241. the type checker.
  18242. %
  18243. \fi}
  18244. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18245. \code{Project} can be translated as follows:
  18246. \begin{center}
  18247. \begin{minipage}{1.0\textwidth}
  18248. {\if\edition\racketEd
  18249. \begin{lstlisting}
  18250. (Project |$e$| |$\FType$|)
  18251. |$\Rightarrow$|
  18252. (Let |$\itm{tmp}$| |$e'$|
  18253. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18254. (Int |$\itm{tagof}(\FType)$|)))
  18255. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18256. (Exit)))
  18257. \end{lstlisting}
  18258. \fi}
  18259. {\if\edition\pythonEd\pythonColor
  18260. \begin{lstlisting}
  18261. Project(|$e$|, |$\FType$|)
  18262. |$\Rightarrow$|
  18263. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18264. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18265. [Constant(|$\itm{tagof}(\FType)$|)]),
  18266. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18267. Call(Name('exit'), [])))
  18268. \end{lstlisting}
  18269. \fi}
  18270. \end{minipage}
  18271. \end{center}
  18272. If the target type of the projection is a tuple or function type, then
  18273. there is a bit more work to do. For tuples, check that the length of
  18274. the tuple type matches the length of the tuple. For functions, check
  18275. that the number of parameters in the function type matches the
  18276. function's arity.
  18277. Regarding \code{Inject}, we recommend compiling it to a slightly
  18278. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18279. takes a tag instead of a type.
  18280. \begin{center}
  18281. \begin{minipage}{1.0\textwidth}
  18282. {\if\edition\racketEd
  18283. \begin{lstlisting}
  18284. (Inject |$e$| |$\FType$|)
  18285. |$\Rightarrow$|
  18286. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18287. \end{lstlisting}
  18288. \fi}
  18289. {\if\edition\pythonEd\pythonColor
  18290. \begin{lstlisting}
  18291. Inject(|$e$|, |$\FType$|)
  18292. |$\Rightarrow$|
  18293. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18294. \end{lstlisting}
  18295. \fi}
  18296. \end{minipage}
  18297. \end{center}
  18298. {\if\edition\pythonEd\pythonColor
  18299. %
  18300. The introduction of \code{make\_any} makes it difficult to use
  18301. bidirectional type checking because we no longer have an expected type
  18302. to use for type checking the expression $e'$. Thus, we run into
  18303. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18304. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18305. annotated lambda) that contains its return type and the types of its
  18306. parameters.
  18307. %
  18308. \fi}
  18309. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18310. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18311. translation of \code{Project}.}
  18312. {\if\edition\racketEd
  18313. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18314. combine the projection action with the vector operation. Also, the
  18315. read and write operations allow arbitrary expressions for the index, so
  18316. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18317. cannot guarantee that the index is within bounds. Thus, we insert code
  18318. to perform bounds checking at runtime. The translation for
  18319. \code{any-vector-ref} is as follows, and the other two operations are
  18320. translated in a similar way:
  18321. \begin{center}
  18322. \begin{minipage}{0.95\textwidth}
  18323. \begin{lstlisting}
  18324. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18325. |$\Rightarrow$|
  18326. (Let |$v$| |$e'_1$|
  18327. (Let |$i$| |$e'_2$|
  18328. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18329. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18330. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18331. (Exit))
  18332. (Exit))))
  18333. \end{lstlisting}
  18334. \end{minipage}
  18335. \end{center}
  18336. \fi}
  18337. %
  18338. {\if\edition\pythonEd\pythonColor
  18339. %
  18340. The \code{any\_tuple\_load} operation combines the projection action
  18341. with the load operation. Also, the load operation allows arbitrary
  18342. expressions for the index, so the type checker for \LangAny{}
  18343. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18344. within bounds. Thus, we insert code to perform bounds checking at
  18345. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18346. \begin{lstlisting}
  18347. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18348. |$\Rightarrow$|
  18349. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18350. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18351. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18352. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18353. Call(Name('exit'), [])),
  18354. Call(Name('exit'), [])))
  18355. \end{lstlisting}
  18356. \fi}
  18357. {\if\edition\pythonEd\pythonColor
  18358. \section{Assignment Conversion}
  18359. \label{sec:convert-assignments-Lany}
  18360. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18361. \code{AnnLambda} AST classes.
  18362. \section{Closure Conversion}
  18363. \label{sec:closure-conversion-Lany}
  18364. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18365. \code{AnnLambda} AST classes.
  18366. \fi}
  18367. \section{Remove Complex Operands}
  18368. \label{sec:rco-Lany}
  18369. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18370. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18371. %
  18372. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18373. complex expressions. Their subexpressions must be atomic.}
  18374. \section{Explicate Control and \LangCAny{}}
  18375. \label{sec:explicate-Lany}
  18376. The output of \code{explicate\_control} is the \LangCAny{} language,
  18377. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18378. %
  18379. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18380. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18381. note that the index argument of \code{vector-ref} and
  18382. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18383. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18384. %
  18385. \python{Update the auxiliary functions \code{explicate\_tail},
  18386. \code{explicate\_effect}, and \code{explicate\_pred} as
  18387. appropriate to handle the new expressions in \LangCAny{}. }
  18388. \newcommand{\CanyASTPython}{
  18389. \begin{array}{lcl}
  18390. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18391. &\MID& \key{TagOf}\LP \Atm \RP
  18392. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18393. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18394. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18395. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18396. \end{array}
  18397. }
  18398. \newcommand{\CanyASTRacket}{
  18399. \begin{array}{lcl}
  18400. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18401. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18402. &\MID& \VALUEOF{\Atm}{\FType} \\
  18403. \Tail &::= & \LP\key{Exit}\RP
  18404. \end{array}
  18405. }
  18406. \begin{figure}[tp]
  18407. \begin{tcolorbox}[colback=white]
  18408. \small
  18409. {\if\edition\racketEd
  18410. \[
  18411. \begin{array}{l}
  18412. \gray{\CvarASTRacket} \\ \hline
  18413. \gray{\CifASTRacket} \\ \hline
  18414. \gray{\CloopASTRacket} \\ \hline
  18415. \gray{\CtupASTRacket} \\ \hline
  18416. \gray{\CfunASTRacket} \\ \hline
  18417. \gray{\ClambdaASTRacket} \\ \hline
  18418. \CanyASTRacket \\
  18419. \begin{array}{lcl}
  18420. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18421. \end{array}
  18422. \end{array}
  18423. \]
  18424. \fi}
  18425. {\if\edition\pythonEd\pythonColor
  18426. \[
  18427. \begin{array}{l}
  18428. \gray{\CifASTPython} \\ \hline
  18429. \gray{\CtupASTPython} \\ \hline
  18430. \gray{\CfunASTPython} \\ \hline
  18431. \gray{\ClambdaASTPython} \\ \hline
  18432. \CanyASTPython \\
  18433. \begin{array}{lcl}
  18434. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18435. \end{array}
  18436. \end{array}
  18437. \]
  18438. \fi}
  18439. \end{tcolorbox}
  18440. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18441. \label{fig:c5-syntax}
  18442. \index{subject}{Cany@\LangCAny{} abstract syntax}
  18443. \end{figure}
  18444. \section{Select Instructions}
  18445. \label{sec:select-Lany}
  18446. \index{subject}{select instructions}
  18447. In the \code{select\_instructions} pass, we translate the primitive
  18448. operations on the \ANYTY{} type to x86 instructions that manipulate
  18449. the three tag bits of the tagged value. In the following descriptions,
  18450. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18451. of translating $e$ into an x86 argument:
  18452. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18453. We recommend compiling the
  18454. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18455. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18456. shifts the destination to the left by the number of bits specified by its
  18457. source argument (in this case three, the length of the tag), and it
  18458. preserves the sign of the integer. We use the \key{orq} instruction to
  18459. combine the tag and the value to form the tagged value.
  18460. {\if\edition\racketEd
  18461. \begin{lstlisting}
  18462. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18463. |$\Rightarrow$|
  18464. movq |$e'$|, |\itm{lhs'}|
  18465. salq $3, |\itm{lhs'}|
  18466. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18467. \end{lstlisting}
  18468. \fi}
  18469. %
  18470. {\if\edition\pythonEd\pythonColor
  18471. \begin{lstlisting}
  18472. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18473. |$\Rightarrow$|
  18474. movq |$e'$|, |\itm{lhs'}|
  18475. salq $3, |\itm{lhs'}|
  18476. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18477. \end{lstlisting}
  18478. \fi}
  18479. %
  18480. The instruction selection\index{subject}{instruction selection} for
  18481. tuples and procedures is different because there is no need to shift
  18482. them to the left. The rightmost 3 bits are already zeros, so we simply
  18483. combine the value and the tag using \key{orq}. \\
  18484. %
  18485. {\if\edition\racketEd
  18486. \begin{center}
  18487. \begin{minipage}{\textwidth}
  18488. \begin{lstlisting}
  18489. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18490. |$\Rightarrow$|
  18491. movq |$e'$|, |\itm{lhs'}|
  18492. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18493. \end{lstlisting}
  18494. \end{minipage}
  18495. \end{center}
  18496. \fi}
  18497. %
  18498. {\if\edition\pythonEd\pythonColor
  18499. \begin{lstlisting}
  18500. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18501. |$\Rightarrow$|
  18502. movq |$e'$|, |\itm{lhs'}|
  18503. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18504. \end{lstlisting}
  18505. \fi}
  18506. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18507. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18508. operation extracts the type tag from a value of type \ANYTY{}. The
  18509. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18510. bitwise-and of the value with $111$ ($7$ decimal).
  18511. %
  18512. {\if\edition\racketEd
  18513. \begin{lstlisting}
  18514. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18515. |$\Rightarrow$|
  18516. movq |$e'$|, |\itm{lhs'}|
  18517. andq $7, |\itm{lhs'}|
  18518. \end{lstlisting}
  18519. \fi}
  18520. %
  18521. {\if\edition\pythonEd\pythonColor
  18522. \begin{lstlisting}
  18523. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18524. |$\Rightarrow$|
  18525. movq |$e'$|, |\itm{lhs'}|
  18526. andq $7, |\itm{lhs'}|
  18527. \end{lstlisting}
  18528. \fi}
  18529. \paragraph{\code{ValueOf}}
  18530. The instructions for \key{ValueOf} also differ, depending on whether
  18531. the type $T$ is a pointer (tuple or function) or not (integer or
  18532. Boolean). The following shows the instruction
  18533. selection for integers and
  18534. Booleans, in which we produce an untagged value by shifting it to the
  18535. right by 3 bits:
  18536. %
  18537. {\if\edition\racketEd
  18538. \begin{lstlisting}
  18539. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18540. |$\Rightarrow$|
  18541. movq |$e'$|, |\itm{lhs'}|
  18542. sarq $3, |\itm{lhs'}|
  18543. \end{lstlisting}
  18544. \fi}
  18545. %
  18546. {\if\edition\pythonEd\pythonColor
  18547. \begin{lstlisting}
  18548. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18549. |$\Rightarrow$|
  18550. movq |$e'$|, |\itm{lhs'}|
  18551. sarq $3, |\itm{lhs'}|
  18552. \end{lstlisting}
  18553. \fi}
  18554. %
  18555. In the case for tuples and procedures, we zero out the rightmost 3
  18556. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18557. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18558. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18559. Finally, we apply \code{andq} with the tagged value to get the desired
  18560. result.
  18561. %
  18562. {\if\edition\racketEd
  18563. \begin{lstlisting}
  18564. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18565. |$\Rightarrow$|
  18566. movq $|$-8$|, |\itm{lhs'}|
  18567. andq |$e'$|, |\itm{lhs'}|
  18568. \end{lstlisting}
  18569. \fi}
  18570. %
  18571. {\if\edition\pythonEd\pythonColor
  18572. \begin{lstlisting}
  18573. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18574. |$\Rightarrow$|
  18575. movq $|$-8$|, |\itm{lhs'}|
  18576. andq |$e'$|, |\itm{lhs'}|
  18577. \end{lstlisting}
  18578. \fi}
  18579. %% \paragraph{Type Predicates} We leave it to the reader to
  18580. %% devise a sequence of instructions to implement the type predicates
  18581. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18582. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18583. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18584. operation combines the effect of \code{ValueOf} with accessing the
  18585. length of a tuple from the tag stored at the zero index of the tuple.
  18586. {\if\edition\racketEd
  18587. \begin{lstlisting}
  18588. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18589. |$\Longrightarrow$|
  18590. movq $|$-8$|, %r11
  18591. andq |$e_1'$|, %r11
  18592. movq 0(%r11), %r11
  18593. andq $126, %r11
  18594. sarq $1, %r11
  18595. movq %r11, |$\itm{lhs'}$|
  18596. \end{lstlisting}
  18597. \fi}
  18598. {\if\edition\pythonEd\pythonColor
  18599. \begin{lstlisting}
  18600. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18601. |$\Longrightarrow$|
  18602. movq $|$-8$|, %r11
  18603. andq |$e_1'$|, %r11
  18604. movq 0(%r11), %r11
  18605. andq $126, %r11
  18606. sarq $1, %r11
  18607. movq %r11, |$\itm{lhs'}$|
  18608. \end{lstlisting}
  18609. \fi}
  18610. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18611. This operation combines the effect of \code{ValueOf} with reading an
  18612. element of the tuple (see
  18613. section~\ref{sec:select-instructions-gc}). However, the index may be
  18614. an arbitrary atom, so instead of computing the offset at compile time,
  18615. we must generate instructions to compute the offset at runtime as
  18616. follows. Note the use of the new instruction \code{imulq}.
  18617. \begin{center}
  18618. \begin{minipage}{0.96\textwidth}
  18619. {\if\edition\racketEd
  18620. \begin{lstlisting}
  18621. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18622. |$\Longrightarrow$|
  18623. movq |$\neg 111$|, %r11
  18624. andq |$e_1'$|, %r11
  18625. movq |$e_2'$|, %rax
  18626. addq $1, %rax
  18627. imulq $8, %rax
  18628. addq %rax, %r11
  18629. movq 0(%r11) |$\itm{lhs'}$|
  18630. \end{lstlisting}
  18631. \fi}
  18632. %
  18633. {\if\edition\pythonEd\pythonColor
  18634. \begin{lstlisting}
  18635. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18636. |$\Longrightarrow$|
  18637. movq $|$-8$|, %r11
  18638. andq |$e_1'$|, %r11
  18639. movq |$e_2'$|, %rax
  18640. addq $1, %rax
  18641. imulq $8, %rax
  18642. addq %rax, %r11
  18643. movq 0(%r11) |$\itm{lhs'}$|
  18644. \end{lstlisting}
  18645. \fi}
  18646. \end{minipage}
  18647. \end{center}
  18648. % $ pacify font lock
  18649. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18650. %% The code generation for
  18651. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18652. %% analogous to the above translation for reading from a tuple.
  18653. \section{Register Allocation for \LangAny{} }
  18654. \label{sec:register-allocation-Lany}
  18655. \index{subject}{register allocation}
  18656. There is an interesting interaction between tagged values and garbage
  18657. collection that has an impact on register allocation. A variable of
  18658. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18659. that needs to be inspected and copied during garbage collection. Thus,
  18660. we need to treat variables of type \ANYTY{} in a similar way to
  18661. variables of tuple type for purposes of register allocation,
  18662. with particular attention to the following:
  18663. \begin{itemize}
  18664. \item If a variable of type \ANYTY{} is live during a function call,
  18665. then it must be spilled. This can be accomplished by changing
  18666. \code{build\_interference} to mark all variables of type \ANYTY{}
  18667. that are live after a \code{callq} to be interfering with all the
  18668. registers.
  18669. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18670. the root stack instead of the normal procedure call stack.
  18671. \end{itemize}
  18672. Another concern regarding the root stack is that the garbage collector
  18673. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18674. tagged value that points to a tuple, and (3) a tagged value that is
  18675. not a tuple. We enable this differentiation by choosing not to use the
  18676. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18677. reserved for identifying plain old pointers to tuples. That way, if
  18678. one of the first three bits is set, then we have a tagged value and
  18679. inspecting the tag can differentiate between tuples ($010$) and the
  18680. other kinds of values.
  18681. %% \begin{exercise}\normalfont
  18682. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18683. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18684. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18685. %% compiler on these new programs and all of your previously created test
  18686. %% programs.
  18687. %% \end{exercise}
  18688. \begin{exercise}\normalfont\normalsize
  18689. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18690. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18691. by removing type annotations. Add five more test programs that
  18692. specifically rely on the language being dynamically typed. That is,
  18693. they should not be legal programs in a statically typed language, but
  18694. nevertheless they should be valid \LangDyn{} programs that run to
  18695. completion without error.
  18696. \end{exercise}
  18697. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18698. for the compilation of \LangDyn{}.
  18699. \begin{figure}[bthp]
  18700. \begin{tcolorbox}[colback=white]
  18701. {\if\edition\racketEd
  18702. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18703. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18704. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18705. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18706. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18707. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18708. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18709. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18710. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18711. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18712. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18713. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18714. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18715. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18716. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18717. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18718. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18719. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18720. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18721. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18722. \path[->,bend left=15] (Lfun) edge [above] node
  18723. {\ttfamily\footnotesize shrink} (Lfun-2);
  18724. \path[->,bend left=15] (Lfun-2) edge [above] node
  18725. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18726. \path[->,bend left=15] (Lfun-3) edge [above] node
  18727. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18728. \path[->,bend left=15] (Lfun-4) edge [left] node
  18729. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18730. \path[->,bend left=15] (Lfun-5) edge [below] node
  18731. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18732. \path[->,bend left=15] (Lfun-6) edge [below] node
  18733. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18734. \path[->,bend right=15] (Lfun-7) edge [above] node
  18735. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18736. \path[->,bend right=15] (F1-2) edge [right] node
  18737. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18738. \path[->,bend right=15] (F1-3) edge [below] node
  18739. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18740. \path[->,bend right=15] (F1-4) edge [below] node
  18741. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18742. \path[->,bend left=15] (F1-5) edge [above] node
  18743. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18744. \path[->,bend left=10] (F1-6) edge [below] node
  18745. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18746. \path[->,bend left=15] (C3-2) edge [right] node
  18747. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18748. \path[->,bend right=15] (x86-2) edge [right] node
  18749. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18750. \path[->,bend right=15] (x86-2-1) edge [below] node
  18751. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18752. \path[->,bend right=15] (x86-2-2) edge [right] node
  18753. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18754. \path[->,bend left=15] (x86-3) edge [above] node
  18755. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18756. \path[->,bend left=15] (x86-4) edge [right] node
  18757. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18758. \end{tikzpicture}
  18759. \fi}
  18760. {\if\edition\pythonEd\pythonColor
  18761. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18762. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18763. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18764. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18765. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18766. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18767. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18768. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18769. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18770. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18771. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18772. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18773. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18774. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18775. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18776. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18777. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18778. \path[->,bend left=15] (Lfun) edge [above] node
  18779. {\ttfamily\footnotesize shrink} (Lfun-2);
  18780. \path[->,bend left=15] (Lfun-2) edge [above] node
  18781. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18782. \path[->,bend left=15] (Lfun-3) edge [above] node
  18783. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18784. \path[->,bend left=15] (Lfun-4) edge [left] node
  18785. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18786. \path[->,bend left=15] (Lfun-5) edge [below] node
  18787. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18788. \path[->,bend right=15] (Lfun-6) edge [above] node
  18789. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18790. \path[->,bend right=15] (Lfun-7) edge [above] node
  18791. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18792. \path[->,bend right=15] (F1-2) edge [right] node
  18793. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18794. \path[->,bend right=15] (F1-3) edge [below] node
  18795. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18796. \path[->,bend left=15] (F1-5) edge [above] node
  18797. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18798. \path[->,bend left=10] (F1-6) edge [below] node
  18799. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18800. \path[->,bend right=15] (C3-2) edge [right] node
  18801. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18802. \path[->,bend right=15] (x86-2) edge [below] node
  18803. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18804. \path[->,bend right=15] (x86-3) edge [below] node
  18805. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18806. \path[->,bend left=15] (x86-4) edge [above] node
  18807. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18808. \end{tikzpicture}
  18809. \fi}
  18810. \end{tcolorbox}
  18811. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18812. \label{fig:Ldyn-passes}
  18813. \end{figure}
  18814. % Further Reading
  18815. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18816. %% {\if\edition\pythonEd\pythonColor
  18817. %% \chapter{Objects}
  18818. %% \label{ch:Lobject}
  18819. %% \index{subject}{objects}
  18820. %% \index{subject}{classes}
  18821. %% \setcounter{footnote}{0}
  18822. %% \fi}
  18823. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18824. \chapter{Gradual Typing}
  18825. \label{ch:Lgrad}
  18826. \index{subject}{gradual typing}
  18827. \setcounter{footnote}{0}
  18828. This chapter studies the language \LangGrad{}, in which the programmer
  18829. can choose between static and dynamic type checking in different parts
  18830. of a program, thereby mixing the statically typed \LangLam{} language
  18831. with the dynamically typed \LangDyn{}. There are several approaches to
  18832. mixing static and dynamic typing, including multilanguage
  18833. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18834. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18835. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18836. programmer controls the amount of static versus dynamic checking by
  18837. adding or removing type annotations on parameters and
  18838. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18839. The definition of the concrete syntax of \LangGrad{} is shown in
  18840. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18841. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18842. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18843. annotations are optional, which is specified in the grammar using the
  18844. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18845. annotations are not optional, but we use the \CANYTY{} type when a type
  18846. annotation is absent.
  18847. %
  18848. Both the type checker and the interpreter for \LangGrad{} require some
  18849. interesting changes to enable gradual typing, which we discuss in the
  18850. next two sections.
  18851. \newcommand{\LgradGrammarRacket}{
  18852. \begin{array}{lcl}
  18853. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18854. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18855. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18856. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18857. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18858. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18859. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18860. \end{array}
  18861. }
  18862. \newcommand{\LgradASTRacket}{
  18863. \begin{array}{lcl}
  18864. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18865. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18866. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18867. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18868. \itm{op} &::=& \code{procedure-arity} \\
  18869. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18870. \end{array}
  18871. }
  18872. \newcommand{\LgradGrammarPython}{
  18873. \begin{array}{lcl}
  18874. \Type &::=& \key{Any}
  18875. \MID \key{int}
  18876. \MID \key{bool}
  18877. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18878. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18879. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18880. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18881. \MID \CARITY{\Exp} \\
  18882. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18883. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18884. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18885. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18886. \end{array}
  18887. }
  18888. \newcommand{\LgradASTPython}{
  18889. \begin{array}{lcl}
  18890. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18891. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18892. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18893. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18894. &\MID& \ARITY{\Exp} \\
  18895. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18896. \MID \RETURN{\Exp} \\
  18897. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18898. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18899. \end{array}
  18900. }
  18901. \begin{figure}[tbp]
  18902. \centering
  18903. \begin{tcolorbox}[colback=white]
  18904. \vspace{-5pt}
  18905. \small
  18906. {\if\edition\racketEd
  18907. \[
  18908. \begin{array}{l}
  18909. \gray{\LintGrammarRacket{}} \\ \hline
  18910. \gray{\LvarGrammarRacket{}} \\ \hline
  18911. \gray{\LifGrammarRacket{}} \\ \hline
  18912. \gray{\LwhileGrammarRacket} \\ \hline
  18913. \gray{\LtupGrammarRacket} \\ \hline
  18914. \LgradGrammarRacket \\
  18915. \begin{array}{lcl}
  18916. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18917. \end{array}
  18918. \end{array}
  18919. \]
  18920. \fi}
  18921. {\if\edition\pythonEd\pythonColor
  18922. \[
  18923. \begin{array}{l}
  18924. \gray{\LintGrammarPython{}} \\ \hline
  18925. \gray{\LvarGrammarPython{}} \\ \hline
  18926. \gray{\LifGrammarPython{}} \\ \hline
  18927. \gray{\LwhileGrammarPython} \\ \hline
  18928. \gray{\LtupGrammarPython} \\ \hline
  18929. \LgradGrammarPython \\
  18930. \begin{array}{lcl}
  18931. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18932. \end{array}
  18933. \end{array}
  18934. \]
  18935. \fi}
  18936. \end{tcolorbox}
  18937. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18938. \label{fig:Lgrad-concrete-syntax}
  18939. \index{subject}{L?@\LangGrad{} concrete syntax}
  18940. \end{figure}
  18941. \begin{figure}[tbp]
  18942. \centering
  18943. \begin{tcolorbox}[colback=white]
  18944. \small
  18945. {\if\edition\racketEd
  18946. \[
  18947. \begin{array}{l}
  18948. \gray{\LintOpAST} \\ \hline
  18949. \gray{\LvarASTRacket{}} \\ \hline
  18950. \gray{\LifASTRacket{}} \\ \hline
  18951. \gray{\LwhileASTRacket{}} \\ \hline
  18952. \gray{\LtupASTRacket{}} \\ \hline
  18953. \LgradASTRacket \\
  18954. \begin{array}{lcl}
  18955. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18956. \end{array}
  18957. \end{array}
  18958. \]
  18959. \fi}
  18960. {\if\edition\pythonEd\pythonColor
  18961. \[
  18962. \begin{array}{l}
  18963. \gray{\LintASTPython{}} \\ \hline
  18964. \gray{\LvarASTPython{}} \\ \hline
  18965. \gray{\LifASTPython{}} \\ \hline
  18966. \gray{\LwhileASTPython} \\ \hline
  18967. \gray{\LtupASTPython} \\ \hline
  18968. \LgradASTPython \\
  18969. \begin{array}{lcl}
  18970. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18971. \end{array}
  18972. \end{array}
  18973. \]
  18974. \fi}
  18975. \end{tcolorbox}
  18976. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18977. \label{fig:Lgrad-syntax}
  18978. \index{subject}{L?@\LangGrad{} abstract syntax}
  18979. \end{figure}
  18980. % TODO: more road map -Jeremy
  18981. %\clearpage
  18982. \section{Type Checking \LangGrad{}}
  18983. \label{sec:gradual-type-check}
  18984. We begin by discussing the type checking of a partially typed variant
  18985. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18986. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18987. statically typed, so there is nothing special happening there with
  18988. respect to type checking. On the other hand, the \code{inc} function
  18989. does not have type annotations, so the type checker assigns the type
  18990. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18991. \code{+} operator inside \code{inc}. It expects both arguments to have
  18992. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18993. a gradually typed language, such differences are allowed so long as
  18994. the types are \emph{consistent}; that is, they are equal except in
  18995. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18996. is consistent with every other type. Figure~\ref{fig:consistent}
  18997. shows the definition of the
  18998. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18999. %
  19000. So the type checker allows the \code{+} operator to be applied
  19001. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  19002. %
  19003. Next consider the call to the \code{map} function shown in
  19004. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  19005. tuple. The \code{inc} function has type
  19006. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  19007. but parameter \code{f} of \code{map} has type
  19008. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19009. The type checker for \LangGrad{} accepts this call because the two types are
  19010. consistent.
  19011. \begin{figure}[hbtp]
  19012. % gradual_test_9.rkt
  19013. \begin{tcolorbox}[colback=white]
  19014. {\if\edition\racketEd
  19015. \begin{lstlisting}
  19016. (define (map [f : (Integer -> Integer)]
  19017. [v : (Vector Integer Integer)])
  19018. : (Vector Integer Integer)
  19019. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19020. (define (inc x) (+ x 1))
  19021. (vector-ref (map inc (vector 0 41)) 1)
  19022. \end{lstlisting}
  19023. \fi}
  19024. {\if\edition\pythonEd\pythonColor
  19025. \begin{lstlisting}
  19026. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19027. return f(v[0]), f(v[1])
  19028. def inc(x):
  19029. return x + 1
  19030. t = map(inc, (0, 41))
  19031. print(t[1])
  19032. \end{lstlisting}
  19033. \fi}
  19034. \end{tcolorbox}
  19035. \caption{A partially typed version of the \code{map} example.}
  19036. \label{fig:gradual-map}
  19037. \end{figure}
  19038. \begin{figure}[tbp]
  19039. \begin{tcolorbox}[colback=white]
  19040. {\if\edition\racketEd
  19041. \begin{lstlisting}
  19042. (define/public (consistent? t1 t2)
  19043. (match* (t1 t2)
  19044. [('Integer 'Integer) #t]
  19045. [('Boolean 'Boolean) #t]
  19046. [('Void 'Void) #t]
  19047. [('Any t2) #t]
  19048. [(t1 'Any) #t]
  19049. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19050. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  19051. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19052. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  19053. (consistent? rt1 rt2))]
  19054. [(other wise) #f]))
  19055. \end{lstlisting}
  19056. \fi}
  19057. {\if\edition\pythonEd\pythonColor
  19058. \begin{lstlisting}
  19059. def consistent(self, t1, t2):
  19060. match (t1, t2):
  19061. case (AnyType(), _):
  19062. return True
  19063. case (_, AnyType()):
  19064. return True
  19065. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19066. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  19067. case (TupleType(ts1), TupleType(ts2)):
  19068. return all(map(self.consistent, ts1, ts2))
  19069. case (_, _):
  19070. return t1 == t2
  19071. \end{lstlisting}
  19072. \fi}
  19073. \vspace{-5pt}
  19074. \end{tcolorbox}
  19075. \caption{The consistency method on types.}
  19076. \label{fig:consistent}
  19077. \end{figure}
  19078. It is also helpful to consider how gradual typing handles programs with an
  19079. error, such as applying \code{map} to a function that sometimes
  19080. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  19081. type checker for \LangGrad{} accepts this program because the type of
  19082. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  19083. \code{map}; that is,
  19084. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  19085. is consistent with
  19086. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19087. One might say that a gradual type checker is optimistic in that it
  19088. accepts programs that might execute without a runtime type error.
  19089. %
  19090. The definition of the type checker for \LangGrad{} is shown in
  19091. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  19092. and \ref{fig:type-check-Lgradual-3}.
  19093. %% \begin{figure}[tp]
  19094. %% \centering
  19095. %% \fbox{
  19096. %% \begin{minipage}{0.96\textwidth}
  19097. %% \small
  19098. %% \[
  19099. %% \begin{array}{lcl}
  19100. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  19101. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  19102. %% \end{array}
  19103. %% \]
  19104. %% \end{minipage}
  19105. %% }
  19106. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  19107. %% \label{fig:Lgrad-prime-syntax}
  19108. %% \end{figure}
  19109. \begin{figure}[tbp]
  19110. \begin{tcolorbox}[colback=white]
  19111. {\if\edition\racketEd
  19112. \begin{lstlisting}
  19113. (define (map [f : (Integer -> Integer)]
  19114. [v : (Vector Integer Integer)])
  19115. : (Vector Integer Integer)
  19116. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19117. (define (inc x) (+ x 1))
  19118. (define (true) #t)
  19119. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19120. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19121. \end{lstlisting}
  19122. \fi}
  19123. {\if\edition\pythonEd\pythonColor
  19124. \begin{lstlisting}
  19125. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19126. return f(v[0]), f(v[1])
  19127. def inc(x):
  19128. return x + 1
  19129. def true():
  19130. return True
  19131. def maybe_inc(x):
  19132. return inc(x) if input_int() == 0 else true()
  19133. t = map(maybe_inc, (0, 41))
  19134. print(t[1])
  19135. \end{lstlisting}
  19136. \fi}
  19137. \vspace{-5pt}
  19138. \end{tcolorbox}
  19139. \caption{A variant of the \code{map} example with an error.}
  19140. \label{fig:map-maybe_inc}
  19141. \end{figure}
  19142. Running this program with input \code{1} triggers an
  19143. error when the \code{maybe\_inc} function returns
  19144. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19145. performs checking at runtime to ensure the integrity of the static
  19146. types, such as the
  19147. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19148. annotation on
  19149. parameter \code{f} of \code{map}.
  19150. Here we give a preview of how the runtime checking is accomplished;
  19151. the following sections provide the details.
  19152. The runtime checking is carried out by a new \code{Cast} AST node that
  19153. is generated in a new pass named \code{cast\_insert}. The output of
  19154. \code{cast\_insert} is a program in the \LangCast{} language, which
  19155. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19156. %
  19157. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19158. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19159. inserted every time the type checker encounters two types that are
  19160. consistent but not equal. In the \code{inc} function, \code{x} is
  19161. cast to \INTTY{} and the result of the \code{+} is cast to
  19162. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19163. is cast from
  19164. \racket{\code{(Any -> Any)}}
  19165. \python{\code{Callable[[Any], Any]}}
  19166. to
  19167. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19168. %
  19169. In the next section we see how to interpret the \code{Cast} node.
  19170. \begin{figure}[btp]
  19171. \begin{tcolorbox}[colback=white]
  19172. {\if\edition\racketEd
  19173. \begin{lstlisting}
  19174. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19175. : (Vector Integer Integer)
  19176. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19177. (define (inc [x : Any]) : Any
  19178. (cast (+ (cast x Any Integer) 1) Integer Any))
  19179. (define (true) : Any (cast #t Boolean Any))
  19180. (define (maybe_inc [x : Any]) : Any
  19181. (if (eq? 0 (read)) (inc x) (true)))
  19182. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19183. (vector 0 41)) 0)
  19184. \end{lstlisting}
  19185. \fi}
  19186. {\if\edition\pythonEd\pythonColor
  19187. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19188. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19189. return f(v[0]), f(v[1])
  19190. def inc(x : Any) -> Any:
  19191. return Cast(Cast(x, Any, int) + 1, int, Any)
  19192. def true() -> Any:
  19193. return Cast(True, bool, Any)
  19194. def maybe_inc(x : Any) -> Any:
  19195. return inc(x) if input_int() == 0 else true()
  19196. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19197. (0, 41))
  19198. print(t[1])
  19199. \end{lstlisting}
  19200. \fi}
  19201. \vspace{-5pt}
  19202. \end{tcolorbox}
  19203. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19204. and \code{maybe\_inc} example.}
  19205. \label{fig:map-cast}
  19206. \end{figure}
  19207. {\if\edition\pythonEd\pythonColor
  19208. \begin{figure}[tbp]
  19209. \begin{tcolorbox}[colback=white]
  19210. \begin{lstlisting}
  19211. class TypeCheckLgrad(TypeCheckLlambda):
  19212. def type_check_exp(self, e, env) -> Type:
  19213. match e:
  19214. case Name(id):
  19215. return env[id]
  19216. case Constant(value) if isinstance(value, bool):
  19217. return BoolType()
  19218. case Constant(value) if isinstance(value, int):
  19219. return IntType()
  19220. case Call(Name('input_int'), []):
  19221. return IntType()
  19222. case BinOp(left, op, right):
  19223. left_type = self.type_check_exp(left, env)
  19224. self.check_consistent(left_type, IntType(), left)
  19225. right_type = self.type_check_exp(right, env)
  19226. self.check_consistent(right_type, IntType(), right)
  19227. return IntType()
  19228. case IfExp(test, body, orelse):
  19229. test_t = self.type_check_exp(test, env)
  19230. self.check_consistent(test_t, BoolType(), test)
  19231. body_t = self.type_check_exp(body, env)
  19232. orelse_t = self.type_check_exp(orelse, env)
  19233. self.check_consistent(body_t, orelse_t, e)
  19234. return self.join_types(body_t, orelse_t)
  19235. case Call(func, args):
  19236. func_t = self.type_check_exp(func, env)
  19237. args_t = [self.type_check_exp(arg, env) for arg in args]
  19238. match func_t:
  19239. case FunctionType(params_t, return_t) \
  19240. if len(params_t) == len(args_t):
  19241. for (arg_t, param_t) in zip(args_t, params_t):
  19242. self.check_consistent(param_t, arg_t, e)
  19243. return return_t
  19244. case AnyType():
  19245. return AnyType()
  19246. case _:
  19247. raise Exception('type_check_exp: in call, unexpected '
  19248. + repr(func_t))
  19249. ...
  19250. case _:
  19251. raise Exception('type_check_exp: unexpected ' + repr(e))
  19252. \end{lstlisting}
  19253. \end{tcolorbox}
  19254. \caption{Type checking expressions in the \LangGrad{} language.}
  19255. \label{fig:type-check-Lgradual-1}
  19256. \end{figure}
  19257. \begin{figure}[tbp]
  19258. \begin{tcolorbox}[colback=white]
  19259. \begin{lstlisting}
  19260. def check_exp(self, e, expected_ty, env):
  19261. match e:
  19262. case Lambda(params, body):
  19263. match expected_ty:
  19264. case FunctionType(params_t, return_t):
  19265. new_env = env.copy().update(zip(params, params_t))
  19266. e.has_type = expected_ty
  19267. body_ty = self.type_check_exp(body, new_env)
  19268. self.check_consistent(body_ty, return_t)
  19269. case AnyType():
  19270. new_env = env.copy().update((p, AnyType()) for p in params)
  19271. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19272. body_ty = self.type_check_exp(body, new_env)
  19273. case _:
  19274. raise Exception('lambda is not of type ' + str(expected_ty))
  19275. case _:
  19276. e_ty = self.type_check_exp(e, env)
  19277. self.check_consistent(e_ty, expected_ty, e)
  19278. \end{lstlisting}
  19279. \end{tcolorbox}
  19280. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19281. \label{fig:type-check-Lgradual-2}
  19282. \end{figure}
  19283. \begin{figure}[tbp]
  19284. \begin{tcolorbox}[colback=white]
  19285. \begin{lstlisting}
  19286. def type_check_stmt(self, s, env, return_type):
  19287. match s:
  19288. case Assign([Name(id)], value):
  19289. value_ty = self.type_check_exp(value, env)
  19290. if id in env:
  19291. self.check_consistent(env[id], value_ty, value)
  19292. else:
  19293. env[id] = value_ty
  19294. ...
  19295. case _:
  19296. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19297. def type_check_stmts(self, ss, env, return_type):
  19298. for s in ss:
  19299. self.type_check_stmt(s, env, return_type)
  19300. \end{lstlisting}
  19301. \end{tcolorbox}
  19302. \caption{Type checking statements in the \LangGrad{} language.}
  19303. \label{fig:type-check-Lgradual-3}
  19304. \end{figure}
  19305. \clearpage
  19306. \begin{figure}[tbp]
  19307. \begin{tcolorbox}[colback=white]
  19308. \begin{lstlisting}
  19309. def join_types(self, t1, t2):
  19310. match (t1, t2):
  19311. case (AnyType(), _):
  19312. return t2
  19313. case (_, AnyType()):
  19314. return t1
  19315. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19316. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19317. self.join_types(rt1,rt2))
  19318. case (TupleType(ts1), TupleType(ts2)):
  19319. return TupleType(list(map(self.join_types, ts1, ts2)))
  19320. case (_, _):
  19321. return t1
  19322. def check_consistent(self, t1, t2, e):
  19323. if not self.consistent(t1, t2):
  19324. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19325. + repr(t2) + ' in ' + repr(e))
  19326. \end{lstlisting}
  19327. \end{tcolorbox}
  19328. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19329. \label{fig:type-check-Lgradual-aux}
  19330. \end{figure}
  19331. \fi}
  19332. {\if\edition\racketEd
  19333. \begin{figure}[tbp]
  19334. \begin{tcolorbox}[colback=white]
  19335. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19336. (define/override (type-check-exp env)
  19337. (lambda (e)
  19338. (define recur (type-check-exp env))
  19339. (match e
  19340. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19341. (define-values (new-es ts)
  19342. (for/lists (exprs types) ([e es])
  19343. (recur e)))
  19344. (define t-ret (type-check-op op ts e))
  19345. (values (Prim op new-es) t-ret)]
  19346. [(Prim 'eq? (list e1 e2))
  19347. (define-values (e1^ t1) (recur e1))
  19348. (define-values (e2^ t2) (recur e2))
  19349. (check-consistent? t1 t2 e)
  19350. (define T (meet t1 t2))
  19351. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19352. [(Prim 'and (list e1 e2))
  19353. (recur (If e1 e2 (Bool #f)))]
  19354. [(Prim 'or (list e1 e2))
  19355. (define tmp (gensym 'tmp))
  19356. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19357. [(If e1 e2 e3)
  19358. (define-values (e1^ T1) (recur e1))
  19359. (define-values (e2^ T2) (recur e2))
  19360. (define-values (e3^ T3) (recur e3))
  19361. (check-consistent? T1 'Boolean e)
  19362. (check-consistent? T2 T3 e)
  19363. (define Tif (meet T2 T3))
  19364. (values (If e1^ e2^ e3^) Tif)]
  19365. [(SetBang x e1)
  19366. (define-values (e1^ T1) (recur e1))
  19367. (define varT (dict-ref env x))
  19368. (check-consistent? T1 varT e)
  19369. (values (SetBang x e1^) 'Void)]
  19370. [(WhileLoop e1 e2)
  19371. (define-values (e1^ T1) (recur e1))
  19372. (check-consistent? T1 'Boolean e)
  19373. (define-values (e2^ T2) ((type-check-exp env) e2))
  19374. (values (WhileLoop e1^ e2^) 'Void)]
  19375. [(Prim 'vector-length (list e1))
  19376. (define-values (e1^ t) (recur e1))
  19377. (match t
  19378. [`(Vector ,ts ...)
  19379. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19380. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19381. \end{lstlisting}
  19382. \end{tcolorbox}
  19383. \caption{Type checker for the \LangGrad{} language, part 1.}
  19384. \label{fig:type-check-Lgradual-1}
  19385. \end{figure}
  19386. \begin{figure}[tbp]
  19387. \begin{tcolorbox}[colback=white]
  19388. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19389. [(Prim 'vector-ref (list e1 e2))
  19390. (define-values (e1^ t1) (recur e1))
  19391. (define-values (e2^ t2) (recur e2))
  19392. (check-consistent? t2 'Integer e)
  19393. (match t1
  19394. [`(Vector ,ts ...)
  19395. (match e2^
  19396. [(Int i)
  19397. (unless (and (0 . <= . i) (i . < . (length ts)))
  19398. (error 'type-check "invalid index ~a in ~a" i e))
  19399. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19400. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19401. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19402. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19403. [(Prim 'vector-set! (list e1 e2 e3) )
  19404. (define-values (e1^ t1) (recur e1))
  19405. (define-values (e2^ t2) (recur e2))
  19406. (define-values (e3^ t3) (recur e3))
  19407. (check-consistent? t2 'Integer e)
  19408. (match t1
  19409. [`(Vector ,ts ...)
  19410. (match e2^
  19411. [(Int i)
  19412. (unless (and (0 . <= . i) (i . < . (length ts)))
  19413. (error 'type-check "invalid index ~a in ~a" i e))
  19414. (check-consistent? (list-ref ts i) t3 e)
  19415. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19416. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19417. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19418. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19419. [(Apply e1 e2s)
  19420. (define-values (e1^ T1) (recur e1))
  19421. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19422. (match T1
  19423. [`(,T1ps ... -> ,T1rt)
  19424. (for ([T2 T2s] [Tp T1ps])
  19425. (check-consistent? T2 Tp e))
  19426. (values (Apply e1^ e2s^) T1rt)]
  19427. [`Any (values (Apply e1^ e2s^) 'Any)]
  19428. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19429. [(Lambda params Tr e1)
  19430. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19431. (match p
  19432. [`[,x : ,T] (values x T)]
  19433. [(? symbol? x) (values x 'Any)])))
  19434. (define-values (e1^ T1)
  19435. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19436. (check-consistent? Tr T1 e)
  19437. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19438. `(,@Ts -> ,Tr))]
  19439. [else ((super type-check-exp env) e)]
  19440. )))
  19441. \end{lstlisting}
  19442. \end{tcolorbox}
  19443. \caption{Type checker for the \LangGrad{} language, part 2.}
  19444. \label{fig:type-check-Lgradual-2}
  19445. \end{figure}
  19446. \begin{figure}[tbp]
  19447. \begin{tcolorbox}[colback=white]
  19448. \begin{lstlisting}
  19449. (define/override (type-check-def env)
  19450. (lambda (e)
  19451. (match e
  19452. [(Def f params rt info body)
  19453. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19454. (match p
  19455. [`[,x : ,T] (values x T)]
  19456. [(? symbol? x) (values x 'Any)])))
  19457. (define new-env (append (map cons xs ps) env))
  19458. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19459. (check-consistent? ty^ rt e)
  19460. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19461. [else (error 'type-check "ill-formed function definition ~a" e)]
  19462. )))
  19463. (define/override (type-check-program e)
  19464. (match e
  19465. [(Program info body)
  19466. (define-values (body^ ty) ((type-check-exp '()) body))
  19467. (check-consistent? ty 'Integer e)
  19468. (ProgramDefsExp info '() body^)]
  19469. [(ProgramDefsExp info ds body)
  19470. (define new-env (for/list ([d ds])
  19471. (cons (Def-name d) (fun-def-type d))))
  19472. (define ds^ (for/list ([d ds])
  19473. ((type-check-def new-env) d)))
  19474. (define-values (body^ ty) ((type-check-exp new-env) body))
  19475. (check-consistent? ty 'Integer e)
  19476. (ProgramDefsExp info ds^ body^)]
  19477. [else (super type-check-program e)]))
  19478. \end{lstlisting}
  19479. \end{tcolorbox}
  19480. \caption{Type checker for the \LangGrad{} language, part 3.}
  19481. \label{fig:type-check-Lgradual-3}
  19482. \end{figure}
  19483. \begin{figure}[tbp]
  19484. \begin{tcolorbox}[colback=white]
  19485. \begin{lstlisting}
  19486. (define/public (join t1 t2)
  19487. (match* (t1 t2)
  19488. [('Integer 'Integer) 'Integer]
  19489. [('Boolean 'Boolean) 'Boolean]
  19490. [('Void 'Void) 'Void]
  19491. [('Any t2) t2]
  19492. [(t1 'Any) t1]
  19493. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19494. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19495. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19496. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19497. -> ,(join rt1 rt2))]))
  19498. (define/public (meet t1 t2)
  19499. (match* (t1 t2)
  19500. [('Integer 'Integer) 'Integer]
  19501. [('Boolean 'Boolean) 'Boolean]
  19502. [('Void 'Void) 'Void]
  19503. [('Any t2) 'Any]
  19504. [(t1 'Any) 'Any]
  19505. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19506. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19507. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19508. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19509. -> ,(meet rt1 rt2))]))
  19510. (define/public (check-consistent? t1 t2 e)
  19511. (unless (consistent? t1 t2)
  19512. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19513. (define explicit-prim-ops
  19514. (set-union
  19515. (type-predicates)
  19516. (set 'procedure-arity 'eq? 'not 'and 'or
  19517. 'vector 'vector-length 'vector-ref 'vector-set!
  19518. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19519. (define/override (fun-def-type d)
  19520. (match d
  19521. [(Def f params rt info body)
  19522. (define ps
  19523. (for/list ([p params])
  19524. (match p
  19525. [`[,x : ,T] T]
  19526. [(? symbol?) 'Any]
  19527. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19528. `(,@ps -> ,rt)]
  19529. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19530. \end{lstlisting}
  19531. \end{tcolorbox}
  19532. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19533. \label{fig:type-check-Lgradual-aux}
  19534. \end{figure}
  19535. \fi}
  19536. \section{Interpreting \LangCast{} }
  19537. \label{sec:interp-casts}
  19538. The runtime behavior of casts involving simple types such as
  19539. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19540. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19541. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19542. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19543. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19544. operator, by checking the value's tag and either retrieving
  19545. the underlying integer or signaling an error if the tag is not the
  19546. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19547. %
  19548. Things get more interesting with casts involving
  19549. \racket{function and tuple types}\python{function, tuple, and array types}.
  19550. Consider the cast of the function \code{maybe\_inc} from
  19551. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19552. to
  19553. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19554. shown in figure~\ref{fig:map-maybe_inc}.
  19555. When the \code{maybe\_inc} function flows through
  19556. this cast at runtime, we don't know whether it will return
  19557. an integer, because that depends on the input from the user.
  19558. The \LangCast{} interpreter therefore delays the checking
  19559. of the cast until the function is applied. To do so it
  19560. wraps \code{maybe\_inc} in a new function that casts its parameter
  19561. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19562. casts the return value from \CANYTY{} to \INTTY{}.
  19563. {\if\edition\pythonEd\pythonColor
  19564. %
  19565. There are further complications regarding casts on mutable data,
  19566. such as the \code{list} type introduced in
  19567. the challenge assignment of section~\ref{sec:arrays}.
  19568. %
  19569. \fi}
  19570. %
  19571. Consider the example presented in figure~\ref{fig:map-bang} that
  19572. defines a partially typed version of \code{map} whose parameter
  19573. \code{v} has type
  19574. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19575. and that updates \code{v} in place
  19576. instead of returning a new tuple. We name this function
  19577. \code{map\_inplace}. We apply \code{map\_inplace} to
  19578. \racket{a tuple}\python{an array} of integers, so the type checker
  19579. inserts a cast from
  19580. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19581. to
  19582. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19583. A naive way for the \LangCast{} interpreter to cast between
  19584. \racket{tuple}\python{array} types would be to build a new
  19585. \racket{tuple}\python{array} whose elements are the result
  19586. of casting each of the original elements to the target
  19587. type. However, this approach is not valid for mutable data structures.
  19588. In the example of figure~\ref{fig:map-bang},
  19589. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19590. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19591. the original one.
  19592. Instead the interpreter needs to create a new kind of value, a
  19593. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19594. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19595. and then applies a
  19596. cast to the resulting value. On a write, the proxy casts the argument
  19597. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19598. \racket{
  19599. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19600. \code{0} from \INTTY{} to \CANYTY{}.
  19601. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19602. from \CANYTY{} to \INTTY{}.
  19603. }
  19604. \python{
  19605. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19606. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19607. For the subscript on the left of the assignment,
  19608. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19609. }
  19610. Finally we consider casts between the \CANYTY{} type and higher-order types
  19611. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19612. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19613. have a type annotation, so it is given type \CANYTY{}. In the call to
  19614. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19615. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19616. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19617. \code{Inject}, but that doesn't work because
  19618. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19619. a flat type. Instead, we must first cast to
  19620. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19621. and then inject to \CANYTY{}.
  19622. \begin{figure}[tbp]
  19623. \begin{tcolorbox}[colback=white]
  19624. % gradual_test_11.rkt
  19625. {\if\edition\racketEd
  19626. \begin{lstlisting}
  19627. (define (map_inplace [f : (Any -> Any)]
  19628. [v : (Vector Any Any)]) : Void
  19629. (begin
  19630. (vector-set! v 0 (f (vector-ref v 0)))
  19631. (vector-set! v 1 (f (vector-ref v 1)))))
  19632. (define (inc x) (+ x 1))
  19633. (let ([v (vector 0 41)])
  19634. (begin (map_inplace inc v) (vector-ref v 1)))
  19635. \end{lstlisting}
  19636. \fi}
  19637. {\if\edition\pythonEd\pythonColor
  19638. \begin{lstlisting}
  19639. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19640. i = 0
  19641. while i != len(v):
  19642. v[i] = f(v[i])
  19643. i = i + 1
  19644. def inc(x : int) -> int:
  19645. return x + 1
  19646. v = [0, 41]
  19647. map_inplace(inc, v)
  19648. print(v[1])
  19649. \end{lstlisting}
  19650. \fi}
  19651. \end{tcolorbox}
  19652. \caption{An example involving casts on arrays.}
  19653. \label{fig:map-bang}
  19654. \end{figure}
  19655. \begin{figure}[btp]
  19656. \begin{tcolorbox}[colback=white]
  19657. {\if\edition\racketEd
  19658. \begin{lstlisting}
  19659. (define (map_inplace [f : (Any -> Any)] v) : Void
  19660. (begin
  19661. (vector-set! v 0 (f (vector-ref v 0)))
  19662. (vector-set! v 1 (f (vector-ref v 1)))))
  19663. (define (inc x) (+ x 1))
  19664. (let ([v (vector 0 41)])
  19665. (begin (map_inplace inc v) (vector-ref v 1)))
  19666. \end{lstlisting}
  19667. \fi}
  19668. {\if\edition\pythonEd\pythonColor
  19669. \begin{lstlisting}
  19670. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19671. i = 0
  19672. while i != len(v):
  19673. v[i] = f(v[i])
  19674. i = i + 1
  19675. def inc(x):
  19676. return x + 1
  19677. v = [0, 41]
  19678. map_inplace(inc, v)
  19679. print(v[1])
  19680. \end{lstlisting}
  19681. \fi}
  19682. \end{tcolorbox}
  19683. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19684. \label{fig:map-any}
  19685. \end{figure}
  19686. \begin{figure}[tbp]
  19687. \begin{tcolorbox}[colback=white]
  19688. {\if\edition\racketEd
  19689. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19690. (define/public (apply_cast v s t)
  19691. (match* (s t)
  19692. [(t1 t2) #:when (equal? t1 t2) v]
  19693. [('Any t2)
  19694. (match t2
  19695. [`(,ts ... -> ,rt)
  19696. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19697. (define v^ (apply-project v any->any))
  19698. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19699. [`(Vector ,ts ...)
  19700. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19701. (define v^ (apply-project v vec-any))
  19702. (apply_cast v^ vec-any `(Vector ,@ts))]
  19703. [else (apply-project v t2)])]
  19704. [(t1 'Any)
  19705. (match t1
  19706. [`(,ts ... -> ,rt)
  19707. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19708. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19709. (apply-inject v^ (any-tag any->any))]
  19710. [`(Vector ,ts ...)
  19711. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19712. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19713. (apply-inject v^ (any-tag vec-any))]
  19714. [else (apply-inject v (any-tag t1))])]
  19715. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19716. (define x (gensym 'x))
  19717. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19718. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19719. (define cast-writes
  19720. (for/list ([t1 ts1] [t2 ts2])
  19721. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19722. `(vector-proxy ,(vector v (apply vector cast-reads)
  19723. (apply vector cast-writes)))]
  19724. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19725. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19726. `(function ,xs ,(Cast
  19727. (Apply (Value v)
  19728. (for/list ([x xs][t1 ts1][t2 ts2])
  19729. (Cast (Var x) t2 t1)))
  19730. rt1 rt2) ())]
  19731. ))
  19732. \end{lstlisting}
  19733. \fi}
  19734. {\if\edition\pythonEd\pythonColor
  19735. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19736. def apply_cast(self, value, src, tgt):
  19737. match (src, tgt):
  19738. case (AnyType(), FunctionType(ps2, rt2)):
  19739. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19740. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19741. case (AnyType(), TupleType(ts2)):
  19742. anytup = TupleType([AnyType() for t1 in ts2])
  19743. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19744. case (AnyType(), ListType(t2)):
  19745. anylist = ListType([AnyType() for t1 in ts2])
  19746. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19747. case (AnyType(), AnyType()):
  19748. return value
  19749. case (AnyType(), _):
  19750. return self.apply_project(value, tgt)
  19751. case (FunctionType(ps1,rt1), AnyType()):
  19752. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19753. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19754. case (TupleType(ts1), AnyType()):
  19755. anytup = TupleType([AnyType() for t1 in ts1])
  19756. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19757. case (ListType(t1), AnyType()):
  19758. anylist = ListType(AnyType())
  19759. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19760. case (_, AnyType()):
  19761. return self.apply_inject(value, src)
  19762. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19763. params = [generate_name('x') for p in ps2]
  19764. args = [Cast(Name(x), t2, t1)
  19765. for (x,t1,t2) in zip(params, ps1, ps2)]
  19766. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19767. return Function('cast', params, [Return(body)], {})
  19768. case (TupleType(ts1), TupleType(ts2)):
  19769. x = generate_name('x')
  19770. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19771. for (t1,t2) in zip(ts1,ts2)]
  19772. return ProxiedTuple(value, reads)
  19773. case (ListType(t1), ListType(t2)):
  19774. x = generate_name('x')
  19775. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19776. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19777. return ProxiedList(value, read, write)
  19778. case (t1, t2) if t1 == t2:
  19779. return value
  19780. case (t1, t2):
  19781. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19782. def apply_inject(self, value, src):
  19783. return Tagged(value, self.type_to_tag(src))
  19784. def apply_project(self, value, tgt):
  19785. match value:
  19786. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19787. return val
  19788. case _:
  19789. raise Exception('apply_project, unexpected ' + repr(value))
  19790. \end{lstlisting}
  19791. \fi}
  19792. \end{tcolorbox}
  19793. \caption{The \code{apply\_cast} auxiliary method.}
  19794. \label{fig:apply_cast}
  19795. \end{figure}
  19796. The \LangCast{} interpreter uses an auxiliary function named
  19797. \code{apply\_cast} to cast a value from a source type to a target type,
  19798. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19799. the kinds of casts that we've discussed in this section.
  19800. %
  19801. The definition of the interpreter for \LangCast{} is shown in
  19802. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19803. dispatching to \code{apply\_cast}.
  19804. \racket{To handle the addition of tuple
  19805. proxies, we update the tuple primitives in \code{interp-op} using the
  19806. functions given in figure~\ref{fig:guarded-tuple}.}
  19807. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19808. \begin{figure}[tbp]
  19809. \begin{tcolorbox}[colback=white]
  19810. {\if\edition\racketEd
  19811. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19812. (define interp-Lcast-class
  19813. (class interp-Llambda-class
  19814. (super-new)
  19815. (inherit apply-fun apply-inject apply-project)
  19816. (define/override (interp-op op)
  19817. (match op
  19818. ['vector-length guarded-vector-length]
  19819. ['vector-ref guarded-vector-ref]
  19820. ['vector-set! guarded-vector-set!]
  19821. ['any-vector-ref (lambda (v i)
  19822. (match v [`(tagged ,v^ ,tg)
  19823. (guarded-vector-ref v^ i)]))]
  19824. ['any-vector-set! (lambda (v i a)
  19825. (match v [`(tagged ,v^ ,tg)
  19826. (guarded-vector-set! v^ i a)]))]
  19827. ['any-vector-length (lambda (v)
  19828. (match v [`(tagged ,v^ ,tg)
  19829. (guarded-vector-length v^)]))]
  19830. [else (super interp-op op)]
  19831. ))
  19832. (define/override ((interp-exp env) e)
  19833. (define (recur e) ((interp-exp env) e))
  19834. (match e
  19835. [(Value v) v]
  19836. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19837. [else ((super interp-exp env) e)]))
  19838. ))
  19839. (define (interp-Lcast p)
  19840. (send (new interp-Lcast-class) interp-program p))
  19841. \end{lstlisting}
  19842. \fi}
  19843. {\if\edition\pythonEd\pythonColor
  19844. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19845. class InterpLcast(InterpLany):
  19846. def interp_exp(self, e, env):
  19847. match e:
  19848. case Cast(value, src, tgt):
  19849. v = self.interp_exp(value, env)
  19850. return self.apply_cast(v, src, tgt)
  19851. case ValueExp(value):
  19852. return value
  19853. ...
  19854. case _:
  19855. return super().interp_exp(e, env)
  19856. \end{lstlisting}
  19857. \fi}
  19858. \end{tcolorbox}
  19859. \caption{The interpreter for \LangCast{}.}
  19860. \label{fig:interp-Lcast}
  19861. \end{figure}
  19862. {\if\edition\racketEd
  19863. \begin{figure}[tbp]
  19864. \begin{tcolorbox}[colback=white]
  19865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19866. (define (guarded-vector-ref vec i)
  19867. (match vec
  19868. [`(vector-proxy ,proxy)
  19869. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19870. (define rd (vector-ref (vector-ref proxy 1) i))
  19871. (apply-fun rd (list val) 'guarded-vector-ref)]
  19872. [else (vector-ref vec i)]))
  19873. (define (guarded-vector-set! vec i arg)
  19874. (match vec
  19875. [`(vector-proxy ,proxy)
  19876. (define wr (vector-ref (vector-ref proxy 2) i))
  19877. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19878. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19879. [else (vector-set! vec i arg)]))
  19880. (define (guarded-vector-length vec)
  19881. (match vec
  19882. [`(vector-proxy ,proxy)
  19883. (guarded-vector-length (vector-ref proxy 0))]
  19884. [else (vector-length vec)]))
  19885. \end{lstlisting}
  19886. %% {\if\edition\pythonEd\pythonColor
  19887. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19888. %% UNDER CONSTRUCTION
  19889. %% \end{lstlisting}
  19890. %% \fi}
  19891. \end{tcolorbox}
  19892. \caption{The \code{guarded-vector} auxiliary functions.}
  19893. \label{fig:guarded-tuple}
  19894. \end{figure}
  19895. \fi}
  19896. {\if\edition\pythonEd\pythonColor
  19897. \section{Overload Resolution }
  19898. \label{sec:gradual-resolution}
  19899. Recall that when we added support for arrays in
  19900. section~\ref{sec:arrays}, the syntax for the array operations were the
  19901. same as for tuple operations (for example, accessing an element and
  19902. getting the length). So we performed overload resolution, with a pass
  19903. named \code{resolve}, to separate the array and tuple operations. In
  19904. particular, we introduced the primitives \code{array\_load},
  19905. \code{array\_store}, and \code{array\_len}.
  19906. For gradual typing, we further overload these operators to work on
  19907. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19908. updated with new cases for the \CANYTY{} type, translating the element
  19909. access and length operations to the primitives \code{any\_load},
  19910. \code{any\_store}, and \code{any\_len}.
  19911. \fi}
  19912. \section{Cast Insertion }
  19913. \label{sec:gradual-insert-casts}
  19914. In our discussion of type checking of \LangGrad{}, we mentioned how
  19915. the runtime aspect of type checking is carried out by the \code{Cast}
  19916. AST node, which is added to the program by a new pass named
  19917. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19918. language. We now discuss the details of this pass.
  19919. The \code{cast\_insert} pass is closely related to the type checker
  19920. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19921. In particular, the type checker allows implicit casts between
  19922. consistent types. The job of the \code{cast\_insert} pass is to make
  19923. those casts explicit. It does so by inserting
  19924. \code{Cast} nodes into the AST.
  19925. %
  19926. For the most part, the implicit casts occur in places where the type
  19927. checker checks two types for consistency. Consider the case for
  19928. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19929. checker requires that the type of the left operand is consistent with
  19930. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19931. \code{Cast} around the left operand, converting from its type to
  19932. \INTTY{}. The story is similar for the right operand. It is not always
  19933. necessary to insert a cast, for example, if the left operand already has type
  19934. \INTTY{} then there is no need for a \code{Cast}.
  19935. Some of the implicit casts are not as straightforward. One such case
  19936. arises with the
  19937. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19938. see that the type checker requires that the two branches have
  19939. consistent types and that type of the conditional expression is the
  19940. meet of the branches' types. In the target language \LangCast{}, both
  19941. branches will need to have the same type, and that type
  19942. will be the type of the conditional expression. Thus, each branch requires
  19943. a \code{Cast} to convert from its type to the meet of the branches' types.
  19944. The case for the function call exhibits another interesting situation. If
  19945. the function expression is of type \CANYTY{}, then it needs to be cast
  19946. to a function type so that it can be used in a function call in
  19947. \LangCast{}. Which function type should it be cast to? The parameter
  19948. and return types are unknown, so we can simply use \CANYTY{} for all
  19949. of them. Furthermore, in \LangCast{} the argument types will need to
  19950. exactly match the parameter types, so we must cast all the arguments
  19951. to type \CANYTY{} (if they are not already of that type).
  19952. {\if\edition\racketEd
  19953. %
  19954. Likewise, the cases for the tuple operators \code{vector-length},
  19955. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19956. where the tuple expression is of type \CANYTY{}. Instead of
  19957. handling these situations with casts, we recommend translating
  19958. the special-purpose variants of the tuple operators that handle
  19959. tuples of type \CANYTY{}: \code{any-vector-length},
  19960. \code{any-vector-ref}, and \code{any-vector-set!}.
  19961. %
  19962. \fi}
  19963. \section{Lower Casts }
  19964. \label{sec:lower_casts}
  19965. The next step in the journey toward x86 is the \code{lower\_casts}
  19966. pass that translates the casts in \LangCast{} to the lower-level
  19967. \code{Inject} and \code{Project} operators and new operators for
  19968. proxies, extending the \LangLam{} language to \LangProxy{}.
  19969. The \LangProxy{} language can also be described as an extension of
  19970. \LangAny{}, with the addition of proxies. We recommend creating an
  19971. auxiliary function named \code{lower\_cast} that takes an expression
  19972. (in \LangCast{}), a source type, and a target type and translates it
  19973. to an expression in \LangProxy{}.
  19974. The \code{lower\_cast} function can follow a code structure similar to
  19975. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19976. the interpreter for \LangCast{}, because it must handle the same cases
  19977. as \code{apply\_cast} and it needs to mimic the behavior of
  19978. \code{apply\_cast}. The most interesting cases concern
  19979. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19980. {\if\edition\racketEd
  19981. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19982. type to another tuple type is accomplished by creating a proxy that
  19983. intercepts the operations on the underlying tuple. Here we make the
  19984. creation of the proxy explicit with the \code{vector-proxy} AST
  19985. node. It takes three arguments: the first is an expression for the
  19986. tuple, the second is a tuple of functions for casting an element that is
  19987. being read from the tuple, and the third is a tuple of functions for
  19988. casting an element that is being written to the array. You can create
  19989. the functions for reading and writing using lambda expressions. Also,
  19990. as we show in the next section, we need to differentiate these tuples
  19991. of functions from the user-created ones, so we recommend using a new
  19992. AST node named \code{raw-vector} instead of \code{vector}.
  19993. %
  19994. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19995. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19996. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19997. \fi}
  19998. {\if\edition\pythonEd\pythonColor
  19999. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  20000. type to another array type is accomplished by creating a proxy that
  20001. intercepts the operations on the underlying array. Here we make the
  20002. creation of the proxy explicit with the \code{ListProxy} AST node. It
  20003. takes fives arguments: the first is an expression for the array, the
  20004. second is a function for casting an element that is being read from
  20005. the array, the third is a function for casting an element that is
  20006. being written to the array, the fourth is the type of the underlying
  20007. array, and the fifth is the type of the proxied array. You can create
  20008. the functions for reading and writing using lambda expressions.
  20009. A cast between two tuple types can be handled in a similar manner. We
  20010. create a proxy with the \code{TupleProxy} AST node. Tuples are
  20011. immutable, so there is no need for a function to cast the value during
  20012. a write. Because there is a separate element type for each slot in
  20013. the tuple, we need more than one function for casting during a read:
  20014. we need a tuple of functions.
  20015. %
  20016. Also, as we show in the next section, we need to differentiate these
  20017. tuples from the user-created ones, so we recommend using a new AST
  20018. node named \code{RawTuple} instead of \code{Tuple} to create the
  20019. tuples of functions.
  20020. %
  20021. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20022. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20023. that involves casting an array of integers to an array of \CANYTY{}.
  20024. \fi}
  20025. \begin{figure}[tbp]
  20026. \begin{tcolorbox}[colback=white]
  20027. {\if\edition\racketEd
  20028. \begin{lstlisting}
  20029. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  20030. (begin
  20031. (vector-set! v 0 (f (vector-ref v 0)))
  20032. (vector-set! v 1 (f (vector-ref v 1)))))
  20033. (define (inc [x : Any]) : Any
  20034. (inject (+ (project x Integer) 1) Integer))
  20035. (let ([v (vector 0 41)])
  20036. (begin
  20037. (map_inplace inc (vector-proxy v
  20038. (raw-vector (lambda: ([x9 : Integer]) : Any
  20039. (inject x9 Integer))
  20040. (lambda: ([x9 : Integer]) : Any
  20041. (inject x9 Integer)))
  20042. (raw-vector (lambda: ([x9 : Any]) : Integer
  20043. (project x9 Integer))
  20044. (lambda: ([x9 : Any]) : Integer
  20045. (project x9 Integer)))))
  20046. (vector-ref v 1)))
  20047. \end{lstlisting}
  20048. \fi}
  20049. {\if\edition\pythonEd\pythonColor
  20050. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20051. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  20052. i = 0
  20053. while i != array_len(v):
  20054. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  20055. i = (i + 1)
  20056. def inc(x : int) -> int:
  20057. return (x + 1)
  20058. def main() -> int:
  20059. v = [0, 41]
  20060. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  20061. print(array_load(v, 1))
  20062. return 0
  20063. \end{lstlisting}
  20064. \fi}
  20065. \end{tcolorbox}
  20066. \caption{Output of \code{lower\_casts} on the example shown in
  20067. figure~\ref{fig:map-bang}.}
  20068. \label{fig:map-bang-lower-cast}
  20069. \end{figure}
  20070. A cast from one function type to another function type is accomplished
  20071. by generating a \code{lambda} whose parameter and return types match
  20072. the target function type. The body of the \code{lambda} should cast
  20073. the parameters from the target type to the source type. (Yes,
  20074. backward! Functions are contravariant\index{subject}{contravariant}
  20075. in the parameters.) Afterward, call the underlying function and then
  20076. cast the result from the source return type to the target return type.
  20077. Figure~\ref{fig:map-lower-cast} shows the output of the
  20078. \code{lower\_casts} pass on the \code{map} example given in
  20079. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  20080. call to \code{map} is wrapped in a \code{lambda}.
  20081. \begin{figure}[tbp]
  20082. \begin{tcolorbox}[colback=white]
  20083. {\if\edition\racketEd
  20084. \begin{lstlisting}
  20085. (define (map [f : (Integer -> Integer)]
  20086. [v : (Vector Integer Integer)])
  20087. : (Vector Integer Integer)
  20088. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20089. (define (inc [x : Any]) : Any
  20090. (inject (+ (project x Integer) 1) Integer))
  20091. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  20092. (project (inc (inject x9 Integer)) Integer))
  20093. (vector 0 41)) 1)
  20094. \end{lstlisting}
  20095. \fi}
  20096. {\if\edition\pythonEd\pythonColor
  20097. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20098. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  20099. return (f(v[0]), f(v[1]),)
  20100. def inc(x : any) -> any:
  20101. return inject((project(x, int) + 1), int)
  20102. def main() -> int:
  20103. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  20104. print(t[1])
  20105. return 0
  20106. \end{lstlisting}
  20107. \fi}
  20108. \end{tcolorbox}
  20109. \caption{Output of \code{lower\_casts} on the example shown in
  20110. figure~\ref{fig:gradual-map}.}
  20111. \label{fig:map-lower-cast}
  20112. \end{figure}
  20113. %\pagebreak
  20114. \section{Differentiate Proxies }
  20115. \label{sec:differentiate-proxies}
  20116. So far, the responsibility of differentiating tuples and tuple proxies
  20117. has been the job of the interpreter.
  20118. %
  20119. \racket{For example, the interpreter for \LangCast{} implements
  20120. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20121. figure~\ref{fig:guarded-tuple}.}
  20122. %
  20123. In the \code{differentiate\_proxies} pass we shift this responsibility
  20124. to the generated code.
  20125. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20126. we used the type \TUPLETYPENAME{} for both
  20127. real tuples and tuple proxies.
  20128. \python{Similarly, we use the type \code{list} for both arrays and
  20129. array proxies.}
  20130. In \LangPVec{} we return the
  20131. \TUPLETYPENAME{} type to its original
  20132. meaning, as the type of just tuples, and we introduce a new type,
  20133. \PTUPLETYNAME{}, whose values
  20134. can be either real tuples or tuple
  20135. proxies.
  20136. %
  20137. {\if\edition\pythonEd\pythonColor
  20138. Likewise, we return the
  20139. \ARRAYTYPENAME{} type to its original
  20140. meaning, as the type of arrays, and we introduce a new type,
  20141. \PARRAYTYNAME{}, whose values
  20142. can be either arrays or array proxies.
  20143. These new types come with a suite of new primitive operations.
  20144. \fi}
  20145. {\if\edition\racketEd
  20146. A tuple proxy is represented by a tuple containing three things: (1) the
  20147. underlying tuple, (2) a tuple of functions for casting elements that
  20148. are read from the tuple, and (3) a tuple of functions for casting
  20149. values to be written to the tuple. So, we define the following
  20150. abbreviation for the type of a tuple proxy:
  20151. \[
  20152. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20153. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20154. \]
  20155. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20156. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20157. %
  20158. Next we describe each of the new primitive operations.
  20159. \begin{description}
  20160. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20161. (\key{PVector} $T \ldots$)]\ \\
  20162. %
  20163. This operation brands a vector as a value of the \code{PVector} type.
  20164. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20165. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20166. %
  20167. This operation brands a vector proxy as value of the \code{PVector} type.
  20168. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20169. \BOOLTY{}] \ \\
  20170. %
  20171. This returns true if the value is a tuple proxy and false if it is a
  20172. real tuple.
  20173. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20174. (\key{Vector} $T \ldots$)]\ \\
  20175. %
  20176. Assuming that the input is a tuple, this operation returns the
  20177. tuple.
  20178. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20179. $\to$ \INTTY{}]\ \\
  20180. %
  20181. Given a tuple proxy, this operation returns the length of the tuple.
  20182. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20183. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20184. %
  20185. Given a tuple proxy, this operation returns the $i$th element of the
  20186. tuple.
  20187. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20188. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20189. Given a tuple proxy, this operation writes a value to the $i$th element
  20190. of the tuple.
  20191. \end{description}
  20192. \fi}
  20193. {\if\edition\pythonEd\pythonColor
  20194. %
  20195. A tuple proxy is represented by a tuple containing (1) the underlying
  20196. tuple and (2) a tuple of functions for casting elements that are read
  20197. from the tuple. The \LangPVec{} language includes the following AST
  20198. classes and primitive functions.
  20199. \begin{description}
  20200. \item[\code{InjectTuple}] \ \\
  20201. %
  20202. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20203. \item[\code{InjectTupleProxy}]\ \\
  20204. %
  20205. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20206. \item[\code{is\_tuple\_proxy}]\ \\
  20207. %
  20208. This primitive returns true if the value is a tuple proxy and false
  20209. if it is a tuple.
  20210. \item[\code{project\_tuple}]\ \\
  20211. %
  20212. Converts a tuple that is branded as \PTUPLETYNAME{}
  20213. back to a tuple.
  20214. \item[\code{proxy\_tuple\_len}]\ \\
  20215. %
  20216. Given a tuple proxy, returns the length of the underlying tuple.
  20217. \item[\code{proxy\_tuple\_load}]\ \\
  20218. %
  20219. Given a tuple proxy, returns the $i$th element of the underlying
  20220. tuple.
  20221. \end{description}
  20222. An array proxy is represented by a tuple containing (1) the underlying
  20223. array, (2) a function for casting elements that are read from the
  20224. array, and (3) a function for casting elements that are written to the
  20225. array. The \LangPVec{} language includes the following AST classes
  20226. and primitive functions.
  20227. \begin{description}
  20228. \item[\code{InjectList}]\ \\
  20229. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20230. \item[\code{InjectListProxy}]\ \\
  20231. %
  20232. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20233. \item[\code{is\_array\_proxy}]\ \\
  20234. %
  20235. Returns true if the value is an array proxy and false if it is an
  20236. array.
  20237. \item[\code{project\_array}]\ \\
  20238. %
  20239. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20240. array.
  20241. \item[\code{proxy\_array\_len}]\ \\
  20242. %
  20243. Given an array proxy, returns the length of the underlying array.
  20244. \item[\code{proxy\_array\_load}]\ \\
  20245. %
  20246. Given an array proxy, returns the $i$th element of the underlying
  20247. array.
  20248. \item[\code{proxy\_array\_store}]\ \\
  20249. %
  20250. Given an array proxy, writes a value to the $i$th element of the
  20251. underlying array.
  20252. \end{description}
  20253. \fi}
  20254. Now we discuss the translation that differentiates tuples and arrays
  20255. from proxies. First, every type annotation in the program is
  20256. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20257. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20258. places. For example, we wrap every tuple creation with an
  20259. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20260. %
  20261. {\if\edition\racketEd
  20262. \begin{minipage}{0.96\textwidth}
  20263. \begin{lstlisting}
  20264. (vector |$e_1 \ldots e_n$|)
  20265. |$\Rightarrow$|
  20266. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20267. \end{lstlisting}
  20268. \end{minipage}
  20269. \fi}
  20270. {\if\edition\pythonEd\pythonColor
  20271. \begin{lstlisting}
  20272. Tuple(|$e_1, \ldots, e_n$|)
  20273. |$\Rightarrow$|
  20274. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20275. \end{lstlisting}
  20276. \fi}
  20277. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20278. AST node that we introduced in the previous
  20279. section does not get injected.
  20280. {\if\edition\racketEd
  20281. \begin{lstlisting}
  20282. (raw-vector |$e_1 \ldots e_n$|)
  20283. |$\Rightarrow$|
  20284. (vector |$e'_1 \ldots e'_n$|)
  20285. \end{lstlisting}
  20286. \fi}
  20287. {\if\edition\pythonEd\pythonColor
  20288. \begin{lstlisting}
  20289. RawTuple(|$e_1, \ldots, e_n$|)
  20290. |$\Rightarrow$|
  20291. Tuple(|$e'_1, \ldots, e'_n$|)
  20292. \end{lstlisting}
  20293. \fi}
  20294. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20295. translates as follows:
  20296. %
  20297. {\if\edition\racketEd
  20298. \begin{lstlisting}
  20299. (vector-proxy |$e_1~e_2~e_3$|)
  20300. |$\Rightarrow$|
  20301. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20302. \end{lstlisting}
  20303. \fi}
  20304. {\if\edition\pythonEd\pythonColor
  20305. \begin{lstlisting}
  20306. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20307. |$\Rightarrow$|
  20308. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20309. \end{lstlisting}
  20310. \fi}
  20311. We translate the element access operations into conditional
  20312. expressions that check whether the value is a proxy and then dispatch
  20313. to either the appropriate proxy tuple operation or the regular tuple
  20314. operation.
  20315. {\if\edition\racketEd
  20316. \begin{lstlisting}
  20317. (vector-ref |$e_1$| |$i$|)
  20318. |$\Rightarrow$|
  20319. (let ([|$v~e_1$|])
  20320. (if (proxy? |$v$|)
  20321. (proxy-vector-ref |$v$| |$i$|)
  20322. (vector-ref (project-vector |$v$|) |$i$|)
  20323. \end{lstlisting}
  20324. \fi}
  20325. %
  20326. Note that in the branch for a tuple, we must apply
  20327. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20328. from the tuple.
  20329. The translation of array operations is similar to the ones for tuples.
  20330. \section{Reveal Casts }
  20331. \label{sec:reveal-casts-gradual}
  20332. {\if\edition\racketEd
  20333. Recall that the \code{reveal\_casts} pass
  20334. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20335. \code{Inject} and \code{Project} into lower-level operations.
  20336. %
  20337. In particular, \code{Project} turns into a conditional expression that
  20338. inspects the tag and retrieves the underlying value. Here we need to
  20339. augment the translation of \code{Project} to handle the situation in which
  20340. the target type is \code{PVector}. Instead of using
  20341. \code{vector-length} we need to use \code{proxy-vector-length}.
  20342. \begin{lstlisting}
  20343. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20344. |$\Rightarrow$|
  20345. (let |$\itm{tmp}$| |$e'$|
  20346. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20347. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20348. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20349. (exit)))
  20350. \end{lstlisting}
  20351. \fi}
  20352. %
  20353. {\if\edition\pythonEd\pythonColor
  20354. Recall that the $\itm{tagof}$ function determines the bits used to
  20355. identify values of different types, and it is used in the \code{reveal\_casts}
  20356. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20357. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20358. decimal), just like the tuple and array types.
  20359. \fi}
  20360. %
  20361. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20362. \pagebreak
  20363. \section{Closure Conversion }
  20364. \label{sec:closure-conversion-gradual}
  20365. The auxiliary function that translates type annotations needs to be
  20366. updated to handle the \PTUPLETYNAME{}
  20367. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20368. %
  20369. Otherwise, the only other changes are adding cases that copy the new
  20370. AST nodes.
  20371. \section{Select Instructions }
  20372. \label{sec:select-instructions-gradual}
  20373. \index{subject}{select instructions}
  20374. Recall that the \code{select\_instructions} pass is responsible for
  20375. lowering the primitive operations into x86 instructions. So, we need
  20376. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20377. to x86. To do so, the first question we need to answer is how to
  20378. differentiate between tuple and tuple proxies\python{, and likewise for
  20379. arrays and array proxies}. We need just one bit to accomplish this;
  20380. we use the bit in position $63$ of the 64-bit tag at the front of
  20381. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20382. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20383. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20384. it that way.
  20385. {\if\edition\racketEd
  20386. \begin{lstlisting}
  20387. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20388. |$\Rightarrow$|
  20389. movq |$e'_1$|, |$\itm{lhs'}$|
  20390. \end{lstlisting}
  20391. \fi}
  20392. {\if\edition\pythonEd\pythonColor
  20393. \begin{lstlisting}
  20394. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20395. |$\Rightarrow$|
  20396. movq |$e'_1$|, |$\itm{lhs'}$|
  20397. \end{lstlisting}
  20398. \fi}
  20399. \python{The translation for \code{InjectList} is also a move instruction.}
  20400. \noindent On the other hand,
  20401. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20402. $63$ to $1$.
  20403. %
  20404. {\if\edition\racketEd
  20405. \begin{lstlisting}
  20406. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20407. |$\Rightarrow$|
  20408. movq |$e'_1$|, %r11
  20409. movq |$(1 << 63)$|, %rax
  20410. orq 0(%r11), %rax
  20411. movq %rax, 0(%r11)
  20412. movq %r11, |$\itm{lhs'}$|
  20413. \end{lstlisting}
  20414. \fi}
  20415. {\if\edition\pythonEd\pythonColor
  20416. \begin{lstlisting}
  20417. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20418. |$\Rightarrow$|
  20419. movq |$e'_1$|, %r11
  20420. movq |$(1 << 63)$|, %rax
  20421. orq 0(%r11), %rax
  20422. movq %rax, 0(%r11)
  20423. movq %r11, |$\itm{lhs'}$|
  20424. \end{lstlisting}
  20425. \fi}
  20426. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20427. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20428. The \racket{\code{proxy?} operation consumes}%
  20429. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20430. consume}
  20431. the information so carefully stashed away by the injections. It
  20432. isolates bit $63$ to tell whether the value is a proxy.
  20433. %
  20434. {\if\edition\racketEd
  20435. \begin{lstlisting}
  20436. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20437. |$\Rightarrow$|
  20438. movq |$e_1'$|, %r11
  20439. movq 0(%r11), %rax
  20440. sarq $63, %rax
  20441. andq $1, %rax
  20442. movq %rax, |$\itm{lhs'}$|
  20443. \end{lstlisting}
  20444. \fi}%
  20445. %
  20446. {\if\edition\pythonEd\pythonColor
  20447. \begin{lstlisting}
  20448. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20449. |$\Rightarrow$|
  20450. movq |$e_1'$|, %r11
  20451. movq 0(%r11), %rax
  20452. sarq $63, %rax
  20453. andq $1, %rax
  20454. movq %rax, |$\itm{lhs'}$|
  20455. \end{lstlisting}
  20456. \fi}%
  20457. %
  20458. The \racket{\code{project-vector} operation is}
  20459. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20460. straightforward to translate, so we leave that to the reader.
  20461. Regarding the element access operations for tuples\python{ and arrays}, the
  20462. runtime provides procedures that implement them (they are recursive
  20463. functions!), so here we simply need to translate these tuple
  20464. operations into the appropriate function call. For example, here is
  20465. the translation for
  20466. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20467. {\if\edition\racketEd
  20468. \begin{minipage}{0.96\textwidth}
  20469. \begin{lstlisting}
  20470. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20471. |$\Rightarrow$|
  20472. movq |$e_1'$|, %rdi
  20473. movq |$e_2'$|, %rsi
  20474. callq proxy_vector_ref
  20475. movq %rax, |$\itm{lhs'}$|
  20476. \end{lstlisting}
  20477. \end{minipage}
  20478. \fi}
  20479. {\if\edition\pythonEd\pythonColor
  20480. \begin{lstlisting}
  20481. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20482. |$\Rightarrow$|
  20483. movq |$e_1'$|, %rdi
  20484. movq |$e_2'$|, %rsi
  20485. callq proxy_vector_ref
  20486. movq %rax, |$\itm{lhs'}$|
  20487. \end{lstlisting}
  20488. \fi}
  20489. {\if\edition\pythonEd\pythonColor
  20490. % TODO: revisit the names vecof for python -Jeremy
  20491. We translate
  20492. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20493. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20494. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20495. \fi}
  20496. We have another batch of operations to deal with: those for the
  20497. \CANYTY{} type. Recall that we generate an
  20498. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20499. there is a element access on something of type \CANYTY{}, and
  20500. similarly for
  20501. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20502. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20503. section~\ref{sec:select-Lany} we selected instructions for these
  20504. operations on the basis of the idea that the underlying value was a tuple or
  20505. array. But in the current setting, the underlying value is of type
  20506. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20507. functions to deal with this:
  20508. \code{proxy\_vector\_ref},
  20509. \code{proxy\_vector\_set}, and
  20510. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20511. to determine whether the value is a proxy, and then
  20512. dispatches to the the appropriate code.
  20513. %
  20514. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20515. can be translated as follows.
  20516. We begin by projecting the underlying value out of the tagged value and
  20517. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20518. {\if\edition\racketEd
  20519. \begin{lstlisting}
  20520. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20521. |$\Rightarrow$|
  20522. movq |$\neg 111$|, %rdi
  20523. andq |$e_1'$|, %rdi
  20524. movq |$e_2'$|, %rsi
  20525. callq proxy_vector_ref
  20526. movq %rax, |$\itm{lhs'}$|
  20527. \end{lstlisting}
  20528. \fi}
  20529. {\if\edition\pythonEd\pythonColor
  20530. \begin{lstlisting}
  20531. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20532. |$\Rightarrow$|
  20533. movq |$\neg 111$|, %rdi
  20534. andq |$e_1'$|, %rdi
  20535. movq |$e_2'$|, %rsi
  20536. callq proxy_vector_ref
  20537. movq %rax, |$\itm{lhs'}$|
  20538. \end{lstlisting}
  20539. \fi}
  20540. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20541. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20542. are translated in a similar way. Alternatively, you could generate
  20543. instructions to open-code
  20544. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20545. and \code{proxy\_vector\_length} functions.
  20546. \begin{exercise}\normalfont\normalsize
  20547. Implement a compiler for the gradually typed \LangGrad{} language by
  20548. extending and adapting your compiler for \LangLam{}. Create ten new
  20549. partially typed test programs. In addition to testing with these
  20550. new programs, test your compiler on all the tests for \LangLam{}
  20551. and for \LangDyn{}.
  20552. %
  20553. \racket{Sometimes you may get a type-checking error on the
  20554. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20555. the \CANYTY{} type around each subexpression that has caused a type
  20556. error. Although \LangDyn{} does not have explicit casts, you can
  20557. induce one by wrapping the subexpression \code{e} with a call to
  20558. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20559. %
  20560. \python{Sometimes you may get a type-checking error on the
  20561. \LangDyn{} programs, but you can adapt them by inserting a
  20562. temporary variable of type \CANYTY{} that is initialized with the
  20563. troublesome expression.}
  20564. \end{exercise}
  20565. \begin{figure}[t]
  20566. \begin{tcolorbox}[colback=white]
  20567. {\if\edition\racketEd
  20568. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20569. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20570. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20571. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20572. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20573. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20574. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20575. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20576. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20577. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20578. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20579. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20580. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20581. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20582. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20583. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20584. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20585. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20586. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20587. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20588. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20589. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20590. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20591. \path[->,bend left=15] (Lgradual) edge [above] node
  20592. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20593. \path[->,bend left=15] (Lgradual2) edge [above] node
  20594. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20595. \path[->,bend left=15] (Lgradual3) edge [above] node
  20596. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20597. \path[->,bend left=15] (Lgradual4) edge [left] node
  20598. {\ttfamily\footnotesize shrink} (Lgradualr);
  20599. \path[->,bend left=15] (Lgradualr) edge [above] node
  20600. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20601. \path[->,bend right=15] (Lgradualp) edge [above] node
  20602. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20603. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20604. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20605. \path[->,bend right=15] (Llambdapp) edge [above] node
  20606. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20607. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20608. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20609. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20610. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20611. \path[->,bend left=15] (F1-2) edge [above] node
  20612. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20613. \path[->,bend left=15] (F1-3) edge [left] node
  20614. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20615. \path[->,bend left=15] (F1-4) edge [below] node
  20616. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20617. \path[->,bend right=15] (F1-5) edge [above] node
  20618. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20619. \path[->,bend right=15] (F1-6) edge [above] node
  20620. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20621. \path[->,bend right=15] (C3-2) edge [right] node
  20622. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20623. \path[->,bend right=15] (x86-2) edge [right] node
  20624. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20625. \path[->,bend right=15] (x86-2-1) edge [below] node
  20626. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20627. \path[->,bend right=15] (x86-2-2) edge [right] node
  20628. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20629. \path[->,bend left=15] (x86-3) edge [above] node
  20630. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20631. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20632. \end{tikzpicture}
  20633. \fi}
  20634. {\if\edition\pythonEd\pythonColor
  20635. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20636. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20637. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20638. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20639. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20640. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20641. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20642. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20643. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20644. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20645. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20646. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20647. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20648. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20649. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20650. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20651. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20652. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20653. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20654. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20655. \path[->,bend left=15] (Lgradual) edge [above] node
  20656. {\ttfamily\footnotesize shrink} (Lgradual2);
  20657. \path[->,bend left=15] (Lgradual2) edge [above] node
  20658. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20659. \path[->,bend left=15] (Lgradual3) edge [above] node
  20660. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20661. \path[->,bend left=15] (Lgradual4) edge [left] node
  20662. {\ttfamily\footnotesize resolve} (Lgradualr);
  20663. \path[->,bend left=15] (Lgradualr) edge [below] node
  20664. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20665. \path[->,bend right=15] (Lgradualp) edge [above] node
  20666. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20667. \path[->,bend right=15] (Llambdapp) edge [above] node
  20668. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20669. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20670. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20671. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20672. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20673. \path[->,bend left=15] (F1-1) edge [above] node
  20674. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20675. \path[->,bend left=15] (F1-2) edge [above] node
  20676. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20677. \path[->,bend left=15] (F1-3) edge [right] node
  20678. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20679. \path[->,bend right=15] (F1-5) edge [above] node
  20680. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20681. \path[->,bend right=15] (F1-6) edge [above] node
  20682. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20683. \path[->,bend right=15] (C3-2) edge [right] node
  20684. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20685. \path[->,bend right=15] (x86-2) edge [below] node
  20686. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20687. \path[->,bend right=15] (x86-3) edge [below] node
  20688. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20689. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20690. \end{tikzpicture}
  20691. \fi}
  20692. \end{tcolorbox}
  20693. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20694. \label{fig:Lgradual-passes}
  20695. \end{figure}
  20696. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20697. needed for the compilation of \LangGrad{}.
  20698. \section{Further Reading}
  20699. This chapter just scratches the surface of gradual typing. The basic
  20700. approach described here is missing two key ingredients that one would
  20701. want in an implementation of gradual typing: blame
  20702. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20703. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20704. problem addressed by blame tracking is that when a cast on a
  20705. higher-order value fails, it often does so at a point in the program
  20706. that is far removed from the original cast. Blame tracking is a
  20707. technique for propagating extra information through casts and proxies
  20708. so that when a cast fails, the error message can point back to the
  20709. original location of the cast in the source program.
  20710. The problem addressed by space-efficient casts also relates to
  20711. higher-order casts. It turns out that in partially typed programs, a
  20712. function or tuple can flow through a great many casts at runtime. With
  20713. the approach described in this chapter, each cast adds another
  20714. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20715. considerable space, but it also makes the function calls and tuple
  20716. operations slow. For example, a partially typed version of quicksort
  20717. could, in the worst case, build a chain of proxies of length $O(n)$
  20718. around the tuple, changing the overall time complexity of the
  20719. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20720. solution to this problem by representing casts using the coercion
  20721. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20722. long chains of proxies by compressing them into a concise normal
  20723. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20724. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20725. the Grift compiler:
  20726. \begin{center}
  20727. \url{https://github.com/Gradual-Typing/Grift}
  20728. \end{center}
  20729. There are also interesting interactions between gradual typing and
  20730. other language features, such as generics, information-flow types, and
  20731. type inference, to name a few. We recommend to the reader the
  20732. online gradual typing bibliography for more material:
  20733. \begin{center}
  20734. \url{http://samth.github.io/gradual-typing-bib/}
  20735. \end{center}
  20736. % TODO: challenge problem:
  20737. % type analysis and type specialization?
  20738. % coercions?
  20739. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20740. \chapter{Generics}
  20741. \label{ch:Lpoly}
  20742. \setcounter{footnote}{0}
  20743. This chapter studies the compilation of
  20744. generics\index{subject}{generics} (aka parametric
  20745. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20746. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20747. enable programmers to make code more reusable by parameterizing
  20748. functions and data structures with respect to the types on which they
  20749. operate. For example, figure~\ref{fig:map-poly} revisits the
  20750. \code{map} example and this time gives it a more fitting type. This
  20751. \code{map} function is parameterized with respect to the element type
  20752. of the tuple. The type of \code{map} is the following generic type
  20753. specified by the \code{All} type with parameter \code{T}:
  20754. {\if\edition\racketEd
  20755. \begin{lstlisting}
  20756. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20757. \end{lstlisting}
  20758. \fi}
  20759. {\if\edition\pythonEd\pythonColor
  20760. \begin{lstlisting}
  20761. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20762. \end{lstlisting}
  20763. \fi}
  20764. %
  20765. The idea is that \code{map} can be used at \emph{all} choices of a
  20766. type for parameter \code{T}. In the example shown in
  20767. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20768. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20769. \code{T}, but we could have just as well applied \code{map} to a tuple
  20770. of Booleans.
  20771. %
  20772. A \emph{monomorphic} function is simply one that is not generic.
  20773. %
  20774. We use the term \emph{instantiation} for the process (within the
  20775. language implementation) of turning a generic function into a
  20776. monomorphic one, where the type parameters have been replaced by
  20777. types.
  20778. {\if\edition\pythonEd\pythonColor
  20779. %
  20780. In Python, when writing a generic function such as \code{map}, one
  20781. does not explicitly write its generic type (using \code{All}).
  20782. Instead, that the function is generic is implied by the use of type
  20783. variables (such as \code{T}) in the type annotations of its
  20784. parameters.
  20785. %
  20786. \fi}
  20787. \begin{figure}[tbp]
  20788. % poly_test_2.rkt
  20789. \begin{tcolorbox}[colback=white]
  20790. {\if\edition\racketEd
  20791. \begin{lstlisting}
  20792. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20793. (define (map f v)
  20794. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20795. (define (inc [x : Integer]) : Integer (+ x 1))
  20796. (vector-ref (map inc (vector 0 41)) 1)
  20797. \end{lstlisting}
  20798. \fi}
  20799. {\if\edition\pythonEd\pythonColor
  20800. \begin{lstlisting}
  20801. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20802. return (f(tup[0]), f(tup[1]))
  20803. def add1(x : int) -> int:
  20804. return x + 1
  20805. t = map(add1, (0, 41))
  20806. print(t[1])
  20807. \end{lstlisting}
  20808. \fi}
  20809. \end{tcolorbox}
  20810. \caption{A generic version of the \code{map} function.}
  20811. \label{fig:map-poly}
  20812. \end{figure}
  20813. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20814. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20815. shows the definition of the abstract syntax.
  20816. %
  20817. {\if\edition\racketEd
  20818. We add a second form for function definitions in which a type
  20819. declaration comes before the \code{define}. In the abstract syntax,
  20820. the return type in the \code{Def} is \CANYTY{}, but that should be
  20821. ignored in favor of the return type in the type declaration. (The
  20822. \CANYTY{} comes from using the same parser as discussed in
  20823. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20824. enables the use of an \code{All} type for a function, thereby making
  20825. it generic.
  20826. \fi}
  20827. %
  20828. The grammar for types is extended to include the type of a generic
  20829. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20830. abstract syntax)}.
  20831. \newcommand{\LpolyGrammarRacket}{
  20832. \begin{array}{lcl}
  20833. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20834. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20835. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20836. \end{array}
  20837. }
  20838. \newcommand{\LpolyASTRacket}{
  20839. \begin{array}{lcl}
  20840. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20841. \Def &::=& \DECL{\Var}{\Type} \\
  20842. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20843. \end{array}
  20844. }
  20845. \newcommand{\LpolyGrammarPython}{
  20846. \begin{array}{lcl}
  20847. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20848. \end{array}
  20849. }
  20850. \newcommand{\LpolyASTPython}{
  20851. \begin{array}{lcl}
  20852. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20853. \MID \key{GenericVar}\LP\Var\RP
  20854. \end{array}
  20855. }
  20856. \begin{figure}[tp]
  20857. \centering
  20858. \begin{tcolorbox}[colback=white]
  20859. \footnotesize
  20860. {\if\edition\racketEd
  20861. \[
  20862. \begin{array}{l}
  20863. \gray{\LintGrammarRacket{}} \\ \hline
  20864. \gray{\LvarGrammarRacket{}} \\ \hline
  20865. \gray{\LifGrammarRacket{}} \\ \hline
  20866. \gray{\LwhileGrammarRacket} \\ \hline
  20867. \gray{\LtupGrammarRacket} \\ \hline
  20868. \gray{\LfunGrammarRacket} \\ \hline
  20869. \gray{\LlambdaGrammarRacket} \\ \hline
  20870. \LpolyGrammarRacket \\
  20871. \begin{array}{lcl}
  20872. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20873. \end{array}
  20874. \end{array}
  20875. \]
  20876. \fi}
  20877. {\if\edition\pythonEd\pythonColor
  20878. \[
  20879. \begin{array}{l}
  20880. \gray{\LintGrammarPython{}} \\ \hline
  20881. \gray{\LvarGrammarPython{}} \\ \hline
  20882. \gray{\LifGrammarPython{}} \\ \hline
  20883. \gray{\LwhileGrammarPython} \\ \hline
  20884. \gray{\LtupGrammarPython} \\ \hline
  20885. \gray{\LfunGrammarPython} \\ \hline
  20886. \gray{\LlambdaGrammarPython} \\\hline
  20887. \LpolyGrammarPython \\
  20888. \begin{array}{lcl}
  20889. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20890. \end{array}
  20891. \end{array}
  20892. \]
  20893. \fi}
  20894. \end{tcolorbox}
  20895. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20896. (figure~\ref{fig:Llam-concrete-syntax}).}
  20897. \label{fig:Lpoly-concrete-syntax}
  20898. \index{subject}{Lgen@\LangPoly{} concrete syntax}
  20899. \end{figure}
  20900. \begin{figure}[tp]
  20901. \centering
  20902. \begin{tcolorbox}[colback=white]
  20903. \footnotesize
  20904. {\if\edition\racketEd
  20905. \[
  20906. \begin{array}{l}
  20907. \gray{\LintOpAST} \\ \hline
  20908. \gray{\LvarASTRacket{}} \\ \hline
  20909. \gray{\LifASTRacket{}} \\ \hline
  20910. \gray{\LwhileASTRacket{}} \\ \hline
  20911. \gray{\LtupASTRacket{}} \\ \hline
  20912. \gray{\LfunASTRacket} \\ \hline
  20913. \gray{\LlambdaASTRacket} \\ \hline
  20914. \LpolyASTRacket \\
  20915. \begin{array}{lcl}
  20916. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20917. \end{array}
  20918. \end{array}
  20919. \]
  20920. \fi}
  20921. {\if\edition\pythonEd\pythonColor
  20922. \[
  20923. \begin{array}{l}
  20924. \gray{\LintASTPython} \\ \hline
  20925. \gray{\LvarASTPython{}} \\ \hline
  20926. \gray{\LifASTPython{}} \\ \hline
  20927. \gray{\LwhileASTPython{}} \\ \hline
  20928. \gray{\LtupASTPython{}} \\ \hline
  20929. \gray{\LfunASTPython} \\ \hline
  20930. \gray{\LlambdaASTPython} \\ \hline
  20931. \LpolyASTPython \\
  20932. \begin{array}{lcl}
  20933. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20934. \end{array}
  20935. \end{array}
  20936. \]
  20937. \fi}
  20938. \end{tcolorbox}
  20939. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20940. (figure~\ref{fig:Llam-syntax}).}
  20941. \label{fig:Lpoly-syntax}
  20942. \index{subject}{Lgen@\LangPoly{} abstract syntax}
  20943. \end{figure}
  20944. By including the \code{All} type in the $\Type$ nonterminal of the
  20945. grammar we choose to make generics first class, which has interesting
  20946. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20947. not include syntax for the \code{All} type. It is inferred for functions whose
  20948. type annotations contain type variables.} Many languages with generics, such as
  20949. C++~\citep{stroustrup88:_param_types} and Standard
  20950. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20951. may be helpful to see an example of first-class generics in action. In
  20952. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20953. whose parameter is a generic function. Indeed, because the grammar for
  20954. $\Type$ includes the \code{All} type, a generic function may also be
  20955. returned from a function or stored inside a tuple. The body of
  20956. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20957. and also to an integer, which would not be possible if \code{f} were
  20958. not generic.
  20959. \begin{figure}[tbp]
  20960. \begin{tcolorbox}[colback=white]
  20961. {\if\edition\racketEd
  20962. \begin{lstlisting}
  20963. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20964. (define (apply_twice f)
  20965. (if (f #t) (f 42) (f 777)))
  20966. (: id (All (T) (T -> T)))
  20967. (define (id x) x)
  20968. (apply_twice id)
  20969. \end{lstlisting}
  20970. \fi}
  20971. {\if\edition\pythonEd\pythonColor
  20972. \begin{lstlisting}
  20973. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20974. if f(True):
  20975. return f(42)
  20976. else:
  20977. return f(777)
  20978. def id(x: T) -> T:
  20979. return x
  20980. print(apply_twice(id))
  20981. \end{lstlisting}
  20982. \fi}
  20983. \end{tcolorbox}
  20984. \caption{An example illustrating first-class generics.}
  20985. \label{fig:apply-twice}
  20986. \end{figure}
  20987. The type checker for \LangPoly{} shown in
  20988. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20989. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20990. {\if\edition\pythonEd\pythonColor
  20991. %
  20992. Regarding function definitions, if the type annotations on its
  20993. parameters contain generic variables, then the function is generic and
  20994. therefore its type is an \code{All} type wrapped around a function
  20995. type. Otherwise the function is monomorphic and its type is simply
  20996. a function type.
  20997. %
  20998. \fi}
  20999. The type checking of a function application is extended to handle the
  21000. case in which the operator expression is a generic function. In that case
  21001. the type arguments are deduced by matching the types of the parameters
  21002. with the types of the arguments.
  21003. %
  21004. The \code{match\_types} auxiliary function
  21005. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  21006. recursively descending through a parameter type \code{param\_ty} and
  21007. the corresponding argument type \code{arg\_ty}, making sure that they
  21008. are equal except when there is a type parameter in the parameter
  21009. type. Upon encountering a type parameter for the first time, the
  21010. algorithm deduces an association of the type parameter to the
  21011. corresponding part of the argument type. If it is not the first time
  21012. that the type parameter has been encountered, the algorithm looks up
  21013. its deduced type and makes sure that it is equal to the corresponding
  21014. part of the argument type. The return type of the application is the
  21015. return type of the generic function with the type parameters
  21016. replaced by the deduced type arguments, using the
  21017. \code{substitute\_type} auxiliary function, which is also listed in
  21018. figure~\ref{fig:type-check-Lpoly-aux}.
  21019. The type checker extends type equality to handle the \code{All} type.
  21020. This is not quite as simple as for other types, such as function and
  21021. tuple types, because two \code{All} types can be syntactically
  21022. different even though they are equivalent. For example,
  21023. \begin{center}
  21024. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  21025. \end{center}
  21026. is equivalent to
  21027. \begin{center}
  21028. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  21029. \end{center}
  21030. Two generic types are equal if they differ only in
  21031. the choice of the names of the type parameters. The definition of type
  21032. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  21033. parameters in one type to match the type parameters of the other type.
  21034. {\if\edition\racketEd
  21035. %
  21036. The type checker also ensures that only defined type variables appear
  21037. in type annotations. The \code{check\_well\_formed} function for which
  21038. the definition is shown in figure~\ref{fig:well-formed-types}
  21039. recursively inspects a type, making sure that each type variable has
  21040. been defined.
  21041. %
  21042. \fi}
  21043. \begin{figure}[tbp]
  21044. \begin{tcolorbox}[colback=white]
  21045. {\if\edition\racketEd
  21046. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21047. (define type-check-poly-class
  21048. (class type-check-Llambda-class
  21049. (super-new)
  21050. (inherit check-type-equal?)
  21051. (define/override (type-check-apply env e1 es)
  21052. (define-values (e^ ty) ((type-check-exp env) e1))
  21053. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  21054. ((type-check-exp env) e)))
  21055. (match ty
  21056. [`(,ty^* ... -> ,rt)
  21057. (for ([arg-ty ty*] [param-ty ty^*])
  21058. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  21059. (values e^ es^ rt)]
  21060. [`(All ,xs (,tys ... -> ,rt))
  21061. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21062. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  21063. (match_types env^^ param-ty arg-ty)))
  21064. (define targs
  21065. (for/list ([x xs])
  21066. (match (dict-ref env^^ x (lambda () #f))
  21067. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  21068. x (Apply e1 es))]
  21069. [ty ty])))
  21070. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  21071. [else (error 'type-check "expected a function, not ~a" ty)]))
  21072. (define/override ((type-check-exp env) e)
  21073. (match e
  21074. [(Lambda `([,xs : ,Ts] ...) rT body)
  21075. (for ([T Ts]) ((check_well_formed env) T))
  21076. ((check_well_formed env) rT)
  21077. ((super type-check-exp env) e)]
  21078. [(HasType e1 ty)
  21079. ((check_well_formed env) ty)
  21080. ((super type-check-exp env) e)]
  21081. [else ((super type-check-exp env) e)]))
  21082. (define/override ((type-check-def env) d)
  21083. (verbose 'type-check "poly/def" d)
  21084. (match d
  21085. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  21086. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  21087. (for ([p ps]) ((check_well_formed ts-env) p))
  21088. ((check_well_formed ts-env) rt)
  21089. (define new-env (append ts-env (map cons xs ps) env))
  21090. (define-values (body^ ty^) ((type-check-exp new-env) body))
  21091. (check-type-equal? ty^ rt body)
  21092. (Generic ts (Def f p:t* rt info body^))]
  21093. [else ((super type-check-def env) d)]))
  21094. (define/override (type-check-program p)
  21095. (match p
  21096. [(Program info body)
  21097. (type-check-program (ProgramDefsExp info '() body))]
  21098. [(ProgramDefsExp info ds body)
  21099. (define ds^ (combine-decls-defs ds))
  21100. (define new-env (for/list ([d ds^])
  21101. (cons (def-name d) (fun-def-type d))))
  21102. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  21103. (define-values (body^ ty) ((type-check-exp new-env) body))
  21104. (check-type-equal? ty 'Integer body)
  21105. (ProgramDefsExp info ds^^ body^)]))
  21106. ))
  21107. \end{lstlisting}
  21108. \fi}
  21109. {\if\edition\pythonEd\pythonColor
  21110. \begin{lstlisting}[basicstyle=\ttfamily\small]
  21111. def type_check_exp(self, e, env):
  21112. match e:
  21113. case Call(Name(f), args) if f in builtin_functions:
  21114. return super().type_check_exp(e, env)
  21115. case Call(func, args):
  21116. func_t = self.type_check_exp(func, env)
  21117. func.has_type = func_t
  21118. match func_t:
  21119. case AllType(ps, FunctionType(p_tys, rt)):
  21120. for arg in args:
  21121. arg.has_type = self.type_check_exp(arg, env)
  21122. arg_tys = [arg.has_type for arg in args]
  21123. deduced = {}
  21124. for (p, a) in zip(p_tys, arg_tys):
  21125. self.match_types(p, a, deduced, e)
  21126. return self.substitute_type(rt, deduced)
  21127. case _:
  21128. return super().type_check_exp(e, env)
  21129. case _:
  21130. return super().type_check_exp(e, env)
  21131. def type_check(self, p):
  21132. match p:
  21133. case Module(body):
  21134. env = {}
  21135. for s in body:
  21136. match s:
  21137. case FunctionDef(name, params, bod, dl, returns, comment):
  21138. params_t = [t for (x,t) in params]
  21139. ty_params = set()
  21140. for t in params_t:
  21141. ty_params |$\mid$|= self.generic_variables(t)
  21142. ty = FunctionType(params_t, returns)
  21143. if len(ty_params) > 0:
  21144. ty = AllType(list(ty_params), ty)
  21145. env[name] = ty
  21146. self.check_stmts(body, IntType(), env)
  21147. case _:
  21148. raise Exception('type_check: unexpected ' + repr(p))
  21149. \end{lstlisting}
  21150. \fi}
  21151. \end{tcolorbox}
  21152. \caption{Type checker for the \LangPoly{} language.}
  21153. \label{fig:type-check-Lpoly}
  21154. \end{figure}
  21155. \begin{figure}[tbp]
  21156. \begin{tcolorbox}[colback=white]
  21157. {\if\edition\racketEd
  21158. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21159. (define/override (type-equal? t1 t2)
  21160. (match* (t1 t2)
  21161. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21162. (define env (map cons xs ys))
  21163. (type-equal? (substitute_type env T1) T2)]
  21164. [(other wise)
  21165. (super type-equal? t1 t2)]))
  21166. (define/public (match_types env pt at)
  21167. (match* (pt at)
  21168. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21169. [('Void 'Void) env] [('Any 'Any) env]
  21170. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21171. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21172. (match_types env^ pt1 at1))]
  21173. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21174. (define env^ (match_types env prt art))
  21175. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21176. (match_types env^^ pt1 at1))]
  21177. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21178. (define env^ (append (map cons pxs axs) env))
  21179. (match_types env^ pt1 at1)]
  21180. [((? symbol? x) at)
  21181. (match (dict-ref env x (lambda () #f))
  21182. [#f (error 'type-check "undefined type variable ~a" x)]
  21183. ['Type (cons (cons x at) env)]
  21184. [t^ (check-type-equal? at t^ 'matching) env])]
  21185. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21186. (define/public (substitute_type env pt)
  21187. (match pt
  21188. ['Integer 'Integer] ['Boolean 'Boolean]
  21189. ['Void 'Void] ['Any 'Any]
  21190. [`(Vector ,ts ...)
  21191. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21192. [`(,ts ... -> ,rt)
  21193. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21194. [`(All ,xs ,t)
  21195. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21196. [(? symbol? x) (dict-ref env x)]
  21197. [else (error 'type-check "expected a type not ~a" pt)]))
  21198. (define/public (combine-decls-defs ds)
  21199. (match ds
  21200. ['() '()]
  21201. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21202. (unless (equal? name f)
  21203. (error 'type-check "name mismatch, ~a != ~a" name f))
  21204. (match type
  21205. [`(All ,xs (,ps ... -> ,rt))
  21206. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21207. (cons (Generic xs (Def name params^ rt info body))
  21208. (combine-decls-defs ds^))]
  21209. [`(,ps ... -> ,rt)
  21210. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21211. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21212. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21213. [`(,(Def f params rt info body) . ,ds^)
  21214. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21215. \end{lstlisting}
  21216. \fi}
  21217. {\if\edition\pythonEd\pythonColor
  21218. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21219. def match_types(self, param_ty, arg_ty, deduced, e):
  21220. match (param_ty, arg_ty):
  21221. case (GenericVar(id), _):
  21222. if id in deduced:
  21223. self.check_type_equal(arg_ty, deduced[id], e)
  21224. else:
  21225. deduced[id] = arg_ty
  21226. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21227. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21228. new_arg_ty = self.substitute_type(arg_ty, rename)
  21229. self.match_types(ty, new_arg_ty, deduced, e)
  21230. case (TupleType(ps), TupleType(ts)):
  21231. for (p, a) in zip(ps, ts):
  21232. self.match_types(p, a, deduced, e)
  21233. case (ListType(p), ListType(a)):
  21234. self.match_types(p, a, deduced, e)
  21235. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21236. for (pp, ap) in zip(pps, aps):
  21237. self.match_types(pp, ap, deduced, e)
  21238. self.match_types(prt, art, deduced, e)
  21239. case (IntType(), IntType()):
  21240. pass
  21241. case (BoolType(), BoolType()):
  21242. pass
  21243. case _:
  21244. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21245. def substitute_type(self, ty, var_map):
  21246. match ty:
  21247. case GenericVar(id):
  21248. return var_map[id]
  21249. case AllType(ps, ty):
  21250. new_map = copy.deepcopy(var_map)
  21251. for p in ps:
  21252. new_map[p] = GenericVar(p)
  21253. return AllType(ps, self.substitute_type(ty, new_map))
  21254. case TupleType(ts):
  21255. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21256. case ListType(ty):
  21257. return ListType(self.substitute_type(ty, var_map))
  21258. case FunctionType(pts, rt):
  21259. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21260. self.substitute_type(rt, var_map))
  21261. case IntType():
  21262. return IntType()
  21263. case BoolType():
  21264. return BoolType()
  21265. case _:
  21266. raise Exception('substitute_type: unexpected ' + repr(ty))
  21267. def check_type_equal(self, t1, t2, e):
  21268. match (t1, t2):
  21269. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21270. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21271. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21272. case (_, _):
  21273. return super().check_type_equal(t1, t2, e)
  21274. \end{lstlisting}
  21275. \fi}
  21276. \end{tcolorbox}
  21277. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21278. \label{fig:type-check-Lpoly-aux}
  21279. \end{figure}
  21280. {\if\edition\racketEd
  21281. \begin{figure}[tbp]
  21282. \begin{tcolorbox}[colback=white]
  21283. \begin{lstlisting}
  21284. (define/public ((check_well_formed env) ty)
  21285. (match ty
  21286. ['Integer (void)]
  21287. ['Boolean (void)]
  21288. ['Void (void)]
  21289. [(? symbol? a)
  21290. (match (dict-ref env a (lambda () #f))
  21291. ['Type (void)]
  21292. [else (error 'type-check "undefined type variable ~a" a)])]
  21293. [`(Vector ,ts ...)
  21294. (for ([t ts]) ((check_well_formed env) t))]
  21295. [`(,ts ... -> ,t)
  21296. (for ([t ts]) ((check_well_formed env) t))
  21297. ((check_well_formed env) t)]
  21298. [`(All ,xs ,t)
  21299. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21300. ((check_well_formed env^) t)]
  21301. [else (error 'type-check "unrecognized type ~a" ty)]))
  21302. \end{lstlisting}
  21303. \end{tcolorbox}
  21304. \caption{Well-formed types.}
  21305. \label{fig:well-formed-types}
  21306. \end{figure}
  21307. \fi}
  21308. % TODO: interpreter for R'_10
  21309. \clearpage
  21310. \section{Compiling Generics}
  21311. \label{sec:compiling-poly}
  21312. Broadly speaking, there are four approaches to compiling generics, as
  21313. follows:
  21314. \begin{description}
  21315. \item[Monomorphization] generates a different version of a generic
  21316. function for each set of type arguments with which it is used,
  21317. producing type-specialized code. This approach results in the most
  21318. efficient code but requires whole-program compilation (no separate
  21319. compilation) and may increase code size. Unfortunately,
  21320. monomorphization is incompatible with first-class generics because
  21321. it is not always possible to determine which generic functions are
  21322. used with which type arguments during compilation. (It can be done
  21323. at runtime with just-in-time compilation.) Monomorphization is
  21324. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21325. generic functions in NESL~\citep{Blelloch:1993aa} and
  21326. ML~\citep{Weeks:2006aa}.
  21327. \item[Uniform representation] generates one version of each generic
  21328. function and requires all values to have a common \emph{boxed} format,
  21329. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21330. generic and monomorphic code is compiled similarly to code in a
  21331. dynamically typed language (like \LangDyn{}), in which primitive
  21332. operators require their arguments to be projected from \CANYTY{} and
  21333. their results to be injected into \CANYTY{}. (In object-oriented
  21334. languages, the projection is accomplished via virtual method
  21335. dispatch.) The uniform representation approach is compatible with
  21336. separate compilation and with first-class generics. However, it
  21337. produces the least efficient code because it introduces overhead in
  21338. the entire program. This approach is used in
  21339. Java~\citep{Bracha:1998fk},
  21340. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21341. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21342. \item[Mixed representation] generates one version of each generic
  21343. function, using a boxed representation for type variables. However,
  21344. monomorphic code is compiled as usual (as in \LangLam{}), and
  21345. conversions are performed at the boundaries between monomorphic code
  21346. and polymorphic code (for example, when a generic function is instantiated
  21347. and called). This approach is compatible with separate compilation
  21348. and first-class generics and maintains efficiency in monomorphic
  21349. code. The trade-off is increased overhead at the boundary between
  21350. monomorphic and generic code. This approach is used in
  21351. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21352. Java 5 with the addition of autoboxing.
  21353. \item[Type passing] uses the unboxed representation in both
  21354. monomorphic and generic code. Each generic function is compiled to a
  21355. single function with extra parameters that describe the type
  21356. arguments. The type information is used by the generated code to
  21357. determine how to access the unboxed values at runtime. This approach is
  21358. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21359. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21360. compilation and first-class generics and maintains the
  21361. efficiency for monomorphic code. There is runtime overhead in
  21362. polymorphic code from dispatching on type information.
  21363. \end{description}
  21364. In this chapter we use the mixed representation approach, partly
  21365. because of its favorable attributes and partly because it is
  21366. straightforward to implement using the tools that we have already
  21367. built to support gradual typing. The work of compiling generic
  21368. functions is performed in two passes, \code{resolve} and
  21369. \code{erase\_types}, that we discuss next. The output of
  21370. \code{erase\_types} is \LangCast{}
  21371. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21372. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21373. \section{Resolve Instantiation}
  21374. \label{sec:generic-resolve}
  21375. Recall that the type checker for \LangPoly{} deduces the type
  21376. arguments at call sites to a generic function. The purpose of the
  21377. \code{resolve} pass is to turn this implicit instantiation into an
  21378. explicit one, by adding \code{inst} nodes to the syntax of the
  21379. intermediate language. An \code{inst} node records the mapping of
  21380. type parameters to type arguments. The semantics of the \code{inst}
  21381. node is to instantiate the result of its first argument, a generic
  21382. function, to produce a monomorphic function. However, because the
  21383. interpreter never analyzes type annotations, instantiation can be a
  21384. no-op and simply return the generic function.
  21385. %
  21386. The output language of the \code{resolve} pass is \LangInst{},
  21387. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21388. {\if\edition\racketEd
  21389. The \code{resolve} pass combines the type declaration and polymorphic
  21390. function into a single definition, using the \code{Poly} form, to make
  21391. polymorphic functions more convenient to process in the next pass of the
  21392. compiler.
  21393. \fi}
  21394. \newcommand{\LinstASTRacket}{
  21395. \begin{array}{lcl}
  21396. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21397. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21398. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21399. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21400. \end{array}
  21401. }
  21402. \newcommand{\LinstASTPython}{
  21403. \begin{array}{lcl}
  21404. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21405. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21406. \end{array}
  21407. }
  21408. \begin{figure}[tp]
  21409. \centering
  21410. \begin{tcolorbox}[colback=white]
  21411. \small
  21412. {\if\edition\racketEd
  21413. \[
  21414. \begin{array}{l}
  21415. \gray{\LintOpAST} \\ \hline
  21416. \gray{\LvarASTRacket{}} \\ \hline
  21417. \gray{\LifASTRacket{}} \\ \hline
  21418. \gray{\LwhileASTRacket{}} \\ \hline
  21419. \gray{\LtupASTRacket{}} \\ \hline
  21420. \gray{\LfunASTRacket} \\ \hline
  21421. \gray{\LlambdaASTRacket} \\ \hline
  21422. \LinstASTRacket \\
  21423. \begin{array}{lcl}
  21424. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21425. \end{array}
  21426. \end{array}
  21427. \]
  21428. \fi}
  21429. {\if\edition\pythonEd\pythonColor
  21430. \[
  21431. \begin{array}{l}
  21432. \gray{\LintASTPython} \\ \hline
  21433. \gray{\LvarASTPython{}} \\ \hline
  21434. \gray{\LifASTPython{}} \\ \hline
  21435. \gray{\LwhileASTPython{}} \\ \hline
  21436. \gray{\LtupASTPython{}} \\ \hline
  21437. \gray{\LfunASTPython} \\ \hline
  21438. \gray{\LlambdaASTPython} \\ \hline
  21439. \LinstASTPython \\
  21440. \begin{array}{lcl}
  21441. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21442. \end{array}
  21443. \end{array}
  21444. \]
  21445. \fi}
  21446. \end{tcolorbox}
  21447. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21448. (figure~\ref{fig:Llam-syntax}).}
  21449. \label{fig:Lpoly-prime-syntax}
  21450. \index{subject}{Linst@\LangInst{} abstract syntax}
  21451. \end{figure}
  21452. The output of the \code{resolve} pass on the generic \code{map}
  21453. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21454. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21455. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21456. \begin{figure}[tbp]
  21457. % poly_test_2.rkt
  21458. \begin{tcolorbox}[colback=white]
  21459. {\if\edition\racketEd
  21460. \begin{lstlisting}
  21461. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21462. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21463. (define (inc [x : Integer]) : Integer (+ x 1))
  21464. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21465. (Integer))
  21466. inc (vector 0 41)) 1)
  21467. \end{lstlisting}
  21468. \fi}
  21469. {\if\edition\pythonEd\pythonColor
  21470. \begin{lstlisting}
  21471. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21472. return (f(tup[0]), f(tup[1]))
  21473. def add1(x : int) -> int:
  21474. return x + 1
  21475. t = inst(map, {T: int})(add1, (0, 41))
  21476. print(t[1])
  21477. \end{lstlisting}
  21478. \fi}
  21479. \end{tcolorbox}
  21480. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21481. \label{fig:map-resolve}
  21482. \end{figure}
  21483. \section{Erase Generic Types}
  21484. \label{sec:erase_types}
  21485. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21486. represent type variables. For example, figure~\ref{fig:map-erase}
  21487. shows the output of the \code{erase\_types} pass on the generic
  21488. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21489. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21490. \code{All} types are removed from the type of \code{map}.
  21491. \begin{figure}[tbp]
  21492. \begin{tcolorbox}[colback=white]
  21493. {\if\edition\racketEd
  21494. \begin{lstlisting}
  21495. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21496. : (Vector Any Any)
  21497. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21498. (define (inc [x : Integer]) : Integer (+ x 1))
  21499. (vector-ref ((cast map
  21500. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21501. ((Integer -> Integer) (Vector Integer Integer)
  21502. -> (Vector Integer Integer)))
  21503. inc (vector 0 41)) 1)
  21504. \end{lstlisting}
  21505. \fi}
  21506. {\if\edition\pythonEd\pythonColor
  21507. \begin{lstlisting}
  21508. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21509. return (f(tup[0]), f(tup[1]))
  21510. def add1(x : int) -> int:
  21511. return (x + 1)
  21512. def main() -> int:
  21513. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21514. print(t[1])
  21515. return 0
  21516. \end{lstlisting}
  21517. {\small
  21518. where\\
  21519. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21520. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21521. }
  21522. \fi}
  21523. \end{tcolorbox}
  21524. \caption{The generic \code{map} example after type erasure.}
  21525. \label{fig:map-erase}
  21526. \end{figure}
  21527. This process of type erasure creates a challenge at points of
  21528. instantiation. For example, consider the instantiation of
  21529. \code{map} shown in figure~\ref{fig:map-resolve}.
  21530. The type of \code{map} is
  21531. %
  21532. {\if\edition\racketEd
  21533. \begin{lstlisting}
  21534. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21535. \end{lstlisting}
  21536. \fi}
  21537. {\if\edition\pythonEd\pythonColor
  21538. \begin{lstlisting}
  21539. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21540. \end{lstlisting}
  21541. \fi}
  21542. %
  21543. \noindent and it is instantiated to
  21544. %
  21545. {\if\edition\racketEd
  21546. \begin{lstlisting}
  21547. ((Integer -> Integer) (Vector Integer Integer)
  21548. -> (Vector Integer Integer))
  21549. \end{lstlisting}
  21550. \fi}
  21551. {\if\edition\pythonEd\pythonColor
  21552. \begin{lstlisting}
  21553. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21554. \end{lstlisting}
  21555. \fi}
  21556. %
  21557. \noindent After erasure, the type of \code{map} is
  21558. %
  21559. {\if\edition\racketEd
  21560. \begin{lstlisting}
  21561. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21562. \end{lstlisting}
  21563. \fi}
  21564. {\if\edition\pythonEd\pythonColor
  21565. \begin{lstlisting}
  21566. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21567. \end{lstlisting}
  21568. \fi}
  21569. %
  21570. \noindent but we need to convert it to the instantiated type. This is
  21571. easy to do in the language \LangCast{} with a single \code{cast}. In
  21572. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21573. \code{map} has been compiled to a \code{cast} from the type of
  21574. \code{map} to the instantiated type. The source and the target type of
  21575. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21576. is the case because both the source and target are obtained from the
  21577. same generic type of \code{map}, replacing the type parameters with
  21578. \CANYTY{} in the former and with the deduced type arguments in the
  21579. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21580. To implement the \code{erase\_types} pass, we first recommend defining
  21581. a recursive function that translates types, named
  21582. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21583. follows.
  21584. %
  21585. {\if\edition\racketEd
  21586. \begin{lstlisting}
  21587. |$T$|
  21588. |$\Rightarrow$|
  21589. Any
  21590. \end{lstlisting}
  21591. \fi}
  21592. {\if\edition\pythonEd\pythonColor
  21593. \begin{lstlisting}
  21594. GenericVar(|$T$|)
  21595. |$\Rightarrow$|
  21596. Any
  21597. \end{lstlisting}
  21598. \fi}
  21599. %
  21600. \noindent The \code{erase\_type} function also removes the generic
  21601. \code{All} types.
  21602. %
  21603. {\if\edition\racketEd
  21604. \begin{lstlisting}
  21605. (All |$xs$| |$T_1$|)
  21606. |$\Rightarrow$|
  21607. |$T'_1$|
  21608. \end{lstlisting}
  21609. \fi}
  21610. {\if\edition\pythonEd\pythonColor
  21611. \begin{lstlisting}
  21612. AllType(|$xs$|, |$T_1$|)
  21613. |$\Rightarrow$|
  21614. |$T'_1$|
  21615. \end{lstlisting}
  21616. \fi}
  21617. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21618. $T_1$.
  21619. %
  21620. In this compiler pass, apply the \code{erase\_type} function to all
  21621. the type annotations in the program.
  21622. Regarding the translation of expressions, the case for \code{Inst} is
  21623. the interesting one. We translate it into a \code{Cast}, as shown
  21624. next.
  21625. The type of the subexpression $e$ is a generic type of the form
  21626. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21627. The source type of the cast is the erasure of $T$, the type $T_s$.
  21628. %
  21629. {\if\edition\racketEd
  21630. %
  21631. The target type $T_t$ is the result of substituting the argument types
  21632. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21633. erasure.
  21634. %
  21635. \begin{lstlisting}
  21636. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21637. |$\Rightarrow$|
  21638. (Cast |$e'$| |$T_s$| |$T_t$|)
  21639. \end{lstlisting}
  21640. %
  21641. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21642. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21643. \fi}
  21644. {\if\edition\pythonEd\pythonColor
  21645. %
  21646. The target type $T_t$ is the result of substituting the deduced
  21647. argument types $d$ in $T$ and then performing type erasure.
  21648. %
  21649. \begin{lstlisting}
  21650. Inst(|$e$|, |$d$|)
  21651. |$\Rightarrow$|
  21652. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21653. \end{lstlisting}
  21654. %
  21655. where
  21656. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21657. \fi}
  21658. Finally, each generic function is translated to a regular
  21659. function in which type erasure has been applied to all the type
  21660. annotations and the body.
  21661. %% \begin{lstlisting}
  21662. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21663. %% |$\Rightarrow$|
  21664. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21665. %% \end{lstlisting}
  21666. \begin{exercise}\normalfont\normalsize
  21667. Implement a compiler for the polymorphic language \LangPoly{} by
  21668. extending and adapting your compiler for \LangGrad{}. Create six new
  21669. test programs that use polymorphic functions. Some of them should
  21670. make use of first-class generics.
  21671. \end{exercise}
  21672. \begin{figure}[tbp]
  21673. \begin{tcolorbox}[colback=white]
  21674. {\if\edition\racketEd
  21675. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21676. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21677. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21678. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21679. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21680. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21681. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21682. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21683. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21684. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21685. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21686. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21687. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21688. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21689. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21690. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21691. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21692. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21693. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21694. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21695. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21696. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21697. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21698. \path[->,bend left=15] (Lpoly) edge [above] node
  21699. {\ttfamily\footnotesize resolve} (Lpolyp);
  21700. \path[->,bend left=15] (Lpolyp) edge [above] node
  21701. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21702. \path[->,bend left=15] (Lgradualp) edge [above] node
  21703. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21704. \path[->,bend left=15] (Llambdapp) edge [left] node
  21705. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21706. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21707. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21708. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21709. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21710. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21711. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21712. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21713. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21714. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21715. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21716. \path[->,bend left=15] (F1-1) edge [above] node
  21717. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21718. \path[->,bend left=15] (F1-2) edge [above] node
  21719. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21720. \path[->,bend left=15] (F1-3) edge [left] node
  21721. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21722. \path[->,bend left=15] (F1-4) edge [below] node
  21723. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21724. \path[->,bend right=15] (F1-5) edge [above] node
  21725. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21726. \path[->,bend right=15] (F1-6) edge [above] node
  21727. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21728. \path[->,bend right=15] (C3-2) edge [right] node
  21729. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21730. \path[->,bend right=15] (x86-2) edge [right] node
  21731. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21732. \path[->,bend right=15] (x86-2-1) edge [below] node
  21733. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21734. \path[->,bend right=15] (x86-2-2) edge [right] node
  21735. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21736. \path[->,bend left=15] (x86-3) edge [above] node
  21737. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21738. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21739. \end{tikzpicture}
  21740. \fi}
  21741. {\if\edition\pythonEd\pythonColor
  21742. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21743. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21744. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21745. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21746. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21747. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21748. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21749. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21750. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21751. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21752. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21753. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21754. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21755. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21756. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21757. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21758. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21759. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21760. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21761. \path[->,bend left=15] (Lgradual) edge [above] node
  21762. {\ttfamily\footnotesize shrink} (Lgradual2);
  21763. \path[->,bend left=15] (Lgradual2) edge [above] node
  21764. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21765. \path[->,bend left=15] (Lgradual3) edge [above] node
  21766. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21767. \path[->,bend left=15] (Lgradual4) edge [left] node
  21768. {\ttfamily\footnotesize resolve} (Lgradualr);
  21769. \path[->,bend left=15] (Lgradualr) edge [below] node
  21770. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21771. \path[->,bend right=15] (Llambdapp) edge [above] node
  21772. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21773. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21774. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21775. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21776. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21777. \path[->,bend right=15] (F1-1) edge [below] node
  21778. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21779. \path[->,bend right=15] (F1-2) edge [below] node
  21780. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21781. \path[->,bend left=15] (F1-3) edge [above] node
  21782. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21783. \path[->,bend left=15] (F1-5) edge [left] node
  21784. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21785. \path[->,bend left=5] (F1-6) edge [below] node
  21786. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21787. \path[->,bend right=15] (C3-2) edge [right] node
  21788. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21789. \path[->,bend right=15] (x86-2) edge [below] node
  21790. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21791. \path[->,bend right=15] (x86-3) edge [below] node
  21792. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21793. \path[->,bend left=15] (x86-4) edge [above] node
  21794. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21795. \end{tikzpicture}
  21796. \fi}
  21797. \end{tcolorbox}
  21798. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21799. \label{fig:Lpoly-passes}
  21800. \end{figure}
  21801. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21802. needed to compile \LangPoly{}.
  21803. % TODO: challenge problem: specialization of instantiations
  21804. % Further Reading
  21805. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21806. \clearpage
  21807. \appendix
  21808. \chapter{Appendix}
  21809. \setcounter{footnote}{0}
  21810. {\if\edition\racketEd
  21811. \section{Interpreters}
  21812. \label{appendix:interp}
  21813. \index{subject}{interpreter}
  21814. We provide interpreters for each of the source languages \LangInt{},
  21815. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21816. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21817. intermediate languages \LangCVar{} and \LangCIf{} are in
  21818. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21819. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21820. \key{interp.rkt} file.
  21821. \section{Utility Functions}
  21822. \label{appendix:utilities}
  21823. The utility functions described in this section are in the
  21824. \key{utilities.rkt} file of the support code.
  21825. \paragraph{\code{interp-tests}}
  21826. This function runs the compiler passes and the interpreters on each of
  21827. the specified tests to check whether each pass is correct. The
  21828. \key{interp-tests} function has the following parameters:
  21829. \begin{description}
  21830. \item[name (a string)] A name to identify the compiler.
  21831. \item[typechecker] A function of exactly one argument that either
  21832. raises an error using the \code{error} function when it encounters a
  21833. type error, or returns \code{\#f} when it encounters a type
  21834. error. If there is no type error, the type checker returns the
  21835. program.
  21836. \item[passes] A list with one entry per pass. An entry is a list
  21837. consisting of four things:
  21838. \begin{enumerate}
  21839. \item a string giving the name of the pass;
  21840. \item the function that implements the pass (a translator from AST
  21841. to AST);
  21842. \item a function that implements the interpreter (a function from
  21843. AST to result value) for the output language; and,
  21844. \item a type checker for the output language. Type checkers for
  21845. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21846. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21847. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21848. type checker entry is optional. The support code does not provide
  21849. type checkers for the x86 languages.
  21850. \end{enumerate}
  21851. \item[source-interp] An interpreter for the source language. The
  21852. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21853. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21854. \item[tests] A list of test numbers that specifies which tests to
  21855. run (explained next).
  21856. \end{description}
  21857. %
  21858. The \key{interp-tests} function assumes that the subdirectory
  21859. \key{tests} has a collection of Racket programs whose names all start
  21860. with the family name, followed by an underscore and then the test
  21861. number, and ending with the file extension \key{.rkt}. Also, for each test
  21862. program that calls \code{read} one or more times, there is a file with
  21863. the same name except that the file extension is \key{.in}, which
  21864. provides the input for the Racket program. If the test program is
  21865. expected to fail type checking, then there should be an empty file of
  21866. the same name with extension \key{.tyerr}.
  21867. \paragraph{\code{compiler-tests}}
  21868. This function runs the compiler passes to generate x86 (a \key{.s}
  21869. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21870. It runs the machine code and checks that the output is $42$. The
  21871. parameters to the \code{compiler-tests} function are similar to those
  21872. of the \code{interp-tests} function, and they consist of
  21873. \begin{itemize}
  21874. \item a compiler name (a string),
  21875. \item a type checker,
  21876. \item description of the passes,
  21877. \item name of a test-family, and
  21878. \item a list of test numbers.
  21879. \end{itemize}
  21880. \paragraph{\code{compile-file}}
  21881. This function takes a description of the compiler passes (see the
  21882. comment for \key{interp-tests}) and returns a function that, given a
  21883. program file name (a string ending in \key{.rkt}), applies all the
  21884. passes and writes the output to a file whose name is the same as the
  21885. program file name with extension \key{.rkt} replaced by \key{.s}.
  21886. \paragraph{\code{read-program}}
  21887. This function takes a file path and parses that file (it must be a
  21888. Racket program) into an abstract syntax tree.
  21889. \paragraph{\code{parse-program}}
  21890. This function takes an S-expression representation of an abstract
  21891. syntax tree and converts it into the struct-based representation.
  21892. \paragraph{\code{assert}}
  21893. This function takes two parameters, a string (\code{msg}) and Boolean
  21894. (\code{bool}), and displays the message \key{msg} if the Boolean
  21895. \key{bool} is false.
  21896. \paragraph{\code{lookup}}
  21897. % remove discussion of lookup? -Jeremy
  21898. This function takes a key and an alist and returns the first value that is
  21899. associated with the given key, if there is one. If not, an error is
  21900. triggered. The alist may contain both immutable pairs (built with
  21901. \key{cons}) and mutable pairs (built with \key{mcons}).
  21902. %The \key{map2} function ...
  21903. \fi} %\racketEd
  21904. \section{x86 Instruction Set Quick Reference}
  21905. \label{sec:x86-quick-reference}
  21906. \index{subject}{x86}
  21907. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21908. do. We write $A \to B$ to mean that the value of $A$ is written into
  21909. location $B$. Address offsets are given in bytes. The instruction
  21910. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21911. registers (such as \code{\%rax}), or memory references (such as
  21912. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21913. reference per instruction. Other operands must be immediates or
  21914. registers.
  21915. \begin{table}[tbp]
  21916. \captionabove{Quick reference for the x86 instructions used in this book.}
  21917. \label{tab:x86-instr}
  21918. \centering
  21919. \begin{tabular}{l|l}
  21920. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21921. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21922. \texttt{negq} $A$ & $- A \to A$ \\
  21923. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21924. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21925. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21926. \texttt{callq} \texttt{*}$A$ & Pushes the return address and jumps to the address in $A$. \\
  21927. \texttt{retq} & Pops the return address and jumps to it. \\
  21928. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21929. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21930. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21931. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21932. & \\
  21933. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21934. matches the condition code of the instruction; otherwise go to the
  21935. next instructions. The condition codes are \key{e} for \emph{equal},
  21936. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21937. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21938. \texttt{jl} $L$ & \\
  21939. \texttt{jle} $L$ & \\
  21940. \texttt{jg} $L$ & \\
  21941. \texttt{jge} $L$ & \\
  21942. \texttt{jmp} $L$ & Jump to label $L$. \\
  21943. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21944. \texttt{movzbq} $A$, $B$ &
  21945. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21946. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21947. and the extra bytes of $B$ are set to zero.} \\
  21948. & \\
  21949. & \\
  21950. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21951. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21952. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21953. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21954. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21955. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21956. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21957. description of the condition codes. $A$ must be a single byte register
  21958. (e.g., \texttt{al} or \texttt{cl}).} \\
  21959. \texttt{setl} $A$ & \\
  21960. \texttt{setle} $A$ & \\
  21961. \texttt{setg} $A$ & \\
  21962. \texttt{setge} $A$ &
  21963. \end{tabular}
  21964. \end{table}
  21965. \backmatter
  21966. \addtocontents{toc}{\vspace{11pt}}
  21967. \cleardoublepage % needed for right page number in TOC for References
  21968. %% \nocite{*} is a way to get all the entries in the .bib file to
  21969. %% print in the bibliography:
  21970. \nocite{*}\let\bibname\refname
  21971. \addcontentsline{toc}{fmbm}{\refname}
  21972. \printbibliography
  21973. %\printindex{authors}{Author Index}
  21974. \printindex{subject}{Index}
  21975. \end{document}
  21976. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21977. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21978. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21979. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21980. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21981. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21982. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21983. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21984. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21985. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21986. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21987. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21988. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21989. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21990. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21991. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21992. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21993. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21994. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21995. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21996. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21997. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21998. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21999. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  22000. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  22001. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  22002. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  22003. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  22004. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  22005. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  22006. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  22007. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  22008. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  22009. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  22010. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  22011. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  22012. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  22013. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  22014. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  22015. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  22016. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  22017. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  22018. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  22019. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  22020. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  22021. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  22022. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  22023. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  22024. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  22025. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  22026. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  22027. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  22028. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  22029. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  22030. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  22031. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  22032. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  22033. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  22034. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  22035. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  22036. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  22037. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  22038. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  22039. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  22040. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  22041. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  22042. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  22043. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  22044. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  22045. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  22046. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  22047. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  22048. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  22049. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  22050. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  22051. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  22052. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  22053. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  22054. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  22055. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  22056. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  22057. % LocalWords: pseudocode underapproximation underapproximations LALR
  22058. % LocalWords: semilattices overapproximate incrementing Earley docs
  22059. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  22060. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  22061. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  22062. % LocalWords: LC partialevaluation pythonEd TOC TrappedError