book.tex 836 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001
  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{0}
  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. class 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 \LangVarANF{} 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 \LangVarANF{} 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 \LangVarANF{},
  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 \LangVar{} 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.
  3625. In this example, we assign variable \code{a} to stack location
  3626. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3627. {\if\edition\racketEd
  3628. \begin{transformation}
  3629. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3630. movq $42, a
  3631. movq a, b
  3632. movq b, %rax
  3633. \end{lstlisting}
  3634. \compilesto
  3635. %stack-space: 16
  3636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3637. movq $42, -8(%rbp)
  3638. movq -8(%rbp), -16(%rbp)
  3639. movq -16(%rbp), %rax
  3640. \end{lstlisting}
  3641. \end{transformation}
  3642. \fi}
  3643. {\if\edition\pythonEd
  3644. \begin{transformation}
  3645. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3646. movq $42, a
  3647. movq a, b
  3648. movq b, %rdi
  3649. callq print_int
  3650. \end{lstlisting}
  3651. \compilesto
  3652. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3653. movq $42, -8(%rbp)
  3654. movq -8(%rbp), -16(%rbp)
  3655. movq -16(%rbp), %rdi
  3656. callq print_int
  3657. \end{lstlisting}
  3658. \end{transformation}
  3659. \fi}
  3660. \racket{
  3661. The \code{assign\_homes} pass should replace all variables
  3662. with stack locations.
  3663. The list of variables can be obtained from
  3664. the \code{locals-types} entry in the $\itm{info}$ of the
  3665. \code{X86Program} node. The \code{locals-types} entry is an alist
  3666. mapping all the variables in the program to their types
  3667. (for now, just \code{Integer}).
  3668. As an aside, the \code{locals-types} entry is
  3669. computed by \code{type-check-Cvar} in the support code, which
  3670. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3671. which you should propagate to the \code{X86Program} node.}
  3672. %
  3673. \python{The \code{assign\_homes} pass should replace all uses of
  3674. variables with stack locations.}
  3675. %
  3676. In the process of assigning variables to stack locations, it is
  3677. convenient for you to compute and store the size of the frame (in
  3678. bytes) in
  3679. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3680. %
  3681. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3682. %
  3683. which is needed later to generate the conclusion of the \code{main}
  3684. procedure. The x86-64 standard requires the frame size to be a
  3685. multiple of 16 bytes.\index{subject}{frame}
  3686. % TODO: store the number of variables instead? -Jeremy
  3687. \begin{exercise}\normalfont\normalsize
  3688. Implement the \code{assign\_homes} pass in
  3689. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3690. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3691. grammar. We recommend that the auxiliary functions take an extra
  3692. parameter that maps variable names to homes (stack locations for now).
  3693. %
  3694. {\if\edition\racketEd
  3695. In the \code{run-tests.rkt} script, add the following entry to the
  3696. list of \code{passes} and then run the script to test your compiler.
  3697. \begin{lstlisting}
  3698. (list "assign homes" assign-homes interp_x86-0)
  3699. \end{lstlisting}
  3700. \fi}
  3701. {\if\edition\pythonEd\pythonColor
  3702. Run the \code{run-tests.py} script to check
  3703. whether the output programs produce the same result as the input
  3704. programs.
  3705. \fi}
  3706. \end{exercise}
  3707. \section{Patch Instructions}
  3708. \label{sec:patch-s0}
  3709. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3710. \LangXInt{} by making sure that each instruction adheres to the
  3711. restriction that at most one argument of an instruction may be a
  3712. memory reference.
  3713. We return to the following example.\\
  3714. \begin{minipage}{0.5\textwidth}
  3715. % var_test_20.rkt
  3716. {\if\edition\racketEd
  3717. \begin{lstlisting}
  3718. (let ([a 42])
  3719. (let ([b a])
  3720. b))
  3721. \end{lstlisting}
  3722. \fi}
  3723. {\if\edition\pythonEd\pythonColor
  3724. \begin{lstlisting}
  3725. a = 42
  3726. b = a
  3727. print(b)
  3728. \end{lstlisting}
  3729. \fi}
  3730. \end{minipage}\\
  3731. The \code{assign\_homes} pass produces the following translation. \\
  3732. \begin{minipage}{0.5\textwidth}
  3733. {\if\edition\racketEd
  3734. \begin{lstlisting}
  3735. movq $42, -8(%rbp)
  3736. movq -8(%rbp), -16(%rbp)
  3737. movq -16(%rbp), %rax
  3738. \end{lstlisting}
  3739. \fi}
  3740. {\if\edition\pythonEd\pythonColor
  3741. \begin{lstlisting}
  3742. movq $42, -8(%rbp)
  3743. movq -8(%rbp), -16(%rbp)
  3744. movq -16(%rbp), %rdi
  3745. callq print_int
  3746. \end{lstlisting}
  3747. \fi}
  3748. \end{minipage}\\
  3749. The second \key{movq} instruction is problematic because both
  3750. arguments are stack locations. We suggest fixing this problem by
  3751. moving from the source location to the register \key{rax} and then
  3752. from \key{rax} to the destination location, as follows.
  3753. \begin{lstlisting}
  3754. movq -8(%rbp), %rax
  3755. movq %rax, -16(%rbp)
  3756. \end{lstlisting}
  3757. There is a similar corner case that also needs to be dealt with. If
  3758. one argument is an immediate integer larger than $2^{16}$ and the
  3759. other is a memory reference, then the instruction is invalid. One can
  3760. fix this, for example, by first moving the immediate integer into
  3761. \key{rax} and then using \key{rax} in place of the integer.
  3762. \begin{exercise}
  3763. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3764. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3765. Create three new example programs that are
  3766. designed to exercise all the interesting cases in this pass.
  3767. %
  3768. {\if\edition\racketEd
  3769. In the \code{run-tests.rkt} script, add the following entry to the
  3770. list of \code{passes} and then run the script to test your compiler.
  3771. \begin{lstlisting}
  3772. (list "patch instructions" patch_instructions interp_x86-0)
  3773. \end{lstlisting}
  3774. \fi}
  3775. {\if\edition\pythonEd\pythonColor
  3776. Run the \code{run-tests.py} script to check
  3777. whether the output programs produce the same result as the input
  3778. programs.
  3779. \fi}
  3780. \end{exercise}
  3781. \section{Generate Prelude and Conclusion}
  3782. \label{sec:print-x86}
  3783. \index{subject}{prelude}\index{subject}{conclusion}
  3784. The last step of the compiler from \LangVar{} to x86 is to generate
  3785. the \code{main} function with a prelude and conclusion wrapped around
  3786. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3787. discussed in section~\ref{sec:x86}.
  3788. When running on Mac OS X, your compiler should prefix an underscore to
  3789. all labels (for example, changing \key{main} to \key{\_main}).
  3790. %
  3791. \racket{The Racket call \code{(system-type 'os)} is useful for
  3792. determining which operating system the compiler is running on. It
  3793. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3794. %
  3795. \python{The Python \code{platform.system}
  3796. function returns \code{\textquotesingle Linux\textquotesingle},
  3797. \code{\textquotesingle Windows\textquotesingle}, or
  3798. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3799. \begin{exercise}\normalfont\normalsize
  3800. %
  3801. Implement the \key{prelude\_and\_conclusion} pass in
  3802. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3803. %
  3804. {\if\edition\racketEd
  3805. In the \code{run-tests.rkt} script, add the following entry to the
  3806. list of \code{passes} and then run the script to test your compiler.
  3807. \begin{lstlisting}
  3808. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3809. \end{lstlisting}
  3810. %
  3811. Uncomment the call to the \key{compiler-tests} function
  3812. (appendix~\ref{appendix:utilities}), which tests your complete
  3813. compiler by executing the generated x86 code. It translates the x86
  3814. AST that you produce into a string by invoking the \code{print-x86}
  3815. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3816. the provided \key{runtime.c} file to \key{runtime.o} using
  3817. \key{gcc}. Run the script to test your compiler.
  3818. %
  3819. \fi}
  3820. {\if\edition\pythonEd\pythonColor
  3821. %
  3822. Run the \code{run-tests.py} script to check whether the output
  3823. programs produce the same result as the input programs. That script
  3824. translates the x86 AST that you produce into a string by invoking the
  3825. \code{repr} method that is implemented by the x86 AST classes in
  3826. \code{x86\_ast.py}.
  3827. %
  3828. \fi}
  3829. \end{exercise}
  3830. \section{Challenge: Partial Evaluator for \LangVar{}}
  3831. \label{sec:pe-Lvar}
  3832. \index{subject}{partialevaluation@partial evaluation}
  3833. This section describes two optional challenge exercises that involve
  3834. adapting and improving the partial evaluator for \LangInt{} that was
  3835. introduced in section~\ref{sec:partial-evaluation}.
  3836. \begin{exercise}\label{ex:pe-Lvar}
  3837. \normalfont\normalsize
  3838. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3839. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3840. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3841. %
  3842. \racket{\key{let} binding}\python{assignment}
  3843. %
  3844. to the \LangInt{} language, so you will need to add cases for them in
  3845. the \code{pe\_exp}
  3846. %
  3847. \racket{function.}
  3848. %
  3849. \python{and \code{pe\_stmt} functions.}
  3850. %
  3851. Once complete, add the partial evaluation pass to the front of your
  3852. compiler.
  3853. \python{In particular, add a method named \code{partial\_eval} to
  3854. the \code{Compiler} class in \code{compiler.py}.}
  3855. Check that your compiler still passes all the
  3856. tests.
  3857. \end{exercise}
  3858. \begin{exercise}
  3859. \normalfont\normalsize
  3860. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3861. \code{pe\_add} auxiliary functions with functions that know more about
  3862. arithmetic. For example, your partial evaluator should translate
  3863. {\if\edition\racketEd
  3864. \[
  3865. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3866. \code{(+ 2 (read))}
  3867. \]
  3868. \fi}
  3869. {\if\edition\pythonEd\pythonColor
  3870. \[
  3871. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3872. \code{2 + input\_int()}
  3873. \]
  3874. \fi}
  3875. %
  3876. To accomplish this, the \code{pe\_exp} function should produce output
  3877. in the form of the $\itm{residual}$ nonterminal of the following
  3878. grammar. The idea is that when processing an addition expression, we
  3879. can always produce one of the following: (1) an integer constant, (2)
  3880. an addition expression with an integer constant on the left-hand side
  3881. but not the right-hand side, or (3) an addition expression in which
  3882. neither subexpression is a constant.
  3883. %
  3884. {\if\edition\racketEd
  3885. \[
  3886. \begin{array}{lcl}
  3887. \itm{inert} &::=& \Var
  3888. \MID \LP\key{read}\RP
  3889. \MID \LP\key{-} ~\Var\RP
  3890. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3891. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3892. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3893. \itm{residual} &::=& \Int
  3894. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3895. \MID \itm{inert}
  3896. \end{array}
  3897. \]
  3898. \fi}
  3899. {\if\edition\pythonEd\pythonColor
  3900. \[
  3901. \begin{array}{lcl}
  3902. \itm{inert} &::=& \Var
  3903. \MID \key{input\_int}\LP\RP
  3904. \MID \key{-} \Var
  3905. \MID \key{-} \key{input\_int}\LP\RP
  3906. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3907. \itm{residual} &::=& \Int
  3908. \MID \Int ~ \key{+} ~ \itm{inert}
  3909. \MID \itm{inert}
  3910. \end{array}
  3911. \]
  3912. \fi}
  3913. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3914. inputs are $\itm{residual}$ expressions and they should return
  3915. $\itm{residual}$ expressions. Once the improvements are complete,
  3916. make sure that your compiler still passes all the tests. After
  3917. all, fast code is useless if it produces incorrect results!
  3918. \end{exercise}
  3919. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3920. {\if\edition\pythonEd\pythonColor
  3921. \chapter{Parsing}
  3922. \label{ch:parsing}
  3923. \setcounter{footnote}{0}
  3924. \index{subject}{parsing}
  3925. In this chapter we learn how to use the Lark parser
  3926. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3927. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3928. You are then asked to create a parser for \LangVar{} using Lark.
  3929. We also describe the parsing algorithms used inside Lark, studying the
  3930. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3931. A parser framework such as Lark takes in a specification of the
  3932. concrete syntax and an input program and produces a parse tree. Even
  3933. though a parser framework does most of the work for us, using one
  3934. properly requires some knowledge. In particular, we must learn about
  3935. its specification languages and we must learn how to deal with
  3936. ambiguity in our language specifications. Also, some algorithms, such
  3937. as LALR(1), place restrictions on the grammars they can handle, in
  3938. which case knowing the algorithm helps with trying to decipher the
  3939. error messages.
  3940. The process of parsing is traditionally subdivided into two phases:
  3941. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3942. analysis} (also called parsing). The lexical analysis phase
  3943. translates the sequence of characters into a sequence of
  3944. \emph{tokens}, that is, words consisting of several characters. The
  3945. parsing phase organizes the tokens into a \emph{parse tree} that
  3946. captures how the tokens were matched by rules in the grammar of the
  3947. language. The reason for the subdivision into two phases is to enable
  3948. the use of a faster but less powerful algorithm for lexical analysis
  3949. and the use of a slower but more powerful algorithm for parsing.
  3950. %
  3951. %% Likewise, parser generators typical come in pairs, with separate
  3952. %% generators for the lexical analyzer (or lexer for short) and for the
  3953. %% parser. A particularly influential pair of generators were
  3954. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3955. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3956. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3957. %% Compiler Compiler.
  3958. %
  3959. The Lark parser framework that we use in this chapter includes both
  3960. lexical analyzers and parsers. The next section discusses lexical
  3961. analysis, and the remainder of the chapter discusses parsing.
  3962. \section{Lexical Analysis and Regular Expressions}
  3963. \label{sec:lex}
  3964. The lexical analyzers produced by Lark turn a sequence of characters
  3965. (a string) into a sequence of token objects. For example, a Lark
  3966. generated lexer for \LangInt{} converts the string
  3967. \begin{lstlisting}
  3968. 'print(1 + 3)'
  3969. \end{lstlisting}
  3970. \noindent into the following sequence of token objects:
  3971. \begin{center}
  3972. \begin{minipage}{0.95\textwidth}
  3973. \begin{lstlisting}
  3974. Token('PRINT', 'print')
  3975. Token('LPAR', '(')
  3976. Token('INT', '1')
  3977. Token('PLUS', '+')
  3978. Token('INT', '3')
  3979. Token('RPAR', ')')
  3980. Token('NEWLINE', '\n')
  3981. \end{lstlisting}
  3982. \end{minipage}
  3983. \end{center}
  3984. Each token includes a field for its \code{type}, such as \skey{INT},
  3985. and a field for its \code{value}, such as \skey{1}.
  3986. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3987. specification language for Lark's lexer is one regular expression for
  3988. each type of token. The term \emph{regular} comes from the term
  3989. \emph{regular languages}, which are the languages that can be
  3990. recognized by a finite state machine. A \emph{regular expression} is a
  3991. pattern formed of the following core elements:\index{subject}{regular
  3992. expression}\footnote{Regular expressions traditionally include the
  3993. empty regular expression that matches any zero-length part of a
  3994. string, but Lark does not support the empty regular expression.}
  3995. \begin{itemize}
  3996. \item A single character $c$ is a regular expression, and it matches
  3997. only itself. For example, the regular expression \code{a} matches
  3998. only the string \skey{a}.
  3999. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  4000. R_2$ form a regular expression that matches any string that matches
  4001. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  4002. matches the string \skey{a} and the string \skey{c}.
  4003. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  4004. expression that matches any string that can be formed by
  4005. concatenating two strings, where the first string matches $R_1$ and
  4006. the second string matches $R_2$. For example, the regular expression
  4007. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  4008. (Parentheses can be used to control the grouping of operators within
  4009. a regular expression.)
  4010. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  4011. Kleene closure) is a regular expression that matches any string that
  4012. can be formed by concatenating zero or more strings that each match
  4013. the regular expression $R$. For example, the regular expression
  4014. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  4015. \skey{abc}.
  4016. \end{itemize}
  4017. For our convenience, Lark also accepts the following extended set of
  4018. regular expressions that are automatically translated into the core
  4019. regular expressions.
  4020. \begin{itemize}
  4021. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  4022. c_n]$ is a regular expression that matches any one of the
  4023. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  4024. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  4025. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  4026. a regular expression that matches any character between $c_1$ and
  4027. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  4028. letter in the alphabet.
  4029. \item A regular expression followed by the plus symbol $R\ttm{+}$
  4030. is a regular expression that matches any string that can
  4031. be formed by concatenating one or more strings that each match $R$.
  4032. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  4033. matches \skey{b} and \skey{bzca}.
  4034. \item A regular expression followed by a question mark $R\ttm{?}$
  4035. is a regular expression that matches any string that either
  4036. matches $R$ or is the empty string.
  4037. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  4038. \end{itemize}
  4039. In a Lark grammar file, each kind of token is specified by a
  4040. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4041. that consists of the name of the terminal followed by a colon followed
  4042. by a sequence of literals. The literals include strings such as
  4043. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4044. terminal names, and literals composed using the regular expression
  4045. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4046. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4047. \begin{center}
  4048. \begin{minipage}{0.95\textwidth}
  4049. \begin{lstlisting}
  4050. DIGIT: /[0-9]/
  4051. INT: "-"? DIGIT+
  4052. NEWLINE: (/\r/? /\n/)+
  4053. \end{lstlisting}
  4054. \end{minipage}
  4055. \end{center}
  4056. \section{Grammars and Parse Trees}
  4057. \label{sec:CFG}
  4058. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4059. specify the abstract syntax of a language. We now take a closer look
  4060. at using grammar rules to specify the concrete syntax. Recall that
  4061. each rule has a left-hand side and a right-hand side, where the
  4062. left-hand side is a nonterminal and the right-hand side is a pattern
  4063. that defines what can be parsed as that nonterminal. For concrete
  4064. syntax, each right-hand side expresses a pattern for a string instead
  4065. of a pattern for an abstract syntax tree. In particular, each
  4066. right-hand side is a sequence of
  4067. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4068. terminal or a nonterminal. The nonterminals play the same role as in
  4069. the abstract syntax, defining categories of syntax. The nonterminals
  4070. of a grammar include the tokens defined in the lexer and all the
  4071. nonterminals defined by the grammar rules.
  4072. As an example, let us take a closer look at the concrete syntax of the
  4073. \LangInt{} language, repeated here.
  4074. \[
  4075. \begin{array}{l}
  4076. \LintGrammarPython \\
  4077. \begin{array}{rcl}
  4078. \LangInt{} &::=& \Stmt^{*}
  4079. \end{array}
  4080. \end{array}
  4081. \]
  4082. The Lark syntax for grammar rules differs slightly from the variant of
  4083. BNF that we use in this book. In particular, the notation $::=$ is
  4084. replaced by a single colon, and the use of typewriter font for string
  4085. literals is replaced by quotation marks. The following grammar serves
  4086. as a first draft of a Lark grammar for \LangInt{}.
  4087. \begin{center}
  4088. \begin{minipage}{0.95\textwidth}
  4089. \begin{lstlisting}[escapechar=$]
  4090. exp: INT
  4091. | "input_int" "(" ")"
  4092. | "-" exp
  4093. | exp "+" exp
  4094. | exp "-" exp
  4095. | "(" exp ")"
  4096. stmt_list:
  4097. | stmt NEWLINE stmt_list
  4098. lang_int: stmt_list
  4099. \end{lstlisting}
  4100. \end{minipage}
  4101. \end{center}
  4102. Let us begin by discussing the rule \code{exp: INT}, which says that
  4103. if the lexer matches a string to \code{INT}, then the parser also
  4104. categorizes the string as an \code{exp}. Recall that in
  4105. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4106. nonterminal with a sentence in English. Here we specify \code{INT}
  4107. more formally using a type of token \code{INT} and its regular
  4108. expression \code{"-"? DIGIT+}.
  4109. The rule \code{exp: exp "+" exp} says that any string that matches
  4110. \code{exp}, followed by the \code{+} character, followed by another
  4111. string that matches \code{exp}, is itself an \code{exp}. For example,
  4112. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4113. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4114. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4115. \code{exp}. We can visualize the application of grammar rules to parse
  4116. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4117. internal node in the tree is an application of a grammar rule and is
  4118. labeled with its left-hand side nonterminal. Each leaf node is a
  4119. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4120. shown in figure~\ref{fig:simple-parse-tree}.
  4121. \begin{figure}[tbp]
  4122. \begin{tcolorbox}[colback=white]
  4123. \centering
  4124. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4125. \end{tcolorbox}
  4126. \caption{The parse tree for \lstinline{'1+3'}.}
  4127. \label{fig:simple-parse-tree}
  4128. \end{figure}
  4129. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4130. following parse tree as represented by \code{Tree} and \code{Token}
  4131. objects.
  4132. \begin{lstlisting}
  4133. Tree('lang_int',
  4134. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4135. Tree('exp', [Token('INT', '3')])])]),
  4136. Token('NEWLINE', '\n')])
  4137. \end{lstlisting}
  4138. The nodes that come from the lexer are \code{Token} objects, whereas
  4139. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4140. object has a \code{data} field containing the name of the nonterminal
  4141. for the grammar rule that was applied. Each \code{Tree} object also
  4142. has a \code{children} field that is a list containing trees and/or
  4143. tokens. Note that Lark does not produce nodes for string literals in
  4144. the grammar. For example, the \code{Tree} node for the addition
  4145. expression has only two children for the two integers but is missing
  4146. its middle child for the \code{"+"} terminal. This would be
  4147. problematic except that Lark provides a mechanism for customizing the
  4148. \code{data} field of each \code{Tree} node on the basis of which rule was
  4149. applied. Next to each alternative in a grammar rule, write \code{->}
  4150. followed by a string that you want to appear in the \code{data}
  4151. field. The following is a second draft of a Lark grammar for
  4152. \LangInt{}, this time with more specific labels on the \code{Tree}
  4153. nodes.
  4154. \begin{center}
  4155. \begin{minipage}{0.95\textwidth}
  4156. \begin{lstlisting}[escapechar=$]
  4157. exp: INT -> int
  4158. | "input_int" "(" ")" -> input_int
  4159. | "-" exp -> usub
  4160. | exp "+" exp -> add
  4161. | exp "-" exp -> sub
  4162. | "(" exp ")" -> paren
  4163. stmt: "print" "(" exp ")" -> print
  4164. | exp -> expr
  4165. stmt_list: -> empty_stmt
  4166. | stmt NEWLINE stmt_list -> add_stmt
  4167. lang_int: stmt_list -> module
  4168. \end{lstlisting}
  4169. \end{minipage}
  4170. \end{center}
  4171. Here is the resulting parse tree.
  4172. \begin{lstlisting}
  4173. Tree('module',
  4174. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4175. Tree('int', [Token('INT', '3')])])]),
  4176. Token('NEWLINE', '\n')])
  4177. \end{lstlisting}
  4178. \section{Ambiguous Grammars}
  4179. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4180. can be parsed in more than one way. For example, consider the string
  4181. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4182. our draft grammar, resulting in the two parse trees shown in
  4183. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4184. interpreting the second parse tree would yield \code{-4} even through
  4185. the correct answer is \code{2}.
  4186. \begin{figure}[tbp]
  4187. \begin{tcolorbox}[colback=white]
  4188. \centering
  4189. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4190. \end{tcolorbox}
  4191. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4192. \label{fig:ambig-parse-tree}
  4193. \end{figure}
  4194. To deal with this problem we can change the grammar by categorizing
  4195. the syntax in a more fine-grained fashion. In this case we want to
  4196. disallow the application of the rule \code{exp: exp "-" exp} when the
  4197. child on the right is an addition. To do this we can replace the
  4198. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4199. the expressions except for addition, as in the following.
  4200. \begin{center}
  4201. \begin{minipage}{0.95\textwidth}
  4202. \begin{lstlisting}[escapechar=$]
  4203. exp: exp "-" exp_no_add -> sub
  4204. | exp "+" exp -> add
  4205. | exp_no_add
  4206. exp_no_add: INT -> int
  4207. | "input_int" "(" ")" -> input_int
  4208. | "-" exp -> usub
  4209. | exp "-" exp_no_add -> sub
  4210. | "(" exp ")" -> paren
  4211. \end{lstlisting}
  4212. \end{minipage}
  4213. \end{center}
  4214. However, there remains some ambiguity in the grammar. For example, the
  4215. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4216. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4217. (incorrect). That is, subtraction is left associative. Likewise,
  4218. addition in Python is left associative. We also need to consider the
  4219. interaction of unary subtraction with both addition and
  4220. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4221. has higher \emph{precedence}\index{subject}{precedence} than addition
  4222. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4223. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4224. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4225. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4226. all the other expressions, and it uses \code{exp\_hi} for the second
  4227. child in the rules for addition and subtraction. Furthermore, unary
  4228. subtraction uses \code{exp\_hi} for its child.
  4229. For languages with more operators and more precedence levels, one must
  4230. refine the \code{exp} nonterminal into several nonterminals, one for
  4231. each precedence level.
  4232. \begin{figure}[tbp]
  4233. \begin{tcolorbox}[colback=white]
  4234. \centering
  4235. \begin{lstlisting}[escapechar=$]
  4236. exp: exp "+" exp_hi -> add
  4237. | exp "-" exp_hi -> sub
  4238. | exp_hi
  4239. exp_hi: INT -> int
  4240. | "input_int" "(" ")" -> input_int
  4241. | "-" exp_hi -> usub
  4242. | "(" exp ")" -> paren
  4243. stmt: "print" "(" exp ")" -> print
  4244. | exp -> expr
  4245. stmt_list: -> empty_stmt
  4246. | stmt NEWLINE stmt_list -> add_stmt
  4247. lang_int: stmt_list -> module
  4248. \end{lstlisting}
  4249. \end{tcolorbox}
  4250. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4251. \label{fig:Lint-lark-grammar}
  4252. \end{figure}
  4253. \section{From Parse Trees to Abstract Syntax Trees}
  4254. As we have seen, the output of a Lark parser is a parse tree, that is,
  4255. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4256. step is to convert the parse tree to an abstract syntax tree. This can
  4257. be accomplished with a recursive function that inspects the
  4258. \code{data} field of each node and then constructs the corresponding
  4259. AST node, using recursion to handle its children. The following is an
  4260. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4261. \begin{center}
  4262. \begin{minipage}{0.95\textwidth}
  4263. \begin{lstlisting}
  4264. def parse_tree_to_ast(e):
  4265. if e.data == 'int':
  4266. return Constant(int(e.children[0].value))
  4267. elif e.data == 'input_int':
  4268. return Call(Name('input_int'), [])
  4269. elif e.data == 'add':
  4270. e1, e2 = e.children
  4271. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4272. ...
  4273. else:
  4274. raise Exception('unhandled parse tree', e)
  4275. \end{lstlisting}
  4276. \end{minipage}
  4277. \end{center}
  4278. \begin{exercise}
  4279. \normalfont\normalsize
  4280. %
  4281. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4282. default parsing algorithm (Earley) with the \code{ambiguity} option
  4283. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4284. output will include multiple parse trees that will indicate to you
  4285. that there is a problem with your grammar. Your parser should ignore
  4286. white space, so we recommend using Lark's \code{\%ignore} directive
  4287. as follows.
  4288. \begin{lstlisting}
  4289. %import common.WS_INLINE
  4290. %ignore WS_INLINE
  4291. \end{lstlisting}
  4292. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4293. Lark parser instead of using the \code{parse} function from
  4294. the \code{ast} module. Test your compiler on all the \LangVar{}
  4295. programs that you have created, and create four additional programs
  4296. that test for ambiguities in your grammar.
  4297. \end{exercise}
  4298. \section{Earley's Algorithm}
  4299. \label{sec:earley}
  4300. In this section we discuss the parsing algorithm of
  4301. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4302. algorithm is powerful in that it can handle any context-free grammar,
  4303. which makes it easy to use, but it is not a particularly
  4304. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4305. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4306. the number of tokens in the input
  4307. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4308. learn about the LALR(1) algorithm, which is more efficient but cannot
  4309. handle all context-free grammars.
  4310. Earley's algorithm can be viewed as an interpreter; it treats the
  4311. grammar as the program being interpreted, and it treats the concrete
  4312. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4313. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4314. keep track of its progress and to store its results. The chart is an
  4315. array with one slot for each position in the input string, where
  4316. position $0$ is before the first character and position $n$ is
  4317. immediately after the last character. So, the array has length $n+1$
  4318. for an input string of length $n$. Each slot in the chart contains a
  4319. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4320. with a period indicating how much of its right-hand side has already
  4321. been parsed. For example, the dotted rule
  4322. \begin{lstlisting}
  4323. exp: exp "+" . exp_hi
  4324. \end{lstlisting}
  4325. represents a partial parse that has matched an \code{exp} followed by
  4326. \code{+} but has not yet parsed an \code{exp} to the right of
  4327. \code{+}.
  4328. %
  4329. Earley's algorithm starts with an initialization phase and then
  4330. repeats three actions---prediction, scanning, and completion---for as
  4331. long as opportunities arise. We demonstrate Earley's algorithm on a
  4332. running example, parsing the following program:
  4333. \begin{lstlisting}
  4334. print(1 + 3)
  4335. \end{lstlisting}
  4336. The algorithm's initialization phase creates dotted rules for all the
  4337. grammar rules whose left-hand side is the start symbol and places them
  4338. in slot $0$ of the chart. We also record the starting position of the
  4339. dotted rule in parentheses on the right. For example, given the
  4340. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4341. \begin{lstlisting}
  4342. lang_int: . stmt_list (0)
  4343. \end{lstlisting}
  4344. in slot $0$ of the chart. The algorithm then proceeds with
  4345. \emph{prediction} actions in which it adds more dotted rules to the
  4346. chart based on the nonterminals that come immediately after a period. In
  4347. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4348. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4349. period at the beginning of their right-hand sides, as follows:
  4350. \begin{lstlisting}
  4351. stmt_list: . (0)
  4352. stmt_list: . stmt NEWLINE stmt_list (0)
  4353. \end{lstlisting}
  4354. We continue to perform prediction actions as more opportunities
  4355. arise. For example, the \code{stmt} nonterminal now appears after a
  4356. period, so we add all the rules for \code{stmt}.
  4357. \begin{lstlisting}
  4358. stmt: . "print" "(" exp ")" (0)
  4359. stmt: . exp (0)
  4360. \end{lstlisting}
  4361. This reveals yet more opportunities for prediction, so we add the grammar
  4362. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4363. \begin{lstlisting}[escapechar=$]
  4364. exp: . exp "+" exp_hi (0)
  4365. exp: . exp "-" exp_hi (0)
  4366. exp: . exp_hi (0)
  4367. exp_hi: . INT (0)
  4368. exp_hi: . "input_int" "(" ")" (0)
  4369. exp_hi: . "-" exp_hi (0)
  4370. exp_hi: . "(" exp ")" (0)
  4371. \end{lstlisting}
  4372. We have exhausted the opportunities for prediction, so the algorithm
  4373. proceeds to \emph{scanning}, in which we inspect the next input token
  4374. and look for a dotted rule at the current position that has a matching
  4375. terminal immediately following the period. In our running example, the
  4376. first input token is \code{"print"}, so we identify the rule in slot
  4377. $0$ of the chart where \code{"print"} follows the period:
  4378. \begin{lstlisting}
  4379. stmt: . "print" "(" exp ")" (0)
  4380. \end{lstlisting}
  4381. We advance the period past \code{"print"} and add the resulting rule
  4382. to slot $1$:
  4383. \begin{lstlisting}
  4384. stmt: "print" . "(" exp ")" (0)
  4385. \end{lstlisting}
  4386. If the new dotted rule had a nonterminal after the period, we would
  4387. need to carry out a prediction action, adding more dotted rules to
  4388. slot $1$. That is not the case, so we continue scanning. The next
  4389. input token is \code{"("}, so we add the following to slot $2$ of the
  4390. chart.
  4391. \begin{lstlisting}
  4392. stmt: "print" "(" . exp ")" (0)
  4393. \end{lstlisting}
  4394. Now we have a nonterminal after the period, so we carry out several
  4395. prediction actions, adding dotted rules for \code{exp} and
  4396. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4397. starting position $2$.
  4398. \begin{lstlisting}[escapechar=$]
  4399. exp: . exp "+" exp_hi (2)
  4400. exp: . exp "-" exp_hi (2)
  4401. exp: . exp_hi (2)
  4402. exp_hi: . INT (2)
  4403. exp_hi: . "input_int" "(" ")" (2)
  4404. exp_hi: . "-" exp_hi (2)
  4405. exp_hi: . "(" exp ")" (2)
  4406. \end{lstlisting}
  4407. With this prediction complete, we return to scanning, noting that the
  4408. next input token is \code{"1"}, which the lexer parses as an
  4409. \code{INT}. There is a matching rule in slot $2$:
  4410. \begin{lstlisting}
  4411. exp_hi: . INT (2)
  4412. \end{lstlisting}
  4413. so we advance the period and put the following rule into slot $3$.
  4414. \begin{lstlisting}
  4415. exp_hi: INT . (2)
  4416. \end{lstlisting}
  4417. This brings us to \emph{completion} actions. When the period reaches
  4418. the end of a dotted rule, we recognize that the substring
  4419. has matched the nonterminal on the left-hand side of the rule, in this case
  4420. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4421. rules into slot $2$ (the starting position for the finished rule) if
  4422. the period is immediately followed by \code{exp\_hi}. So we identify
  4423. \begin{lstlisting}
  4424. exp: . exp_hi (2)
  4425. \end{lstlisting}
  4426. and add the following dotted rule to slot $3$
  4427. \begin{lstlisting}
  4428. exp: exp_hi . (2)
  4429. \end{lstlisting}
  4430. This triggers another completion step for the nonterminal \code{exp},
  4431. adding two more dotted rules to slot $3$.
  4432. \begin{lstlisting}[escapechar=$]
  4433. exp: exp . "+" exp_hi (2)
  4434. exp: exp . "-" exp_hi (2)
  4435. \end{lstlisting}
  4436. Returning to scanning, the next input token is \code{"+"}, so
  4437. we add the following to slot $4$.
  4438. \begin{lstlisting}[escapechar=$]
  4439. exp: exp "+" . exp_hi (2)
  4440. \end{lstlisting}
  4441. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4442. the following dotted rules to slot $4$ of the chart.
  4443. \begin{lstlisting}[escapechar=$]
  4444. exp_hi: . INT (4)
  4445. exp_hi: . "input_int" "(" ")" (4)
  4446. exp_hi: . "-" exp_hi (4)
  4447. exp_hi: . "(" exp ")" (4)
  4448. \end{lstlisting}
  4449. The next input token is \code{"3"} which the lexer categorized as an
  4450. \code{INT}, so we advance the period past \code{INT} for the rules in
  4451. slot $4$, of which there is just one, and put the following into slot $5$.
  4452. \begin{lstlisting}[escapechar=$]
  4453. exp_hi: INT . (4)
  4454. \end{lstlisting}
  4455. The period at the end of the rule triggers a completion action for the
  4456. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4457. So we advance the period and put the following into slot $5$.
  4458. \begin{lstlisting}[escapechar=$]
  4459. exp: exp "+" exp_hi . (2)
  4460. \end{lstlisting}
  4461. This triggers another completion action for the rules in slot $2$ that
  4462. have a period before \code{exp}.
  4463. \begin{lstlisting}[escapechar=$]
  4464. stmt: "print" "(" exp . ")" (0)
  4465. exp: exp . "+" exp_hi (2)
  4466. exp: exp . "-" exp_hi (2)
  4467. \end{lstlisting}
  4468. We scan the next input token \code{")"}, placing the following dotted
  4469. rule into slot $6$.
  4470. \begin{lstlisting}[escapechar=$]
  4471. stmt: "print" "(" exp ")" . (0)
  4472. \end{lstlisting}
  4473. This triggers the completion of \code{stmt} in slot $0$
  4474. \begin{lstlisting}
  4475. stmt_list: stmt . NEWLINE stmt_list (0)
  4476. \end{lstlisting}
  4477. The last input token is a \code{NEWLINE}, so we advance the period
  4478. and place the new dotted rule into slot $7$.
  4479. \begin{lstlisting}
  4480. stmt_list: stmt NEWLINE . stmt_list (0)
  4481. \end{lstlisting}
  4482. We are close to the end of parsing the input!
  4483. The period is before the \code{stmt\_list} nonterminal, so we
  4484. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4485. \begin{lstlisting}
  4486. stmt_list: . (7)
  4487. stmt_list: . stmt NEWLINE stmt_list (7)
  4488. stmt: . "print" "(" exp ")" (7)
  4489. stmt: . exp (7)
  4490. \end{lstlisting}
  4491. There is immediately an opportunity for completion of \code{stmt\_list},
  4492. so we add the following to slot $7$.
  4493. \begin{lstlisting}
  4494. stmt_list: stmt NEWLINE stmt_list . (0)
  4495. \end{lstlisting}
  4496. This triggers another completion action for \code{stmt\_list} in slot $0$
  4497. \begin{lstlisting}
  4498. lang_int: stmt_list . (0)
  4499. \end{lstlisting}
  4500. which in turn completes \code{lang\_int}, the start symbol of the
  4501. grammar, so the parsing of the input is complete.
  4502. For reference, we give a general description of Earley's
  4503. algorithm.
  4504. \begin{enumerate}
  4505. \item The algorithm begins by initializing slot $0$ of the chart with the
  4506. grammar rule for the start symbol, placing a period at the beginning
  4507. of the right-hand side, and recording its starting position as $0$.
  4508. \item The algorithm repeatedly applies the following three kinds of
  4509. actions for as long as there are opportunities to do so.
  4510. \begin{itemize}
  4511. \item Prediction: If there is a rule in slot $k$ whose period comes
  4512. before a nonterminal, add the rules for that nonterminal into slot
  4513. $k$, placing a period at the beginning of their right-hand sides
  4514. and recording their starting position as $k$.
  4515. \item Scanning: If the token at position $k$ of the input string
  4516. matches the symbol after the period in a dotted rule in slot $k$
  4517. of the chart, advance the period in the dotted rule, adding
  4518. the result to slot $k+1$.
  4519. \item Completion: If a dotted rule in slot $k$ has a period at the
  4520. end, inspect the rules in the slot corresponding to the starting
  4521. position of the completed rule. If any of those rules have a
  4522. nonterminal following their period that matches the left-hand side
  4523. of the completed rule, then advance their period, placing the new
  4524. dotted rule in slot $k$.
  4525. \end{itemize}
  4526. While repeating these three actions, take care never to add
  4527. duplicate dotted rules to the chart.
  4528. \end{enumerate}
  4529. We have described how Earley's algorithm recognizes that an input
  4530. string matches a grammar, but we have not described how it builds a
  4531. parse tree. The basic idea is simple, but building parse trees in an
  4532. efficient way is more complex, requiring a data structure called a
  4533. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4534. to attach a partial parse tree to every dotted rule in the chart.
  4535. Initially, the node associated with a dotted rule has no
  4536. children. As the period moves to the right, the nodes from the
  4537. subparses are added as children to the node.
  4538. As mentioned at the beginning of this section, Earley's algorithm is
  4539. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4540. files that contain thousands of tokens in a reasonable amount of time,
  4541. but not millions.
  4542. %
  4543. In the next section we discuss the LALR(1) parsing algorithm, which is
  4544. efficient enough to use with even the largest of input files.
  4545. \section{The LALR(1) Algorithm}
  4546. \label{sec:lalr}
  4547. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4548. two-phase approach in which it first compiles the grammar into a state
  4549. machine and then runs the state machine to parse an input string. The
  4550. second phase has time complexity $O(n)$ where $n$ is the number of
  4551. tokens in the input, so LALR(1) is the best one could hope for with
  4552. respect to efficiency.
  4553. %
  4554. A particularly influential implementation of LALR(1) is the
  4555. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4556. \texttt{yacc} stands for ``yet another compiler compiler.''
  4557. %
  4558. The LALR(1) state machine uses a stack to record its progress in
  4559. parsing the input string. Each element of the stack is a pair: a
  4560. state number and a grammar symbol (a terminal or a nonterminal). The
  4561. symbol characterizes the input that has been parsed so far, and the
  4562. state number is used to remember how to proceed once the next
  4563. symbol's worth of input has been parsed. Each state in the machine
  4564. represents where the parser stands in the parsing process with respect
  4565. to certain grammar rules. In particular, each state is associated with
  4566. a set of dotted rules.
  4567. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4568. (also called parse table) for the following simple but ambiguous
  4569. grammar:
  4570. \begin{lstlisting}[escapechar=$]
  4571. exp: INT
  4572. | exp "+" exp
  4573. stmt: "print" exp
  4574. start: stmt
  4575. \end{lstlisting}
  4576. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4577. read in a \lstinline{"print"} token, so the top of the stack is
  4578. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4579. the input according to grammar rule 1, which is signified by showing
  4580. rule 1 with a period after the \code{"print"} token and before the
  4581. \code{exp} nonterminal. There are two rules that could apply next,
  4582. rules 2 and 3, so state 1 also shows those rules with a period at
  4583. the beginning of their right-hand sides. The edges between states
  4584. indicate which transitions the machine should make depending on the
  4585. next input token. So, for example, if the next input token is
  4586. \code{INT} then the parser will push \code{INT} and the target state 4
  4587. on the stack and transition to state 4. Suppose that we are now at the end
  4588. of the input. State 4 says that we should reduce by rule 3, so we pop
  4589. from the stack the same number of items as the number of symbols in
  4590. the right-hand side of the rule, in this case just one. We then
  4591. momentarily jump to the state at the top of the stack (state 1) and
  4592. then follow the goto edge that corresponds to the left-hand side of
  4593. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4594. state 3. (A slightly longer example parse is shown in
  4595. figure~\ref{fig:shift-reduce}.)
  4596. \begin{figure}[tbp]
  4597. \centering
  4598. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4599. \caption{An LALR(1) parse table and a trace of an example run.}
  4600. \label{fig:shift-reduce}
  4601. \end{figure}
  4602. In general, the algorithm works as follows. First, set the current state to
  4603. state $0$. Then repeat the following, looking at the next input token.
  4604. \begin{itemize}
  4605. \item If there there is a shift edge for the input token in the
  4606. current state, push the edge's target state and the input token onto
  4607. the stack and proceed to the edge's target state.
  4608. \item If there is a reduce action for the input token in the current
  4609. state, pop $k$ elements from the stack, where $k$ is the number of
  4610. symbols in the right-hand side of the rule being reduced. Jump to
  4611. the state at the top of the stack and then follow the goto edge for
  4612. the nonterminal that matches the left-hand side of the rule that we
  4613. are reducing by. Push the edge's target state and the nonterminal on the
  4614. stack.
  4615. \end{itemize}
  4616. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4617. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4618. algorithm does not know which action to take in this case. When a
  4619. state has both a shift and a reduce action for the same token, we say
  4620. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4621. will arise, for example, in trying to parse the input
  4622. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4623. the parser will be in state 6 and will not know whether to
  4624. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4625. to proceed by shifting the next \lstinline{+} from the input.
  4626. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4627. arises when there are two reduce actions in a state for the same
  4628. token. To understand which grammars give rise to shift/reduce and
  4629. reduce/reduce conflicts, it helps to know how the parse table is
  4630. generated from the grammar, which we discuss next.
  4631. The parse table is generated one state at a time. State 0 represents
  4632. the start of the parser. We add the grammar rule for the start symbol
  4633. to this state with a period at the beginning of the right-hand side,
  4634. similarly to the initialization phase of the Earley parser. If the
  4635. period appears immediately before another nonterminal, we add all the
  4636. rules with that nonterminal on the left-hand side. Again, we place a
  4637. period at the beginning of the right-hand side of each new
  4638. rule. This process, called \emph{state closure}, is continued
  4639. until there are no more rules to add (similarly to the prediction
  4640. actions of an Earley parser). We then examine each dotted rule in the
  4641. current state $I$. Suppose that a dotted rule has the form $A ::=
  4642. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4643. are sequences of symbols. We create a new state and call it $J$. If $X$
  4644. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4645. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4646. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4647. state $J$. We start by adding all dotted rules from state $I$ that
  4648. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4649. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4650. the period moved past the $X$. (This is analogous to completion in
  4651. Earley's algorithm.) We then perform state closure on $J$. This
  4652. process repeats until there are no more states or edges to add.
  4653. We then mark states as accepting states if they have a dotted rule
  4654. that is the start rule with a period at the end. Also, to add
  4655. the reduce actions, we look for any state containing a dotted rule
  4656. with a period at the end. Let $n$ be the rule number for this dotted
  4657. rule. We then put a reduce $n$ action into that state for every token
  4658. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4659. dotted rule with a period at the end. We therefore put a reduce by
  4660. rule 3 action into state 4 for every
  4661. token.
  4662. When inserting reduce actions, take care to spot any shift/reduce or
  4663. reduce/reduce conflicts. If there are any, abort the construction of
  4664. the parse table.
  4665. \begin{exercise}
  4666. \normalfont\normalsize
  4667. %
  4668. Working on paper, walk through the parse table generation process for
  4669. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4670. your results against the parse table shown in
  4671. figure~\ref{fig:shift-reduce}.
  4672. \end{exercise}
  4673. \begin{exercise}
  4674. \normalfont\normalsize
  4675. %
  4676. Change the parser in your compiler for \LangVar{} to set the
  4677. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4678. all the \LangVar{} programs that you have created. In doing so, Lark
  4679. may signal an error due to shift/reduce or reduce/reduce conflicts
  4680. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4681. remove those conflicts.
  4682. \end{exercise}
  4683. \section{Further Reading}
  4684. In this chapter we have just scratched the surface of the field of
  4685. parsing, with the study of a very general but less efficient algorithm
  4686. (Earley) and with a more limited but highly efficient algorithm
  4687. (LALR). There are many more algorithms and classes of grammars that
  4688. fall between these two ends of the spectrum. We recommend to the reader
  4689. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4690. Regarding lexical analysis, we have described the specification
  4691. language, which are the regular expressions, but not the algorithms
  4692. for recognizing them. In short, regular expressions can be translated
  4693. to nondeterministic finite automata, which in turn are translated to
  4694. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4695. all the details on lexical analysis.
  4696. \fi}
  4697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4698. \chapter{Register Allocation}
  4699. \label{ch:register-allocation-Lvar}
  4700. \setcounter{footnote}{0}
  4701. \index{subject}{register allocation}
  4702. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4703. storing variables on the procedure call stack. The CPU may require tens
  4704. to hundreds of cycles to access a location on the stack, whereas
  4705. accessing a register takes only a single cycle. In this chapter we
  4706. improve the efficiency of our generated code by storing some variables
  4707. in registers. The goal of register allocation is to fit as many
  4708. variables into registers as possible. Some programs have more
  4709. variables than registers, so we cannot always map each variable to a
  4710. different register. Fortunately, it is common for different variables
  4711. to be in use during different periods of time during program
  4712. execution, and in those cases we can map multiple variables to the
  4713. same register.
  4714. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4715. example. The source program is on the left and the output of
  4716. instruction selection\index{subject}{instruction selection}
  4717. is on the right. The program is almost
  4718. completely in the x86 assembly language, but it still uses variables.
  4719. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4720. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4721. the other hand, is used only after this point, so \code{x} and
  4722. \code{z} could share the same register.
  4723. \begin{figure}
  4724. \begin{tcolorbox}[colback=white]
  4725. \begin{minipage}{0.45\textwidth}
  4726. Example \LangVar{} program:
  4727. % var_test_28.rkt
  4728. {\if\edition\racketEd
  4729. \begin{lstlisting}
  4730. (let ([v 1])
  4731. (let ([w 42])
  4732. (let ([x (+ v 7)])
  4733. (let ([y x])
  4734. (let ([z (+ x w)])
  4735. (+ z (- y)))))))
  4736. \end{lstlisting}
  4737. \fi}
  4738. {\if\edition\pythonEd\pythonColor
  4739. \begin{lstlisting}
  4740. v = 1
  4741. w = 42
  4742. x = v + 7
  4743. y = x
  4744. z = x + w
  4745. print(z + (- y))
  4746. \end{lstlisting}
  4747. \fi}
  4748. \end{minipage}
  4749. \begin{minipage}{0.45\textwidth}
  4750. After instruction selection:
  4751. {\if\edition\racketEd
  4752. \begin{lstlisting}
  4753. locals-types:
  4754. x : Integer, y : Integer,
  4755. z : Integer, t : Integer,
  4756. v : Integer, w : Integer
  4757. start:
  4758. movq $1, v
  4759. movq $42, w
  4760. movq v, x
  4761. addq $7, x
  4762. movq x, y
  4763. movq x, z
  4764. addq w, z
  4765. movq y, t
  4766. negq t
  4767. movq z, %rax
  4768. addq t, %rax
  4769. jmp conclusion
  4770. \end{lstlisting}
  4771. \fi}
  4772. {\if\edition\pythonEd\pythonColor
  4773. \begin{lstlisting}
  4774. movq $1, v
  4775. movq $42, w
  4776. movq v, x
  4777. addq $7, x
  4778. movq x, y
  4779. movq x, z
  4780. addq w, z
  4781. movq y, tmp_0
  4782. negq tmp_0
  4783. movq z, tmp_1
  4784. addq tmp_0, tmp_1
  4785. movq tmp_1, %rdi
  4786. callq print_int
  4787. \end{lstlisting}
  4788. \fi}
  4789. \end{minipage}
  4790. \end{tcolorbox}
  4791. \caption{A running example for register allocation.}
  4792. \label{fig:reg-eg}
  4793. \end{figure}
  4794. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4795. compute where a variable is in use. Once we have that information, we
  4796. compute which variables are in use at the same time, that is, which ones
  4797. \emph{interfere}\index{subject}{interfere} with each other, and
  4798. represent this relation as an undirected graph whose vertices are
  4799. variables and edges indicate when two variables interfere
  4800. (section~\ref{sec:build-interference}). We then model register
  4801. allocation as a graph coloring problem
  4802. (section~\ref{sec:graph-coloring}).
  4803. If we run out of registers despite these efforts, we place the
  4804. remaining variables on the stack, similarly to how we handled
  4805. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4806. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4807. location. The decision to spill a variable is handled as part of the
  4808. graph coloring process.
  4809. We make the simplifying assumption that each variable is assigned to
  4810. one location (a register or stack address). A more sophisticated
  4811. approach is to assign a variable to one or more locations in different
  4812. regions of the program. For example, if a variable is used many times
  4813. in short sequence and then used again only after many other
  4814. instructions, it could be more efficient to assign the variable to a
  4815. register during the initial sequence and then move it to the stack for
  4816. the rest of its lifetime. We refer the interested reader to
  4817. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4818. approach.
  4819. % discuss prioritizing variables based on how much they are used.
  4820. \section{Registers and Calling Conventions}
  4821. \label{sec:calling-conventions}
  4822. \index{subject}{calling conventions}
  4823. As we perform register allocation, we must be aware of the
  4824. \emph{calling conventions} \index{subject}{calling conventions} that
  4825. govern how function calls are performed in x86.
  4826. %
  4827. Even though \LangVar{} does not include programmer-defined functions,
  4828. our generated code includes a \code{main} function that is called by
  4829. the operating system and our generated code contains calls to the
  4830. \code{read\_int} function.
  4831. Function calls require coordination between two pieces of code that
  4832. may be written by different programmers or generated by different
  4833. compilers. Here we follow the System V calling conventions that are
  4834. used by the GNU C compiler on Linux and
  4835. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4836. %
  4837. The calling conventions include rules about how functions share the
  4838. use of registers. In particular, the caller is responsible for freeing
  4839. some registers prior to the function call for use by the callee.
  4840. These are called the \emph{caller-saved registers}
  4841. \index{subject}{caller-saved registers}
  4842. and they are
  4843. \begin{lstlisting}
  4844. rax rcx rdx rsi rdi r8 r9 r10 r11
  4845. \end{lstlisting}
  4846. On the other hand, the callee is responsible for preserving the values
  4847. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4848. which are
  4849. \begin{lstlisting}
  4850. rsp rbp rbx r12 r13 r14 r15
  4851. \end{lstlisting}
  4852. We can think about this caller/callee convention from two points of
  4853. view, the caller view and the callee view, as follows:
  4854. \begin{itemize}
  4855. \item The caller should assume that all the caller-saved registers get
  4856. overwritten with arbitrary values by the callee. On the other hand,
  4857. the caller can safely assume that all the callee-saved registers
  4858. retain their original values.
  4859. \item The callee can freely use any of the caller-saved registers.
  4860. However, if the callee wants to use a callee-saved register, the
  4861. callee must arrange to put the original value back in the register
  4862. prior to returning to the caller. This can be accomplished by saving
  4863. the value to the stack in the prelude of the function and restoring
  4864. the value in the conclusion of the function.
  4865. \end{itemize}
  4866. In x86, registers are also used for passing arguments to a function
  4867. and for the return value. In particular, the first six arguments of a
  4868. function are passed in the following six registers, in this order.
  4869. \begin{lstlisting}
  4870. rdi rsi rdx rcx r8 r9
  4871. \end{lstlisting}
  4872. We refer to these six registers are the argument-passing registers
  4873. \index{subject}{argument-passing registers}.
  4874. If there are more than six arguments, the convention is to use space
  4875. on the frame of the caller for the rest of the arguments. In
  4876. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4877. argument and the rest of the arguments, which simplifies the treatment
  4878. of efficient tail calls.
  4879. %
  4880. \racket{For now, the only function we care about is \code{read\_int},
  4881. which takes zero arguments.}
  4882. %
  4883. \python{For now, the only functions we care about are \code{read\_int}
  4884. and \code{print\_int}, which take zero and one argument, respectively.}
  4885. %
  4886. The register \code{rax} is used for the return value of a function.
  4887. The next question is how these calling conventions impact register
  4888. allocation. Consider the \LangVar{} program presented in
  4889. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4890. example from the caller point of view and then from the callee point
  4891. of view. We refer to a variable that is in use during a function call
  4892. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4893. The program makes two calls to \READOP{}. The variable \code{x} is
  4894. call-live because it is in use during the second call to \READOP{}; we
  4895. must ensure that the value in \code{x} does not get overwritten during
  4896. the call to \READOP{}. One obvious approach is to save all the values
  4897. that reside in caller-saved registers to the stack prior to each
  4898. function call and to restore them after each call. That way, if the
  4899. register allocator chooses to assign \code{x} to a caller-saved
  4900. register, its value will be preserved across the call to \READOP{}.
  4901. However, saving and restoring to the stack is relatively slow. If
  4902. \code{x} is not used many times, it may be better to assign \code{x}
  4903. to a stack location in the first place. Or better yet, if we can
  4904. arrange for \code{x} to be placed in a callee-saved register, then it
  4905. won't need to be saved and restored during function calls.
  4906. We recommend an approach that captures these issues in the
  4907. interference graph, without complicating the graph coloring algorithm.
  4908. During liveness analysis we know which variables are call-live because
  4909. we compute which variables are in use at every instruction
  4910. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4911. interference graph (section~\ref{sec:build-interference}), we can
  4912. place an edge in the interference graph between each call-live
  4913. variable and the caller-saved registers. This will prevent the graph
  4914. coloring algorithm from assigning call-live variables to caller-saved
  4915. registers.
  4916. On the other hand, for variables that are not call-live, we prefer
  4917. placing them in caller-saved registers to leave more room for
  4918. call-live variables in the callee-saved registers. This can also be
  4919. implemented without complicating the graph coloring algorithm. We
  4920. recommend that the graph coloring algorithm assign variables to
  4921. natural numbers, choosing the lowest number for which there is no
  4922. interference. After the coloring is complete, we map the numbers to
  4923. registers and stack locations: mapping the lowest numbers to
  4924. caller-saved registers, the next lowest to callee-saved registers, and
  4925. the largest numbers to stack locations. This ordering gives preference
  4926. to registers over stack locations and to caller-saved registers over
  4927. callee-saved registers.
  4928. Returning to the example in
  4929. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4930. generated x86 code on the right-hand side. Variable \code{x} is
  4931. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4932. in a safe place during the second call to \code{read\_int}. Next,
  4933. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4934. because \code{y} is not a call-live variable.
  4935. We have completed the analysis from the caller point of view, so now
  4936. we switch to the callee point of view, focusing on the prelude and
  4937. conclusion of the \code{main} function. As usual, the prelude begins
  4938. with saving the \code{rbp} register to the stack and setting the
  4939. \code{rbp} to the current stack pointer. We now know why it is
  4940. necessary to save the \code{rbp}: it is a callee-saved register. The
  4941. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4942. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4943. (\code{x}). The other callee-saved registers are not saved in the
  4944. prelude because they are not used. The prelude subtracts 8 bytes from
  4945. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4946. conclusion, we see that \code{rbx} is restored from the stack with a
  4947. \code{popq} instruction.
  4948. \index{subject}{prelude}\index{subject}{conclusion}
  4949. \begin{figure}[tp]
  4950. \begin{tcolorbox}[colback=white]
  4951. \begin{minipage}{0.45\textwidth}
  4952. Example \LangVar{} program:
  4953. %var_test_14.rkt
  4954. {\if\edition\racketEd
  4955. \begin{lstlisting}
  4956. (let ([x (read)])
  4957. (let ([y (read)])
  4958. (+ (+ x y) 42)))
  4959. \end{lstlisting}
  4960. \fi}
  4961. {\if\edition\pythonEd\pythonColor
  4962. \begin{lstlisting}
  4963. x = input_int()
  4964. y = input_int()
  4965. print((x + y) + 42)
  4966. \end{lstlisting}
  4967. \fi}
  4968. \end{minipage}
  4969. \begin{minipage}{0.45\textwidth}
  4970. Generated x86 assembly:
  4971. {\if\edition\racketEd
  4972. \begin{lstlisting}
  4973. start:
  4974. callq read_int
  4975. movq %rax, %rbx
  4976. callq read_int
  4977. movq %rax, %rcx
  4978. addq %rcx, %rbx
  4979. movq %rbx, %rax
  4980. addq $42, %rax
  4981. jmp conclusion
  4982. .globl main
  4983. main:
  4984. pushq %rbp
  4985. movq %rsp, %rbp
  4986. pushq %rbx
  4987. subq $8, %rsp
  4988. jmp start
  4989. conclusion:
  4990. addq $8, %rsp
  4991. popq %rbx
  4992. popq %rbp
  4993. retq
  4994. \end{lstlisting}
  4995. \fi}
  4996. {\if\edition\pythonEd\pythonColor
  4997. \begin{lstlisting}
  4998. .globl main
  4999. main:
  5000. pushq %rbp
  5001. movq %rsp, %rbp
  5002. pushq %rbx
  5003. subq $8, %rsp
  5004. callq read_int
  5005. movq %rax, %rbx
  5006. callq read_int
  5007. movq %rax, %rcx
  5008. movq %rbx, %rdx
  5009. addq %rcx, %rdx
  5010. movq %rdx, %rcx
  5011. addq $42, %rcx
  5012. movq %rcx, %rdi
  5013. callq print_int
  5014. addq $8, %rsp
  5015. popq %rbx
  5016. popq %rbp
  5017. retq
  5018. \end{lstlisting}
  5019. \fi}
  5020. \end{minipage}
  5021. \end{tcolorbox}
  5022. \caption{An example with function calls.}
  5023. \label{fig:example-calling-conventions}
  5024. \end{figure}
  5025. %\clearpage
  5026. \section{Liveness Analysis}
  5027. \label{sec:liveness-analysis-Lvar}
  5028. \index{subject}{liveness analysis}
  5029. The \code{uncover\_live} \racket{pass}\python{function} performs
  5030. \emph{liveness analysis}; that is, it discovers which variables are
  5031. in use in different regions of a program.
  5032. %
  5033. A variable or register is \emph{live} at a program point if its
  5034. current value is used at some later point in the program. We refer to
  5035. variables, stack locations, and registers collectively as
  5036. \emph{locations}.
  5037. %
  5038. Consider the following code fragment in which there are two writes to
  5039. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5040. time?
  5041. \begin{center}
  5042. \begin{minipage}{0.85\textwidth}
  5043. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5044. movq $5, a
  5045. movq $30, b
  5046. movq a, c
  5047. movq $10, b
  5048. addq b, c
  5049. \end{lstlisting}
  5050. \end{minipage}
  5051. \end{center}
  5052. The answer is no, because \code{a} is live from line 1 to 3 and
  5053. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5054. line 2 is never used because it is overwritten (line 4) before the
  5055. next read (line 5).
  5056. The live locations for each instruction can be computed by traversing
  5057. the instruction sequence back to front (i.e., backward in execution
  5058. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5059. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5060. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5061. locations before instruction $I_k$. \racket{We recommend representing
  5062. these sets with the Racket \code{set} data structure described in
  5063. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5064. with the Python
  5065. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5066. data structure.}
  5067. {\if\edition\racketEd
  5068. \begin{figure}[tp]
  5069. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5070. \small
  5071. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5072. A \emph{set} is an unordered collection of elements without duplicates.
  5073. Here are some of the operations defined on sets.
  5074. \index{subject}{set}
  5075. \begin{description}
  5076. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5077. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5078. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5079. difference of the two sets.
  5080. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5081. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5082. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5083. \end{description}
  5084. \end{tcolorbox}
  5085. %\end{wrapfigure}
  5086. \caption{The \code{set} data structure.}
  5087. \label{fig:set}
  5088. \end{figure}
  5089. \fi}
  5090. % TODO: add a python version of the reference box for sets. -Jeremy
  5091. The locations that are live after an instruction are its
  5092. \emph{live-after}\index{subject}{live-after} set, and the locations
  5093. that are live before an instruction are its
  5094. \emph{live-before}\index{subject}{live-before} set. The live-after
  5095. set of an instruction is always the same as the live-before set of the
  5096. next instruction.
  5097. \begin{equation} \label{eq:live-after-before-next}
  5098. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5099. \end{equation}
  5100. To start things off, there are no live locations after the last
  5101. instruction, so
  5102. \begin{equation}\label{eq:live-last-empty}
  5103. L_{\mathsf{after}}(n) = \emptyset
  5104. \end{equation}
  5105. We then apply the following rule repeatedly, traversing the
  5106. instruction sequence back to front.
  5107. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5108. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5109. \end{equation}
  5110. where $W(k)$ are the locations written to by instruction $I_k$, and
  5111. $R(k)$ are the locations read by instruction $I_k$.
  5112. {\if\edition\racketEd
  5113. %
  5114. There is a special case for \code{jmp} instructions. The locations
  5115. that are live before a \code{jmp} should be the locations in
  5116. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5117. maintaining an alist named \code{label->live} that maps each label to
  5118. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5119. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5120. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5121. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5122. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5123. %
  5124. \fi}
  5125. Let us walk through the previous example, applying these formulas
  5126. starting with the instruction on line 5 of the code fragment. We
  5127. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5128. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5129. $\emptyset$ because it is the last instruction
  5130. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5131. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5132. variables \code{b} and \code{c}
  5133. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5134. \[
  5135. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5136. \]
  5137. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5138. the live-before set from line 5 to be the live-after set for this
  5139. instruction (formula~\eqref{eq:live-after-before-next}).
  5140. \[
  5141. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5142. \]
  5143. This move instruction writes to \code{b} and does not read from any
  5144. variables, so we have the following live-before set
  5145. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5146. \[
  5147. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5148. \]
  5149. The live-before for instruction \code{movq a, c}
  5150. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5151. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5152. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5153. variable that is not live and does not read from a variable.
  5154. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5155. because it writes to variable \code{a}.
  5156. \begin{figure}[tbp]
  5157. \centering
  5158. \begin{tcolorbox}[colback=white]
  5159. \hspace{10pt}
  5160. \begin{minipage}{0.4\textwidth}
  5161. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5162. movq $5, a
  5163. movq $30, b
  5164. movq a, c
  5165. movq $10, b
  5166. addq b, c
  5167. \end{lstlisting}
  5168. \end{minipage}
  5169. \vrule\hspace{10pt}
  5170. \begin{minipage}{0.45\textwidth}
  5171. \begin{align*}
  5172. L_{\mathsf{before}}(1)= \emptyset,
  5173. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5174. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5175. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5176. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5177. L_{\mathsf{after}}(3)= \{\ttm{c}\}\\
  5178. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5179. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5180. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5181. L_{\mathsf{after}}(5)= \emptyset
  5182. \end{align*}
  5183. \end{minipage}
  5184. \end{tcolorbox}
  5185. \caption{Example output of liveness analysis on a short example.}
  5186. \label{fig:liveness-example-0}
  5187. \end{figure}
  5188. \begin{exercise}\normalfont\normalsize
  5189. Perform liveness analysis by hand on the running example in
  5190. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5191. sets for each instruction. Compare your answers to the solution
  5192. shown in figure~\ref{fig:live-eg}.
  5193. \end{exercise}
  5194. \begin{figure}[tp]
  5195. \hspace{20pt}
  5196. \begin{minipage}{0.55\textwidth}
  5197. \begin{tcolorbox}[colback=white]
  5198. {\if\edition\racketEd
  5199. \begin{lstlisting}
  5200. |$\{\ttm{rsp}\}$|
  5201. movq $1, v
  5202. |$\{\ttm{v},\ttm{rsp}\}$|
  5203. movq $42, w
  5204. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5205. movq v, x
  5206. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5207. addq $7, x
  5208. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5209. movq x, y
  5210. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5211. movq x, z
  5212. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5213. addq w, z
  5214. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5215. movq y, t
  5216. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5217. negq t
  5218. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5219. movq z, %rax
  5220. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5221. addq t, %rax
  5222. |$\{\ttm{rax},\ttm{rsp}\}$|
  5223. jmp conclusion
  5224. \end{lstlisting}
  5225. \fi}
  5226. {\if\edition\pythonEd\pythonColor
  5227. \begin{lstlisting}
  5228. movq $1, v
  5229. |$\{\ttm{v}\}$|
  5230. movq $42, w
  5231. |$\{\ttm{w}, \ttm{v}\}$|
  5232. movq v, x
  5233. |$\{\ttm{w}, \ttm{x}\}$|
  5234. addq $7, x
  5235. |$\{\ttm{w}, \ttm{x}\}$|
  5236. movq x, y
  5237. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5238. movq x, z
  5239. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5240. addq w, z
  5241. |$\{\ttm{y}, \ttm{z}\}$|
  5242. movq y, tmp_0
  5243. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5244. negq tmp_0
  5245. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5246. movq z, tmp_1
  5247. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5248. addq tmp_0, tmp_1
  5249. |$\{\ttm{tmp\_1}\}$|
  5250. movq tmp_1, %rdi
  5251. |$\{\ttm{rdi}\}$|
  5252. callq print_int
  5253. |$\{\}$|
  5254. \end{lstlisting}
  5255. \fi}
  5256. \end{tcolorbox}
  5257. \end{minipage}
  5258. \caption{The running example annotated with live-after sets.}
  5259. \label{fig:live-eg}
  5260. \end{figure}
  5261. \begin{exercise}\normalfont\normalsize
  5262. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5263. %
  5264. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5265. field of the \code{Block} structure.}
  5266. %
  5267. \python{Return a dictionary that maps each instruction to its
  5268. live-after set.}
  5269. %
  5270. \racket{We recommend creating an auxiliary function that takes a list
  5271. of instructions and an initial live-after set (typically empty) and
  5272. returns the list of live-after sets.}
  5273. %
  5274. We recommend creating auxiliary functions to (1) compute the set
  5275. of locations that appear in an \Arg{}, (2) compute the locations read
  5276. by an instruction (the $R$ function), and (3) the locations written by
  5277. an instruction (the $W$ function). The \code{callq} instruction should
  5278. include all the caller-saved registers in its write set $W$ because
  5279. the calling convention says that those registers may be written to
  5280. during the function call. Likewise, the \code{callq} instruction
  5281. should include the appropriate argument-passing registers in its
  5282. read set $R$, depending on the arity of the function being
  5283. called. (This is why the abstract syntax for \code{callq} includes the
  5284. arity.)
  5285. \end{exercise}
  5286. %\clearpage
  5287. \section{Build the Interference Graph}
  5288. \label{sec:build-interference}
  5289. {\if\edition\racketEd
  5290. \begin{figure}[tp]
  5291. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5292. \small
  5293. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5294. A \emph{graph} is a collection of vertices and edges where each
  5295. edge connects two vertices. A graph is \emph{directed} if each
  5296. edge points from a source to a target. Otherwise the graph is
  5297. \emph{undirected}.
  5298. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5299. \begin{description}
  5300. %% We currently don't use directed graphs. We instead use
  5301. %% directed multi-graphs. -Jeremy
  5302. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5303. directed graph from a list of edges. Each edge is a list
  5304. containing the source and target vertex.
  5305. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5306. undirected graph from a list of edges. Each edge is represented by
  5307. a list containing two vertices.
  5308. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5309. inserts a vertex into the graph.
  5310. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5311. inserts an edge between the two vertices.
  5312. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5313. returns a sequence of vertices adjacent to the vertex.
  5314. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5315. returns a sequence of all vertices in the graph.
  5316. \end{description}
  5317. \end{tcolorbox}
  5318. %\end{wrapfigure}
  5319. \caption{The Racket \code{graph} package.}
  5320. \label{fig:graph}
  5321. \end{figure}
  5322. \fi}
  5323. On the basis of the liveness analysis, we know where each location is
  5324. live. However, during register allocation, we need to answer
  5325. questions of the specific form: are locations $u$ and $v$ live at the
  5326. same time? (If so, they cannot be assigned to the same register.) To
  5327. make this question more efficient to answer, we create an explicit
  5328. data structure, an \emph{interference
  5329. graph}\index{subject}{interference graph}. An interference graph is
  5330. an undirected graph that has a node for every variable and register
  5331. and has an edge between two nodes if they are
  5332. live at the same time, that is, if they interfere with each other.
  5333. %
  5334. \racket{We recommend using the Racket \code{graph} package
  5335. (figure~\ref{fig:graph}) to represent the interference graph.}
  5336. %
  5337. \python{We provide implementations of directed and undirected graph
  5338. data structures in the file \code{graph.py} of the support code.}
  5339. A straightforward way to compute the interference graph is to look at
  5340. the set of live locations between each instruction and add an edge to
  5341. the graph for every pair of variables in the same set. This approach
  5342. is less than ideal for two reasons. First, it can be expensive because
  5343. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5344. locations. Second, in the special case in which two locations hold the
  5345. same value (because one was assigned to the other), they can be live
  5346. at the same time without interfering with each other.
  5347. A better way to compute the interference graph is to focus on
  5348. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5349. must not overwrite something in a live location. So for each
  5350. instruction, we create an edge between the locations being written to
  5351. and the live locations. (However, a location never interferes with
  5352. itself.) For the \key{callq} instruction, we consider all the
  5353. caller-saved registers to have been written to, so an edge is added
  5354. between every live variable and every caller-saved register. Also, for
  5355. \key{movq} there is the special case of two variables holding the same
  5356. value. If a live variable $v$ is the same as the source of the
  5357. \key{movq}, then there is no need to add an edge between $v$ and the
  5358. destination, because they both hold the same value.
  5359. %
  5360. Hence we have the following two rules:
  5361. \begin{enumerate}
  5362. \item If instruction $I_k$ is a move instruction of the form
  5363. \key{movq} $s$\key{,} $d$, then for every $v \in
  5364. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5365. $(d,v)$.
  5366. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5367. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5368. $(d,v)$.
  5369. \end{enumerate}
  5370. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5371. these rules to each instruction. We highlight a few of the
  5372. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5373. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5374. so \code{v} interferes with \code{rsp}.}
  5375. %
  5376. \python{The first instruction is \lstinline{movq $1, v}, and the
  5377. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5378. no interference because $\ttm{v}$ is the destination of the move.}
  5379. %
  5380. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5381. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5382. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5383. %
  5384. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5385. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5386. $\ttm{x}$ interferes with \ttm{w}.}
  5387. %
  5388. \racket{The next instruction is \lstinline{movq x, y}, and the
  5389. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5390. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5391. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5392. \ttm{x} and \ttm{y} hold the same value.}
  5393. %
  5394. \python{The next instruction is \lstinline{movq x, y}, and the
  5395. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5396. applies, so \ttm{y} interferes with \ttm{w} but not
  5397. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5398. \ttm{x} and \ttm{y} hold the same value.}
  5399. %
  5400. Figure~\ref{fig:interference-results} lists the interference results
  5401. for all the instructions, and the resulting interference graph is
  5402. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5403. the interference graph in figure~\ref{fig:interfere} because there
  5404. were no interference edges involving registers and we did not wish to
  5405. clutter the graph, but in general one needs to include all the
  5406. registers in the interference graph.
  5407. \begin{figure}[tbp]
  5408. \begin{tcolorbox}[colback=white]
  5409. \begin{quote}
  5410. {\if\edition\racketEd
  5411. \begin{tabular}{ll}
  5412. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5413. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5414. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5415. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5416. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5417. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5418. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5419. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5420. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5421. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5422. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5423. \lstinline!jmp conclusion!& no interference.
  5424. \end{tabular}
  5425. \fi}
  5426. {\if\edition\pythonEd\pythonColor
  5427. \begin{tabular}{ll}
  5428. \lstinline!movq $1, v!& no interference\\
  5429. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5430. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5431. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5432. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5433. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5434. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5435. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5436. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5437. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5438. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5439. \lstinline!movq tmp_1, %rdi! & no interference \\
  5440. \lstinline!callq print_int!& no interference.
  5441. \end{tabular}
  5442. \fi}
  5443. \end{quote}
  5444. \end{tcolorbox}
  5445. \caption{Interference results for the running example.}
  5446. \label{fig:interference-results}
  5447. \end{figure}
  5448. \begin{figure}[tbp]
  5449. \begin{tcolorbox}[colback=white]
  5450. \large
  5451. {\if\edition\racketEd
  5452. \[
  5453. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5454. \node (rax) at (0,0) {$\ttm{rax}$};
  5455. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5456. \node (t1) at (0,2) {$\ttm{t}$};
  5457. \node (z) at (3,2) {$\ttm{z}$};
  5458. \node (x) at (6,2) {$\ttm{x}$};
  5459. \node (y) at (3,0) {$\ttm{y}$};
  5460. \node (w) at (6,0) {$\ttm{w}$};
  5461. \node (v) at (9,0) {$\ttm{v}$};
  5462. \draw (t1) to (rax);
  5463. \draw (t1) to (z);
  5464. \draw (z) to (y);
  5465. \draw (z) to (w);
  5466. \draw (x) to (w);
  5467. \draw (y) to (w);
  5468. \draw (v) to (w);
  5469. \draw (v) to (rsp);
  5470. \draw (w) to (rsp);
  5471. \draw (x) to (rsp);
  5472. \draw (y) to (rsp);
  5473. \path[-.,bend left=15] (z) edge node {} (rsp);
  5474. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5475. \draw (rax) to (rsp);
  5476. \end{tikzpicture}
  5477. \]
  5478. \fi}
  5479. {\if\edition\pythonEd\pythonColor
  5480. \[
  5481. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5482. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5483. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5484. \node (z) at (3,2) {$\ttm{z}$};
  5485. \node (x) at (6,2) {$\ttm{x}$};
  5486. \node (y) at (3,0) {$\ttm{y}$};
  5487. \node (w) at (6,0) {$\ttm{w}$};
  5488. \node (v) at (9,0) {$\ttm{v}$};
  5489. \draw (t0) to (t1);
  5490. \draw (t0) to (z);
  5491. \draw (z) to (y);
  5492. \draw (z) to (w);
  5493. \draw (x) to (w);
  5494. \draw (y) to (w);
  5495. \draw (v) to (w);
  5496. \end{tikzpicture}
  5497. \]
  5498. \fi}
  5499. \end{tcolorbox}
  5500. \caption{The interference graph of the example program.}
  5501. \label{fig:interfere}
  5502. \end{figure}
  5503. \begin{exercise}\normalfont\normalsize
  5504. \racket{Implement the compiler pass named \code{build\_interference} according
  5505. to the algorithm suggested here. We recommend using the Racket
  5506. \code{graph} package to create and inspect the interference graph.
  5507. The output graph of this pass should be stored in the $\itm{info}$ field of
  5508. the program, under the key \code{conflicts}.}
  5509. %
  5510. \python{Implement a function named \code{build\_interference}
  5511. according to the algorithm suggested above that
  5512. returns the interference graph.}
  5513. \end{exercise}
  5514. \section{Graph Coloring via Sudoku}
  5515. \label{sec:graph-coloring}
  5516. \index{subject}{graph coloring}
  5517. \index{subject}{sudoku}
  5518. \index{subject}{color}
  5519. We come to the main event discussed in this chapter, mapping variables
  5520. to registers and stack locations. Variables that interfere with each
  5521. other must be mapped to different locations. In terms of the
  5522. interference graph, this means that adjacent vertices must be mapped
  5523. to different locations. If we think of locations as colors, the
  5524. register allocation problem becomes the graph coloring
  5525. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5526. The reader may be more familiar with the graph coloring problem than he
  5527. or she realizes; the popular game of sudoku is an instance of the
  5528. graph coloring problem. The following describes how to build a graph
  5529. out of an initial sudoku board.
  5530. \begin{itemize}
  5531. \item There is one vertex in the graph for each sudoku square.
  5532. \item There is an edge between two vertices if the corresponding squares
  5533. are in the same row, in the same column, or in the same $3\times 3$ region.
  5534. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5535. \item On the basis of the initial assignment of numbers to squares on the
  5536. sudoku board, assign the corresponding colors to the corresponding
  5537. vertices in the graph.
  5538. \end{itemize}
  5539. If you can color the remaining vertices in the graph with the nine
  5540. colors, then you have also solved the corresponding game of sudoku.
  5541. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5542. the corresponding graph with colored vertices. Here we use a
  5543. monochrome representation of colors, mapping the sudoku number 1 to
  5544. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5545. of the vertices (the colored ones) because showing edges for all the
  5546. vertices would make the graph unreadable.
  5547. \begin{figure}[tbp]
  5548. \begin{tcolorbox}[colback=white]
  5549. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5550. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5551. \end{tcolorbox}
  5552. \caption{A sudoku game board and the corresponding colored graph.}
  5553. \label{fig:sudoku-graph}
  5554. \end{figure}
  5555. Some techniques for playing sudoku correspond to heuristics used in
  5556. graph coloring algorithms. For example, one of the basic techniques
  5557. for sudoku is called Pencil Marks. The idea is to use a process of
  5558. elimination to determine what numbers are no longer available for a
  5559. square and to write those numbers in the square (writing very
  5560. small). For example, if the number $1$ is assigned to a square, then
  5561. write the pencil mark $1$ in all the squares in the same row, column,
  5562. and region to indicate that $1$ is no longer an option for those other
  5563. squares.
  5564. %
  5565. The Pencil Marks technique corresponds to the notion of
  5566. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5567. saturation of a vertex, in sudoku terms, is the set of numbers that
  5568. are no longer available. In graph terminology, we have the following
  5569. definition:
  5570. \begin{equation*}
  5571. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5572. \text{ and } \mathrm{color}(v) = c \}
  5573. \end{equation*}
  5574. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5575. edge with $u$.
  5576. The Pencil Marks technique leads to a simple strategy for filling in
  5577. numbers: if there is a square with only one possible number left, then
  5578. choose that number! But what if there are no squares with only one
  5579. possibility left? One brute-force approach is to try them all: choose
  5580. the first one, and if that ultimately leads to a solution, great. If
  5581. not, backtrack and choose the next possibility. One good thing about
  5582. Pencil Marks is that it reduces the degree of branching in the search
  5583. tree. Nevertheless, backtracking can be terribly time consuming. One
  5584. way to reduce the amount of backtracking is to use the
  5585. most-constrained-first heuristic (aka minimum remaining
  5586. values)~\citep{Russell2003}. That is, in choosing a square, always
  5587. choose one with the fewest possibilities left (the vertex with the
  5588. highest saturation). The idea is that choosing highly constrained
  5589. squares earlier rather than later is better, because later on there may
  5590. not be any possibilities left in the highly saturated squares.
  5591. However, register allocation is easier than sudoku, because the
  5592. register allocator can fall back to assigning variables to stack
  5593. locations when the registers run out. Thus, it makes sense to replace
  5594. backtracking with greedy search: make the best choice at the time and
  5595. keep going. We still wish to minimize the number of colors needed, so
  5596. we use the most-constrained-first heuristic in the greedy search.
  5597. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5598. algorithm for register allocation based on saturation and the
  5599. most-constrained-first heuristic. It is roughly equivalent to the
  5600. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5601. sudoku, the algorithm represents colors with integers. The integers
  5602. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5603. register allocation. In particular, we recommend the following
  5604. correspondence, with $k=11$.
  5605. \begin{lstlisting}
  5606. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5607. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5608. \end{lstlisting}
  5609. The integers $k$ and larger correspond to stack locations. The
  5610. registers that are not used for register allocation, such as
  5611. \code{rax}, are assigned to negative integers. In particular, we
  5612. recommend the following correspondence.
  5613. \begin{lstlisting}
  5614. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5615. \end{lstlisting}
  5616. \begin{figure}[btp]
  5617. \begin{tcolorbox}[colback=white]
  5618. \centering
  5619. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5620. Algorithm: DSATUR
  5621. Input: A graph |$G$|
  5622. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5623. |$W \gets \mathrm{vertices}(G)$|
  5624. while |$W \neq \emptyset$| do
  5625. pick a vertex |$u$| from |$W$| with the highest saturation,
  5626. breaking ties randomly
  5627. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5628. |$\mathrm{color}[u] \gets c$|
  5629. |$W \gets W - \{u\}$|
  5630. \end{lstlisting}
  5631. \end{tcolorbox}
  5632. \caption{The saturation-based greedy graph coloring algorithm.}
  5633. \label{fig:satur-algo}
  5634. \end{figure}
  5635. {\if\edition\racketEd
  5636. With the DSATUR algorithm in hand, let us return to the running
  5637. example and consider how to color the interference graph shown in
  5638. figure~\ref{fig:interfere}.
  5639. %
  5640. We start by assigning each register node to its own color. For
  5641. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5642. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5643. (To reduce clutter in the interference graph, we elide nodes
  5644. that do not have interference edges, such as \code{rcx}.)
  5645. The variables are not yet colored, so they are annotated with a dash. We
  5646. then update the saturation for vertices that are adjacent to a
  5647. register, obtaining the following annotated graph. For example, the
  5648. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5649. \code{rax} and \code{rsp}.
  5650. \[
  5651. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5652. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5653. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5654. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5655. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5656. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5657. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5658. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5659. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5660. \draw (t1) to (rax);
  5661. \draw (t1) to (z);
  5662. \draw (z) to (y);
  5663. \draw (z) to (w);
  5664. \draw (x) to (w);
  5665. \draw (y) to (w);
  5666. \draw (v) to (w);
  5667. \draw (v) to (rsp);
  5668. \draw (w) to (rsp);
  5669. \draw (x) to (rsp);
  5670. \draw (y) to (rsp);
  5671. \path[-.,bend left=15] (z) edge node {} (rsp);
  5672. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5673. \draw (rax) to (rsp);
  5674. \end{tikzpicture}
  5675. \]
  5676. The algorithm says to select a maximally saturated vertex. So, we pick
  5677. $\ttm{t}$ and color it with the first available integer, which is
  5678. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5679. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5680. \[
  5681. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5682. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5683. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5684. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5685. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5686. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5687. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5688. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5689. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5690. \draw (t1) to (rax);
  5691. \draw (t1) to (z);
  5692. \draw (z) to (y);
  5693. \draw (z) to (w);
  5694. \draw (x) to (w);
  5695. \draw (y) to (w);
  5696. \draw (v) to (w);
  5697. \draw (v) to (rsp);
  5698. \draw (w) to (rsp);
  5699. \draw (x) to (rsp);
  5700. \draw (y) to (rsp);
  5701. \path[-.,bend left=15] (z) edge node {} (rsp);
  5702. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5703. \draw (rax) to (rsp);
  5704. \end{tikzpicture}
  5705. \]
  5706. We repeat the process, selecting a maximally saturated vertex,
  5707. choosing \code{z}, and coloring it with the first available number, which
  5708. is $1$. We add $1$ to the saturation for the neighboring vertices
  5709. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5710. \[
  5711. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5712. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5713. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5714. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5715. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5716. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5717. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5718. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5719. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5720. \draw (t1) to (rax);
  5721. \draw (t1) to (z);
  5722. \draw (z) to (y);
  5723. \draw (z) to (w);
  5724. \draw (x) to (w);
  5725. \draw (y) to (w);
  5726. \draw (v) to (w);
  5727. \draw (v) to (rsp);
  5728. \draw (w) to (rsp);
  5729. \draw (x) to (rsp);
  5730. \draw (y) to (rsp);
  5731. \path[-.,bend left=15] (z) edge node {} (rsp);
  5732. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5733. \draw (rax) to (rsp);
  5734. \end{tikzpicture}
  5735. \]
  5736. The most saturated vertices are now \code{w} and \code{y}. We color
  5737. \code{w} with the first available color, which is $0$.
  5738. \[
  5739. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5740. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5741. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5742. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5743. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5744. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5745. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5746. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5747. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5748. \draw (t1) to (rax);
  5749. \draw (t1) to (z);
  5750. \draw (z) to (y);
  5751. \draw (z) to (w);
  5752. \draw (x) to (w);
  5753. \draw (y) to (w);
  5754. \draw (v) to (w);
  5755. \draw (v) to (rsp);
  5756. \draw (w) to (rsp);
  5757. \draw (x) to (rsp);
  5758. \draw (y) to (rsp);
  5759. \path[-.,bend left=15] (z) edge node {} (rsp);
  5760. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5761. \draw (rax) to (rsp);
  5762. \end{tikzpicture}
  5763. \]
  5764. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5765. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5766. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5767. and \code{z}, whose colors are $0$ and $1$ respectively.
  5768. \[
  5769. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5770. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5771. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5772. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5773. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5774. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5775. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5776. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5777. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5778. \draw (t1) to (rax);
  5779. \draw (t1) to (z);
  5780. \draw (z) to (y);
  5781. \draw (z) to (w);
  5782. \draw (x) to (w);
  5783. \draw (y) to (w);
  5784. \draw (v) to (w);
  5785. \draw (v) to (rsp);
  5786. \draw (w) to (rsp);
  5787. \draw (x) to (rsp);
  5788. \draw (y) to (rsp);
  5789. \path[-.,bend left=15] (z) edge node {} (rsp);
  5790. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5791. \draw (rax) to (rsp);
  5792. \end{tikzpicture}
  5793. \]
  5794. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5795. \[
  5796. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5797. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5798. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5799. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5800. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5801. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5802. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5803. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5804. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5805. \draw (t1) to (rax);
  5806. \draw (t1) to (z);
  5807. \draw (z) to (y);
  5808. \draw (z) to (w);
  5809. \draw (x) to (w);
  5810. \draw (y) to (w);
  5811. \draw (v) to (w);
  5812. \draw (v) to (rsp);
  5813. \draw (w) to (rsp);
  5814. \draw (x) to (rsp);
  5815. \draw (y) to (rsp);
  5816. \path[-.,bend left=15] (z) edge node {} (rsp);
  5817. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5818. \draw (rax) to (rsp);
  5819. \end{tikzpicture}
  5820. \]
  5821. In the last step of the algorithm, we color \code{x} with $1$.
  5822. \[
  5823. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5824. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5825. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5826. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5827. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5828. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5829. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5830. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5831. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5832. \draw (t1) to (rax);
  5833. \draw (t1) to (z);
  5834. \draw (z) to (y);
  5835. \draw (z) to (w);
  5836. \draw (x) to (w);
  5837. \draw (y) to (w);
  5838. \draw (v) to (w);
  5839. \draw (v) to (rsp);
  5840. \draw (w) to (rsp);
  5841. \draw (x) to (rsp);
  5842. \draw (y) to (rsp);
  5843. \path[-.,bend left=15] (z) edge node {} (rsp);
  5844. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5845. \draw (rax) to (rsp);
  5846. \end{tikzpicture}
  5847. \]
  5848. So, we obtain the following coloring:
  5849. \[
  5850. \{
  5851. \ttm{rax} \mapsto -1,
  5852. \ttm{rsp} \mapsto -2,
  5853. \ttm{t} \mapsto 0,
  5854. \ttm{z} \mapsto 1,
  5855. \ttm{x} \mapsto 1,
  5856. \ttm{y} \mapsto 2,
  5857. \ttm{w} \mapsto 0,
  5858. \ttm{v} \mapsto 1
  5859. \}
  5860. \]
  5861. \fi}
  5862. %
  5863. {\if\edition\pythonEd\pythonColor
  5864. %
  5865. With the DSATUR algorithm in hand, let us return to the running
  5866. example and consider how to color the interference graph shown in
  5867. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5868. to indicate that it has not yet been assigned a color. Each register
  5869. node (not shown) should be assigned the number that the register
  5870. corresponds to, for example, color \code{rcx} with the number \code{0}
  5871. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5872. each node; all of them start as the empty set.
  5873. %
  5874. \[
  5875. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5876. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5877. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5878. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5879. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5880. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5881. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5882. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5883. \draw (t0) to (t1);
  5884. \draw (t0) to (z);
  5885. \draw (z) to (y);
  5886. \draw (z) to (w);
  5887. \draw (x) to (w);
  5888. \draw (y) to (w);
  5889. \draw (v) to (w);
  5890. \end{tikzpicture}
  5891. \]
  5892. The algorithm says to select a maximally saturated vertex, but they
  5893. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5894. and then we color it with the first available integer, which is $0$. We mark
  5895. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5896. they interfere with $\ttm{tmp\_0}$.
  5897. \[
  5898. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5899. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5900. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5901. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5902. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5903. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5904. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5905. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5906. \draw (t0) to (t1);
  5907. \draw (t0) to (z);
  5908. \draw (z) to (y);
  5909. \draw (z) to (w);
  5910. \draw (x) to (w);
  5911. \draw (y) to (w);
  5912. \draw (v) to (w);
  5913. \end{tikzpicture}
  5914. \]
  5915. We repeat the process. The most saturated vertices are \code{z} and
  5916. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5917. available number, which is $1$. We add $1$ to the saturation for the
  5918. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5919. \[
  5920. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5921. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5922. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5923. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5924. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5925. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5926. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5927. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5928. \draw (t0) to (t1);
  5929. \draw (t0) to (z);
  5930. \draw (z) to (y);
  5931. \draw (z) to (w);
  5932. \draw (x) to (w);
  5933. \draw (y) to (w);
  5934. \draw (v) to (w);
  5935. \end{tikzpicture}
  5936. \]
  5937. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5938. \code{y}. We color \code{w} with the first available color, which
  5939. is $0$.
  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\}$};
  5945. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5946. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5947. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  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. Now \code{y} is the most saturated, so we color it with $2$.
  5959. \[
  5960. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5961. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5962. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5963. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5964. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5965. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5966. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5967. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5968. \draw (t0) to (t1);
  5969. \draw (t0) to (z);
  5970. \draw (z) to (y);
  5971. \draw (z) to (w);
  5972. \draw (x) to (w);
  5973. \draw (y) to (w);
  5974. \draw (v) to (w);
  5975. \end{tikzpicture}
  5976. \]
  5977. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5978. We choose to color \code{v} 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}: -, \{0\}$};
  5983. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5984. \node (x) at (6,2) {$\ttm{x}: -, \{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. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5998. \[
  5999. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6000. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6001. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6002. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  6003. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  6004. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  6005. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  6006. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  6007. \draw (t0) to (t1);
  6008. \draw (t0) to (z);
  6009. \draw (z) to (y);
  6010. \draw (z) to (w);
  6011. \draw (x) to (w);
  6012. \draw (y) to (w);
  6013. \draw (v) to (w);
  6014. \end{tikzpicture}
  6015. \]
  6016. So, we obtain the following coloring:
  6017. \[
  6018. \{ \ttm{tmp\_0} \mapsto 0,
  6019. \ttm{tmp\_1} \mapsto 1,
  6020. \ttm{z} \mapsto 1,
  6021. \ttm{x} \mapsto 1,
  6022. \ttm{y} \mapsto 2,
  6023. \ttm{w} \mapsto 0,
  6024. \ttm{v} \mapsto 1 \}
  6025. \]
  6026. \fi}
  6027. We recommend creating an auxiliary function named \code{color\_graph}
  6028. that takes an interference graph and a list of all the variables in
  6029. the program. This function should return a mapping of variables to
  6030. their colors (represented as natural numbers). By creating this helper
  6031. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  6032. when we add support for functions.
  6033. To prioritize the processing of highly saturated nodes inside the
  6034. \code{color\_graph} function, we recommend using the priority queue
  6035. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  6036. addition, you will need to maintain a mapping from variables to their
  6037. handles in the priority queue so that you can notify the priority
  6038. queue when their saturation changes.}
  6039. {\if\edition\racketEd
  6040. \begin{figure}[tp]
  6041. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6042. \small
  6043. \begin{tcolorbox}[title=Priority Queue]
  6044. A \emph{priority queue}\index{subject}{priority queue}
  6045. is a collection of items in which the
  6046. removal of items is governed by priority. In a \emph{min} queue,
  6047. lower priority items are removed first. An implementation is in
  6048. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6049. \begin{description}
  6050. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6051. priority queue that uses the $\itm{cmp}$ predicate to determine
  6052. whether its first argument has lower or equal priority to its
  6053. second argument.
  6054. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6055. items in the queue.
  6056. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6057. the item into the queue and returns a handle for the item in the
  6058. queue.
  6059. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6060. the lowest priority.
  6061. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6062. notifies the queue that the priority has decreased for the item
  6063. associated with the given handle.
  6064. \end{description}
  6065. \end{tcolorbox}
  6066. %\end{wrapfigure}
  6067. \caption{The priority queue data structure.}
  6068. \label{fig:priority-queue}
  6069. \end{figure}
  6070. \fi}
  6071. With the coloring complete, we finalize the assignment of variables to
  6072. registers and stack locations. We map the first $k$ colors to the $k$
  6073. registers and the rest of the colors to stack locations. Suppose for
  6074. the moment that we have just one register to use for register
  6075. allocation, \key{rcx}. Then we have the following assignment.
  6076. \[
  6077. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6078. \]
  6079. Composing this mapping with the coloring, we arrive at the following
  6080. assignment of variables to locations.
  6081. {\if\edition\racketEd
  6082. \begin{gather*}
  6083. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6084. \ttm{w} \mapsto \key{\%rcx}, \,
  6085. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6086. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6087. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6088. \ttm{t} \mapsto \key{\%rcx} \}
  6089. \end{gather*}
  6090. \fi}
  6091. {\if\edition\pythonEd\pythonColor
  6092. \begin{gather*}
  6093. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6094. \ttm{w} \mapsto \key{\%rcx}, \,
  6095. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6096. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6097. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6098. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6099. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6100. \end{gather*}
  6101. \fi}
  6102. Adapt the code from the \code{assign\_homes} pass
  6103. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6104. assigned location. Applying this assignment to our running
  6105. example shown next, on the left, yields the program on the right.
  6106. \begin{center}
  6107. {\if\edition\racketEd
  6108. \begin{minipage}{0.35\textwidth}
  6109. \begin{lstlisting}
  6110. movq $1, v
  6111. movq $42, w
  6112. movq v, x
  6113. addq $7, x
  6114. movq x, y
  6115. movq x, z
  6116. addq w, z
  6117. movq y, t
  6118. negq t
  6119. movq z, %rax
  6120. addq t, %rax
  6121. jmp conclusion
  6122. \end{lstlisting}
  6123. \end{minipage}
  6124. $\Rightarrow\qquad$
  6125. \begin{minipage}{0.45\textwidth}
  6126. \begin{lstlisting}
  6127. movq $1, -8(%rbp)
  6128. movq $42, %rcx
  6129. movq -8(%rbp), -8(%rbp)
  6130. addq $7, -8(%rbp)
  6131. movq -8(%rbp), -16(%rbp)
  6132. movq -8(%rbp), -8(%rbp)
  6133. addq %rcx, -8(%rbp)
  6134. movq -16(%rbp), %rcx
  6135. negq %rcx
  6136. movq -8(%rbp), %rax
  6137. addq %rcx, %rax
  6138. jmp conclusion
  6139. \end{lstlisting}
  6140. \end{minipage}
  6141. \fi}
  6142. {\if\edition\pythonEd\pythonColor
  6143. \begin{minipage}{0.35\textwidth}
  6144. \begin{lstlisting}
  6145. movq $1, v
  6146. movq $42, w
  6147. movq v, x
  6148. addq $7, x
  6149. movq x, y
  6150. movq x, z
  6151. addq w, z
  6152. movq y, tmp_0
  6153. negq tmp_0
  6154. movq z, tmp_1
  6155. addq tmp_0, tmp_1
  6156. movq tmp_1, %rdi
  6157. callq print_int
  6158. \end{lstlisting}
  6159. \end{minipage}
  6160. $\Rightarrow\qquad$
  6161. \begin{minipage}{0.45\textwidth}
  6162. \begin{lstlisting}
  6163. movq $1, -8(%rbp)
  6164. movq $42, %rcx
  6165. movq -8(%rbp), -8(%rbp)
  6166. addq $7, -8(%rbp)
  6167. movq -8(%rbp), -16(%rbp)
  6168. movq -8(%rbp), -8(%rbp)
  6169. addq %rcx, -8(%rbp)
  6170. movq -16(%rbp), %rcx
  6171. negq %rcx
  6172. movq -8(%rbp), -8(%rbp)
  6173. addq %rcx, -8(%rbp)
  6174. movq -8(%rbp), %rdi
  6175. callq print_int
  6176. \end{lstlisting}
  6177. \end{minipage}
  6178. \fi}
  6179. \end{center}
  6180. \begin{exercise}\normalfont\normalsize
  6181. Implement the \code{allocate\_registers} \racket{pass}\python{function}.
  6182. Create five programs that exercise all aspects of the register
  6183. allocation algorithm, including spilling variables to the stack.
  6184. %
  6185. {\if\edition\racketEd
  6186. Replace \code{assign\_homes} in the list of \code{passes} in the
  6187. \code{run-tests.rkt} script with the three new passes:
  6188. \code{uncover\_live}, \code{build\_interference}, and
  6189. \code{allocate\_registers}.
  6190. Temporarily remove the call to \code{compiler-tests}.
  6191. Run the script to test the register allocator.
  6192. \fi}
  6193. %
  6194. {\if\edition\pythonEd\pythonColor
  6195. Update the \code{assign\_homes} pass to make use of
  6196. the functions you have created to perform register allocation:
  6197. \code{uncover\_live}, \code{build\_interference}, and
  6198. \code{allocate\_registers}.
  6199. Run the \code{run-tests.py} script to check whether the
  6200. output programs produce the same result as the input programs.
  6201. Inspect the generated x86 programs to make sure that some variables
  6202. are assigned to registers.
  6203. \fi}
  6204. \end{exercise}
  6205. \section{Patch Instructions}
  6206. \label{sec:patch-instructions}
  6207. The remaining step in the compilation to x86 is to ensure that the
  6208. instructions have at most one argument that is a memory access.
  6209. %
  6210. In the running example, the instruction \code{movq -8(\%rbp),
  6211. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6212. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6213. then move \code{rax} into \code{-16(\%rbp)}.
  6214. %
  6215. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6216. problematic, but they can simply be deleted. In general, we recommend
  6217. deleting all the trivial moves whose source and destination are the
  6218. same location.
  6219. %
  6220. The following is the output of \code{patch\_instructions} on the
  6221. running example.
  6222. \begin{center}
  6223. {\if\edition\racketEd
  6224. \begin{minipage}{0.35\textwidth}
  6225. \begin{lstlisting}
  6226. movq $1, -8(%rbp)
  6227. movq $42, %rcx
  6228. movq -8(%rbp), -8(%rbp)
  6229. addq $7, -8(%rbp)
  6230. movq -8(%rbp), -16(%rbp)
  6231. movq -8(%rbp), -8(%rbp)
  6232. addq %rcx, -8(%rbp)
  6233. movq -16(%rbp), %rcx
  6234. negq %rcx
  6235. movq -8(%rbp), %rax
  6236. addq %rcx, %rax
  6237. jmp conclusion
  6238. \end{lstlisting}
  6239. \end{minipage}
  6240. $\Rightarrow\qquad$
  6241. \begin{minipage}{0.45\textwidth}
  6242. \begin{lstlisting}
  6243. movq $1, -8(%rbp)
  6244. movq $42, %rcx
  6245. addq $7, -8(%rbp)
  6246. movq -8(%rbp), %rax
  6247. movq %rax, -16(%rbp)
  6248. addq %rcx, -8(%rbp)
  6249. movq -16(%rbp), %rcx
  6250. negq %rcx
  6251. movq -8(%rbp), %rax
  6252. addq %rcx, %rax
  6253. jmp conclusion
  6254. \end{lstlisting}
  6255. \end{minipage}
  6256. \fi}
  6257. {\if\edition\pythonEd\pythonColor
  6258. \begin{minipage}{0.35\textwidth}
  6259. \begin{lstlisting}
  6260. movq $1, -8(%rbp)
  6261. movq $42, %rcx
  6262. movq -8(%rbp), -8(%rbp)
  6263. addq $7, -8(%rbp)
  6264. movq -8(%rbp), -16(%rbp)
  6265. movq -8(%rbp), -8(%rbp)
  6266. addq %rcx, -8(%rbp)
  6267. movq -16(%rbp), %rcx
  6268. negq %rcx
  6269. movq -8(%rbp), -8(%rbp)
  6270. addq %rcx, -8(%rbp)
  6271. movq -8(%rbp), %rdi
  6272. callq print_int
  6273. \end{lstlisting}
  6274. \end{minipage}
  6275. $\Rightarrow\qquad$
  6276. \begin{minipage}{0.45\textwidth}
  6277. \begin{lstlisting}
  6278. movq $1, -8(%rbp)
  6279. movq $42, %rcx
  6280. addq $7, -8(%rbp)
  6281. movq -8(%rbp), %rax
  6282. movq %rax, -16(%rbp)
  6283. addq %rcx, -8(%rbp)
  6284. movq -16(%rbp), %rcx
  6285. negq %rcx
  6286. addq %rcx, -8(%rbp)
  6287. movq -8(%rbp), %rdi
  6288. callq print_int
  6289. \end{lstlisting}
  6290. \end{minipage}
  6291. \fi}
  6292. \end{center}
  6293. \begin{exercise}\normalfont\normalsize
  6294. %
  6295. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6296. %
  6297. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6298. %in the \code{run-tests.rkt} script.
  6299. %
  6300. Run the script to test the \code{patch\_instructions} pass.
  6301. \end{exercise}
  6302. \section{Generate Prelude and Conclusion}
  6303. \label{sec:print-x86-reg-alloc}
  6304. \index{subject}{calling conventions}
  6305. \index{subject}{prelude}\index{subject}{conclusion}
  6306. Recall that this pass generates the prelude and conclusion
  6307. instructions to satisfy the x86 calling conventions
  6308. (section~\ref{sec:calling-conventions}). With the addition of the
  6309. register allocator, the callee-saved registers used by the register
  6310. allocator must be saved in the prelude and restored in the conclusion.
  6311. In the \code{allocate\_registers} pass,
  6312. %
  6313. \racket{add an entry to the \itm{info}
  6314. of \code{X86Program} named \code{used\_callee}}
  6315. %
  6316. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6317. %
  6318. that stores the set of callee-saved registers that were assigned to
  6319. variables. The \code{prelude\_and\_conclusion} pass can then access
  6320. this information to decide which callee-saved registers need to be
  6321. saved and restored.
  6322. %
  6323. When calculating the amount to adjust the \code{rsp} in the prelude,
  6324. make sure to take into account the space used for saving the
  6325. callee-saved registers. Also, remember that the frame needs to be a
  6326. multiple of 16 bytes! We recommend using the following equation for
  6327. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6328. of stack locations used by spilled variables\footnote{Sometimes two or
  6329. more spilled variables are assigned to the same stack location, so
  6330. $S$ can be less than the number of spilled variables.} and $C$ be
  6331. the number of callee-saved registers that were
  6332. allocated\index{subject}{allocate} to
  6333. variables. The $\itm{align}$ function rounds a number up to the
  6334. nearest 16 bytes.
  6335. \[
  6336. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6337. \]
  6338. The reason we subtract $8\itm{C}$ in this equation is that the
  6339. prelude uses \code{pushq} to save each of the callee-saved registers,
  6340. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6341. \racket{An overview of all the passes involved in register
  6342. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6343. {\if\edition\racketEd
  6344. \begin{figure}[tbp]
  6345. \begin{tcolorbox}[colback=white]
  6346. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6347. \node (Lvar) at (0,2) {\large \LangVar{}};
  6348. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6349. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6350. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6351. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6352. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6353. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6354. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6355. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6356. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6357. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6358. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6359. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6360. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6361. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6362. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6363. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6364. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6365. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6366. \end{tikzpicture}
  6367. \end{tcolorbox}
  6368. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6369. \label{fig:reg-alloc-passes}
  6370. \end{figure}
  6371. \fi}
  6372. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6373. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6374. use of registers and the stack, we limit the register allocator for
  6375. this example to use just two registers: \code{rcx} (color $0$) and
  6376. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6377. \code{main} function, we push \code{rbx} onto the stack because it is
  6378. a callee-saved register and it was assigned to a variable by the
  6379. register allocator. We subtract \code{8} from the \code{rsp} at the
  6380. end of the prelude to reserve space for the one spilled variable.
  6381. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6382. Moving on to the program proper, we see how the registers were
  6383. allocated.
  6384. %
  6385. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6386. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6387. %
  6388. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6389. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6390. were assigned to \code{rbx}.}
  6391. %
  6392. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6393. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6394. callee-save register \code{rbx} onto the stack. The spilled variables
  6395. must be placed lower on the stack than the saved callee-save
  6396. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6397. \code{-16(\%rbp)}.
  6398. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6399. done in the prelude. We move the stack pointer up by \code{8} bytes
  6400. (the room for spilled variables), then pop the old values of
  6401. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6402. \code{retq} to return control to the operating system.
  6403. \begin{figure}[tbp]
  6404. \begin{minipage}{0.55\textwidth}
  6405. \begin{tcolorbox}[colback=white]
  6406. % var_test_28.rkt
  6407. % (use-minimal-set-of-registers! #t)
  6408. % 0 -> rcx
  6409. % 1 -> rbx
  6410. %
  6411. % t 0 rcx
  6412. % z 1 rbx
  6413. % w 0 rcx
  6414. % y 2 rbp -16
  6415. % v 1 rbx
  6416. % x 1 rbx
  6417. {\if\edition\racketEd
  6418. \begin{lstlisting}
  6419. start:
  6420. movq $1, %rbx
  6421. movq $42, %rcx
  6422. addq $7, %rbx
  6423. movq %rbx, -16(%rbp)
  6424. addq %rcx, %rbx
  6425. movq -16(%rbp), %rcx
  6426. negq %rcx
  6427. movq %rbx, %rax
  6428. addq %rcx, %rax
  6429. jmp conclusion
  6430. .globl main
  6431. main:
  6432. pushq %rbp
  6433. movq %rsp, %rbp
  6434. pushq %rbx
  6435. subq $8, %rsp
  6436. jmp start
  6437. conclusion:
  6438. addq $8, %rsp
  6439. popq %rbx
  6440. popq %rbp
  6441. retq
  6442. \end{lstlisting}
  6443. \fi}
  6444. {\if\edition\pythonEd\pythonColor
  6445. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6446. \begin{lstlisting}
  6447. .globl main
  6448. main:
  6449. pushq %rbp
  6450. movq %rsp, %rbp
  6451. pushq %rbx
  6452. subq $8, %rsp
  6453. movq $1, %rcx
  6454. movq $42, %rbx
  6455. addq $7, %rcx
  6456. movq %rcx, -16(%rbp)
  6457. addq %rbx, -16(%rbp)
  6458. negq %rcx
  6459. movq -16(%rbp), %rbx
  6460. addq %rcx, %rbx
  6461. movq %rbx, %rdi
  6462. callq print_int
  6463. addq $8, %rsp
  6464. popq %rbx
  6465. popq %rbp
  6466. retq
  6467. \end{lstlisting}
  6468. \fi}
  6469. \end{tcolorbox}
  6470. \end{minipage}
  6471. \caption{The x86 output from the running example
  6472. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6473. and \code{rcx}.}
  6474. \label{fig:running-example-x86}
  6475. \end{figure}
  6476. \begin{exercise}\normalfont\normalsize
  6477. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6478. %
  6479. \racket{
  6480. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6481. list of passes and the call to \code{compiler-tests}.}
  6482. %
  6483. Run the script to test the complete compiler for \LangVar{} that
  6484. performs register allocation.
  6485. \end{exercise}
  6486. \section{Challenge: Move Biasing}
  6487. \label{sec:move-biasing}
  6488. \index{subject}{move biasing}
  6489. This section describes an enhancement to the register allocator,
  6490. called move biasing, for students who are looking for an extra
  6491. challenge.
  6492. {\if\edition\racketEd
  6493. To motivate the need for move biasing we return to the running example,
  6494. but this time we use all the general purpose registers. So, we have
  6495. the following mapping of color numbers to registers.
  6496. \[
  6497. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6498. \]
  6499. Using the same assignment of variables to color numbers that was
  6500. produced by the register allocator described in the last section, we
  6501. get the following program.
  6502. \begin{center}
  6503. \begin{minipage}{0.35\textwidth}
  6504. \begin{lstlisting}
  6505. movq $1, v
  6506. movq $42, w
  6507. movq v, x
  6508. addq $7, x
  6509. movq x, y
  6510. movq x, z
  6511. addq w, z
  6512. movq y, t
  6513. negq t
  6514. movq z, %rax
  6515. addq t, %rax
  6516. jmp conclusion
  6517. \end{lstlisting}
  6518. \end{minipage}
  6519. $\Rightarrow\qquad$
  6520. \begin{minipage}{0.45\textwidth}
  6521. \begin{lstlisting}
  6522. movq $1, %rdx
  6523. movq $42, %rcx
  6524. movq %rdx, %rdx
  6525. addq $7, %rdx
  6526. movq %rdx, %rsi
  6527. movq %rdx, %rdx
  6528. addq %rcx, %rdx
  6529. movq %rsi, %rcx
  6530. negq %rcx
  6531. movq %rdx, %rax
  6532. addq %rcx, %rax
  6533. jmp conclusion
  6534. \end{lstlisting}
  6535. \end{minipage}
  6536. \end{center}
  6537. In this output code there are two \key{movq} instructions that
  6538. can be removed because their source and target are the same. However,
  6539. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6540. register, we could instead remove three \key{movq} instructions. We
  6541. can accomplish this by taking into account which variables appear in
  6542. \key{movq} instructions with which other variables.
  6543. \fi}
  6544. {\if\edition\pythonEd\pythonColor
  6545. %
  6546. To motivate the need for move biasing we return to the running example
  6547. and recall that in section~\ref{sec:patch-instructions} we were able to
  6548. remove three trivial move instructions from the running
  6549. example. However, we could remove another trivial move if we were able
  6550. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6551. We say that two variables $p$ and $q$ are \emph{move
  6552. related}\index{subject}{move related} if they participate together in
  6553. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6554. \key{movq} $q$\key{,} $p$.
  6555. %
  6556. Recall that we color variables that are more saturated before coloring
  6557. variables that are less saturated, and in the case of equally
  6558. saturated variables, we choose randomly. Now we break such ties by
  6559. giving preference to variables that have an available color that is
  6560. the same as the color of a move-related variable.
  6561. %
  6562. Furthermore, when the register allocator chooses a color for a
  6563. variable, it should prefer a color that has already been used for a
  6564. move-related variable if one exists (and assuming that they do not
  6565. interfere). This preference should not override the preference for
  6566. registers over stack locations. So, this preference should be used as
  6567. a tie breaker in choosing between two registers or in choosing between
  6568. two stack locations.
  6569. We recommend representing the move relationships in a graph, similarly
  6570. to how we represented interference. The following is the \emph{move
  6571. graph} for our example.
  6572. {\if\edition\racketEd
  6573. \[
  6574. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6575. \node (rax) at (0,0) {$\ttm{rax}$};
  6576. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6577. \node (t) at (0,2) {$\ttm{t}$};
  6578. \node (z) at (3,2) {$\ttm{z}$};
  6579. \node (x) at (6,2) {$\ttm{x}$};
  6580. \node (y) at (3,0) {$\ttm{y}$};
  6581. \node (w) at (6,0) {$\ttm{w}$};
  6582. \node (v) at (9,0) {$\ttm{v}$};
  6583. \draw (v) to (x);
  6584. \draw (x) to (y);
  6585. \draw (x) to (z);
  6586. \draw (y) to (t);
  6587. \end{tikzpicture}
  6588. \]
  6589. \fi}
  6590. %
  6591. {\if\edition\pythonEd\pythonColor
  6592. \[
  6593. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6594. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6595. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6596. \node (z) at (3,2) {$\ttm{z}$};
  6597. \node (x) at (6,2) {$\ttm{x}$};
  6598. \node (y) at (3,0) {$\ttm{y}$};
  6599. \node (w) at (6,0) {$\ttm{w}$};
  6600. \node (v) at (9,0) {$\ttm{v}$};
  6601. \draw (y) to (t0);
  6602. \draw (z) to (x);
  6603. \draw (z) to (t1);
  6604. \draw (x) to (y);
  6605. \draw (x) to (v);
  6606. \end{tikzpicture}
  6607. \]
  6608. \fi}
  6609. {\if\edition\racketEd
  6610. Now we replay the graph coloring, pausing to see the coloring of
  6611. \code{y}. Recall the following configuration. The most saturated vertices
  6612. were \code{w} and \code{y}.
  6613. \[
  6614. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6615. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6616. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6617. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6618. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6619. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6620. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6621. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6622. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6623. \draw (t1) to (rax);
  6624. \draw (t1) to (z);
  6625. \draw (z) to (y);
  6626. \draw (z) to (w);
  6627. \draw (x) to (w);
  6628. \draw (y) to (w);
  6629. \draw (v) to (w);
  6630. \draw (v) to (rsp);
  6631. \draw (w) to (rsp);
  6632. \draw (x) to (rsp);
  6633. \draw (y) to (rsp);
  6634. \path[-.,bend left=15] (z) edge node {} (rsp);
  6635. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6636. \draw (rax) to (rsp);
  6637. \end{tikzpicture}
  6638. \]
  6639. %
  6640. The last time, we chose to color \code{w} with $0$. This time, we see
  6641. that \code{w} is not move-related to any vertex, but \code{y} is
  6642. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6643. the same color as \code{t}.
  6644. \[
  6645. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6646. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6647. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6648. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6649. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6650. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6651. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6652. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6653. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6654. \draw (t1) to (rax);
  6655. \draw (t1) to (z);
  6656. \draw (z) to (y);
  6657. \draw (z) to (w);
  6658. \draw (x) to (w);
  6659. \draw (y) to (w);
  6660. \draw (v) to (w);
  6661. \draw (v) to (rsp);
  6662. \draw (w) to (rsp);
  6663. \draw (x) to (rsp);
  6664. \draw (y) to (rsp);
  6665. \path[-.,bend left=15] (z) edge node {} (rsp);
  6666. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6667. \draw (rax) to (rsp);
  6668. \end{tikzpicture}
  6669. \]
  6670. Now \code{w} is the most saturated, so we color it $2$.
  6671. \[
  6672. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6673. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6674. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6675. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6676. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6677. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6678. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6679. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6680. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6681. \draw (t1) to (rax);
  6682. \draw (t1) to (z);
  6683. \draw (z) to (y);
  6684. \draw (z) to (w);
  6685. \draw (x) to (w);
  6686. \draw (y) to (w);
  6687. \draw (v) to (w);
  6688. \draw (v) to (rsp);
  6689. \draw (w) to (rsp);
  6690. \draw (x) to (rsp);
  6691. \draw (y) to (rsp);
  6692. \path[-.,bend left=15] (z) edge node {} (rsp);
  6693. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6694. \draw (rax) to (rsp);
  6695. \end{tikzpicture}
  6696. \]
  6697. At this point, vertices \code{x} and \code{v} are most saturated, but
  6698. \code{x} is move related to \code{y} and \code{z}, so we color
  6699. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6700. \[
  6701. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6702. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6703. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6704. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6705. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6706. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6707. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6708. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6709. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6710. \draw (t1) to (rax);
  6711. \draw (t) to (z);
  6712. \draw (z) to (y);
  6713. \draw (z) to (w);
  6714. \draw (x) to (w);
  6715. \draw (y) to (w);
  6716. \draw (v) to (w);
  6717. \draw (v) to (rsp);
  6718. \draw (w) to (rsp);
  6719. \draw (x) to (rsp);
  6720. \draw (y) to (rsp);
  6721. \path[-.,bend left=15] (z) edge node {} (rsp);
  6722. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6723. \draw (rax) to (rsp);
  6724. \end{tikzpicture}
  6725. \]
  6726. \fi}
  6727. %
  6728. {\if\edition\pythonEd\pythonColor
  6729. Now we replay the graph coloring, pausing before the coloring of
  6730. \code{w}. Recall the following configuration. The most saturated vertices
  6731. were \code{tmp\_1}, \code{w}, and \code{y}.
  6732. \[
  6733. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6734. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6735. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6736. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6737. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6738. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6739. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6740. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6741. \draw (t0) to (t1);
  6742. \draw (t0) to (z);
  6743. \draw (z) to (y);
  6744. \draw (z) to (w);
  6745. \draw (x) to (w);
  6746. \draw (y) to (w);
  6747. \draw (v) to (w);
  6748. \end{tikzpicture}
  6749. \]
  6750. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6751. or \code{y}. Note, however, that \code{w} is not move related to any
  6752. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6753. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6754. \code{y} and color it $0$, we can delete another move instruction.
  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}: -, \{\}$};
  6761. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6762. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6763. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  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. Now \code{w} is the most saturated, so we color it $2$.
  6774. \[
  6775. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6776. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6777. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6778. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6779. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6780. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6781. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6782. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6783. \draw (t0) to (t1);
  6784. \draw (t0) to (z);
  6785. \draw (z) to (y);
  6786. \draw (z) to (w);
  6787. \draw (x) to (w);
  6788. \draw (y) to (w);
  6789. \draw (v) to (w);
  6790. \end{tikzpicture}
  6791. \]
  6792. To finish the coloring, \code{x} and \code{v} get $0$ and
  6793. \code{tmp\_1} gets $1$.
  6794. \[
  6795. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6796. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6797. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6798. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6799. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6800. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6801. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6802. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6803. \draw (t0) to (t1);
  6804. \draw (t0) to (z);
  6805. \draw (z) to (y);
  6806. \draw (z) to (w);
  6807. \draw (x) to (w);
  6808. \draw (y) to (w);
  6809. \draw (v) to (w);
  6810. \end{tikzpicture}
  6811. \]
  6812. \fi}
  6813. So, we have the following assignment of variables to registers.
  6814. {\if\edition\racketEd
  6815. \begin{gather*}
  6816. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6817. \ttm{w} \mapsto \key{\%rsi}, \,
  6818. \ttm{x} \mapsto \key{\%rcx}, \,
  6819. \ttm{y} \mapsto \key{\%rcx}, \,
  6820. \ttm{z} \mapsto \key{\%rdx}, \,
  6821. \ttm{t} \mapsto \key{\%rcx} \}
  6822. \end{gather*}
  6823. \fi}
  6824. {\if\edition\pythonEd\pythonColor
  6825. \begin{gather*}
  6826. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6827. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6828. \ttm{x} \mapsto \key{\%rcx}, \,
  6829. \ttm{y} \mapsto \key{\%rcx}, \\
  6830. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6831. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6832. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6833. \end{gather*}
  6834. \fi}
  6835. %
  6836. We apply this register assignment to the running example shown next,
  6837. on the left, to obtain the code in the middle. The
  6838. \code{patch\_instructions} then deletes the trivial moves to obtain
  6839. the code on the right.
  6840. {\if\edition\racketEd
  6841. \begin{center}
  6842. \begin{minipage}{0.2\textwidth}
  6843. \begin{lstlisting}
  6844. movq $1, v
  6845. movq $42, w
  6846. movq v, x
  6847. addq $7, x
  6848. movq x, y
  6849. movq x, z
  6850. addq w, z
  6851. movq y, t
  6852. negq t
  6853. movq z, %rax
  6854. addq t, %rax
  6855. jmp conclusion
  6856. \end{lstlisting}
  6857. \end{minipage}
  6858. $\Rightarrow\qquad$
  6859. \begin{minipage}{0.25\textwidth}
  6860. \begin{lstlisting}
  6861. movq $1, %rcx
  6862. movq $42, %rsi
  6863. movq %rcx, %rcx
  6864. addq $7, %rcx
  6865. movq %rcx, %rcx
  6866. movq %rcx, %rdx
  6867. addq %rsi, %rdx
  6868. movq %rcx, %rcx
  6869. negq %rcx
  6870. movq %rdx, %rax
  6871. addq %rcx, %rax
  6872. jmp conclusion
  6873. \end{lstlisting}
  6874. \end{minipage}
  6875. $\Rightarrow\qquad$
  6876. \begin{minipage}{0.23\textwidth}
  6877. \begin{lstlisting}
  6878. movq $1, %rcx
  6879. movq $42, %rsi
  6880. addq $7, %rcx
  6881. movq %rcx, %rdx
  6882. addq %rsi, %rdx
  6883. negq %rcx
  6884. movq %rdx, %rax
  6885. addq %rcx, %rax
  6886. jmp conclusion
  6887. \end{lstlisting}
  6888. \end{minipage}
  6889. \end{center}
  6890. \fi}
  6891. {\if\edition\pythonEd\pythonColor
  6892. \begin{center}
  6893. \begin{minipage}{0.20\textwidth}
  6894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6895. movq $1, v
  6896. movq $42, w
  6897. movq v, x
  6898. addq $7, x
  6899. movq x, y
  6900. movq x, z
  6901. addq w, z
  6902. movq y, tmp_0
  6903. negq tmp_0
  6904. movq z, tmp_1
  6905. addq tmp_0, tmp_1
  6906. movq tmp_1, %rdi
  6907. callq _print_int
  6908. \end{lstlisting}
  6909. \end{minipage}
  6910. ${\Rightarrow\qquad}$
  6911. \begin{minipage}{0.35\textwidth}
  6912. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6913. movq $1, %rcx
  6914. movq $42, -16(%rbp)
  6915. movq %rcx, %rcx
  6916. addq $7, %rcx
  6917. movq %rcx, %rcx
  6918. movq %rcx, -8(%rbp)
  6919. addq -16(%rbp), -8(%rbp)
  6920. movq %rcx, %rcx
  6921. negq %rcx
  6922. movq -8(%rbp), -8(%rbp)
  6923. addq %rcx, -8(%rbp)
  6924. movq -8(%rbp), %rdi
  6925. callq _print_int
  6926. \end{lstlisting}
  6927. \end{minipage}
  6928. ${\Rightarrow\qquad}$
  6929. \begin{minipage}{0.20\textwidth}
  6930. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6931. movq $1, %rcx
  6932. movq $42, -16(%rbp)
  6933. addq $7, %rcx
  6934. movq %rcx, -8(%rbp)
  6935. movq -16(%rbp), %rax
  6936. addq %rax, -8(%rbp)
  6937. negq %rcx
  6938. addq %rcx, -8(%rbp)
  6939. movq -8(%rbp), %rdi
  6940. callq print_int
  6941. \end{lstlisting}
  6942. \end{minipage}
  6943. \end{center}
  6944. \fi}
  6945. \begin{exercise}\normalfont\normalsize
  6946. Change your implementation of \code{allocate\_registers} to take move
  6947. biasing into account. Create two new tests that include at least one
  6948. opportunity for move biasing, and visually inspect the output x86
  6949. programs to make sure that your move biasing is working properly. Make
  6950. sure that your compiler still passes all the tests.
  6951. \end{exercise}
  6952. %To do: another neat challenge would be to do
  6953. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6954. %% \subsection{Output of the Running Example}
  6955. %% \label{sec:reg-alloc-output}
  6956. % challenge: prioritize variables based on execution frequencies
  6957. % and the number of uses of a variable
  6958. % challenge: enhance the coloring algorithm using Chaitin's
  6959. % approach of prioritizing high-degree variables
  6960. % by removing low-degree variables (coloring them later)
  6961. % from the interference graph
  6962. \section{Further Reading}
  6963. \label{sec:register-allocation-further-reading}
  6964. Early register allocation algorithms were developed for Fortran
  6965. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6966. of graph coloring began in the late 1970s and early 1980s with the
  6967. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6968. algorithm is based on the following observation of
  6969. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6970. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6971. $v$ removed is also $k$ colorable. To see why, suppose that the
  6972. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6973. different colors, but because there are fewer than $k$ neighbors, there
  6974. will be one or more colors left over to use for coloring $v$ in $G$.
  6975. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6976. less than $k$ from the graph and recursively colors the rest of the
  6977. graph. Upon returning from the recursion, it colors $v$ with one of
  6978. the available colors and returns. \citet{Chaitin:1982vn} augments
  6979. this algorithm to handle spilling as follows. If there are no vertices
  6980. of degree lower than $k$ then pick a vertex at random, spill it,
  6981. remove it from the graph, and proceed recursively to color the rest of
  6982. the graph.
  6983. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6984. move-related and that don't interfere with each other, in a process
  6985. called \emph{coalescing}. Although coalescing decreases the number of
  6986. moves, it can make the graph more difficult to
  6987. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6988. which two variables are merged only if they have fewer than $k$
  6989. neighbors of high degree. \citet{George:1996aa} observes that
  6990. conservative coalescing is sometimes too conservative and made it more
  6991. aggressive by iterating the coalescing with the removal of low-degree
  6992. vertices.
  6993. %
  6994. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6995. also proposed \emph{biased coloring}, in which a variable is assigned to
  6996. the same color as another move-related variable if possible, as
  6997. discussed in section~\ref{sec:move-biasing}.
  6998. %
  6999. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  7000. performs coalescing, graph coloring, and spill code insertion until
  7001. all variables have been assigned a location.
  7002. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  7003. spilled variables that don't have to be: a high-degree variable can be
  7004. colorable if many of its neighbors are assigned the same color.
  7005. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  7006. high-degree vertex is not immediately spilled. Instead the decision is
  7007. deferred until after the recursive call, when it is apparent whether
  7008. there is an available color or not. We observe that this algorithm is
  7009. equivalent to the smallest-last ordering
  7010. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  7011. be registers and the rest to be stack locations.
  7012. %% biased coloring
  7013. Earlier editions of the compiler course at Indiana University
  7014. \citep{Dybvig:2010aa} were based on the algorithm of
  7015. \citet{Briggs:1994kx}.
  7016. The smallest-last ordering algorithm is one of many \emph{greedy}
  7017. coloring algorithms. A greedy coloring algorithm visits all the
  7018. vertices in a particular order and assigns each one the first
  7019. available color. An \emph{offline} greedy algorithm chooses the
  7020. ordering up front, prior to assigning colors. The algorithm of
  7021. \citet{Chaitin:1981vl} should be considered offline because the vertex
  7022. ordering does not depend on the colors assigned. Other orderings are
  7023. possible. For example, \citet{Chow:1984ys} ordered variables according
  7024. to an estimate of runtime cost.
  7025. An \emph{online} greedy coloring algorithm uses information about the
  7026. current assignment of colors to influence the order in which the
  7027. remaining vertices are colored. The saturation-based algorithm
  7028. described in this chapter is one such algorithm. We choose to use
  7029. saturation-based coloring because it is fun to introduce graph
  7030. coloring via sudoku!
  7031. A register allocator may choose to map each variable to just one
  7032. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  7033. variable to one or more locations. The latter can be achieved by
  7034. \emph{live range splitting}, where a variable is replaced by several
  7035. variables that each handle part of its live
  7036. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  7037. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  7038. %% replacement algorithm, bottom-up local
  7039. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  7040. %% Cooper: top-down (priority bassed), bottom-up
  7041. %% top-down
  7042. %% order variables by priority (estimated cost)
  7043. %% caveat: split variables into two groups:
  7044. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  7045. %% color the constrained ones first
  7046. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7047. %% cite J. Cocke for an algorithm that colors variables
  7048. %% in a high-degree first ordering
  7049. %Register Allocation via Usage Counts, Freiburghouse CACM
  7050. \citet{Palsberg:2007si} observes that many of the interference graphs
  7051. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7052. that is, every cycle with four or more edges has an edge that is not
  7053. part of the cycle but that connects two vertices on the cycle. Such
  7054. graphs can be optimally colored by the greedy algorithm with a vertex
  7055. ordering determined by maximum cardinality search.
  7056. In situations in which compile time is of utmost importance, such as
  7057. in just-in-time compilers, graph coloring algorithms can be too
  7058. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7059. be more appropriate.
  7060. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7061. {\if\edition\racketEd
  7062. \addtocontents{toc}{\newpage}
  7063. \fi}
  7064. \chapter{Booleans and Conditionals}
  7065. \label{ch:Lif}
  7066. \setcounter{footnote}{0}
  7067. The \LangVar{} language has only a single kind of value, the
  7068. integers. In this chapter we add a second kind of value, the Booleans,
  7069. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7070. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7071. are written
  7072. \TRUE{}\index{subject}{True@\TRUE{}} and
  7073. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7074. language includes several operations that involve Booleans
  7075. (\key{and}\index{subject}{and@\ANDNAME{}},
  7076. \key{or}\index{subject}{or@\ORNAME{}},
  7077. \key{not}\index{subject}{not@\NOTNAME{}},
  7078. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7079. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7080. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7081. conditional expression\index{subject}{conditional expression}%
  7082. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7083. With the addition of \key{if}, programs can have
  7084. nontrivial control flow\index{subject}{control flow}, which
  7085. %
  7086. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7087. %
  7088. \python{impacts liveness analysis and motivates a new pass named
  7089. \code{explicate\_control}.}
  7090. %
  7091. Also, because we now have two kinds of values, we need to handle
  7092. programs that apply an operation to the wrong kind of value, such as
  7093. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7094. There are two language design options for such situations. One option
  7095. is to signal an error and the other is to provide a wider
  7096. interpretation of the operation. \racket{The Racket
  7097. language}\python{Python} uses a mixture of these two options,
  7098. depending on the operation and the kind of value. For example, the
  7099. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7100. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7101. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7102. %
  7103. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7104. in Racket because \code{car} expects a pair.}
  7105. %
  7106. \python{On the other hand, \code{1[0]} results in a runtime error
  7107. in Python because an ``\code{int} object is not subscriptable.''}
  7108. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7109. design choices as \racket{Racket}\python{Python}, except that much of the
  7110. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7111. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7112. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7113. \python{MyPy} reports a compile-time error
  7114. %
  7115. \racket{because Racket expects the type of the argument to be of the form
  7116. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7117. %
  7118. \python{stating that a ``value of type \code{int} is not indexable.''}
  7119. The \LangIf{} language performs type checking during compilation just as
  7120. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7121. the alternative choice, that is, a dynamically typed language like
  7122. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7123. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7124. restrictive, for example, rejecting \racket{\code{(not
  7125. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7126. fairly simple because the focus of this book is on compilation and not
  7127. type systems, about which there are already several excellent
  7128. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7129. This chapter is organized as follows. We begin by defining the syntax
  7130. and interpreter for the \LangIf{} language
  7131. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7132. checking (aka semantic analysis\index{subject}{semantic analysis})
  7133. and define a type checker for \LangIf{}
  7134. (section~\ref{sec:type-check-Lif}).
  7135. %
  7136. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7137. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7138. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7139. %
  7140. The remaining sections of this chapter discuss how Booleans and
  7141. conditional control flow require changes to the existing compiler
  7142. passes and the addition of new ones. We introduce the \code{shrink}
  7143. pass to translate some operators into others, thereby reducing the
  7144. number of operators that need to be handled in later passes.
  7145. %
  7146. The main event of this chapter is the \code{explicate\_control} pass
  7147. that is responsible for translating \code{if}s into conditional
  7148. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7149. %
  7150. Regarding register allocation, there is the interesting question of
  7151. how to handle conditional \code{goto}s during liveness analysis.
  7152. \section{The \LangIf{} Language}
  7153. \label{sec:lang-if}
  7154. Definitions of the concrete syntax and abstract syntax of the
  7155. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7156. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7157. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7158. literals\index{subject}{literals}
  7159. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7160. \python{, and the \code{if} statement}. We expand the set of
  7161. operators to include
  7162. \begin{enumerate}
  7163. \item the logical operators \key{and}, \key{or}, and \key{not},
  7164. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7165. for comparing integers or Booleans for equality, and
  7166. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7167. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7168. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7169. comparing integers.
  7170. \end{enumerate}
  7171. \racket{We reorganize the abstract syntax for the primitive
  7172. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7173. rule for all of them. This means that the grammar no longer checks
  7174. whether the arity of an operator matches the number of
  7175. arguments. That responsibility is moved to the type checker for
  7176. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7177. \newcommand{\LifGrammarRacket}{
  7178. \begin{array}{lcl}
  7179. \Type &::=& \key{Boolean} \\
  7180. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7181. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7182. \Exp &::=& \itm{bool}
  7183. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7184. \MID (\key{not}\;\Exp) \\
  7185. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7186. \end{array}
  7187. }
  7188. \newcommand{\LifASTRacket}{
  7189. \begin{array}{lcl}
  7190. \Type &::=& \key{Boolean} \\
  7191. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7192. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7193. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7194. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7195. \end{array}
  7196. }
  7197. \newcommand{\LintOpAST}{
  7198. \begin{array}{rcl}
  7199. \Type &::=& \key{Integer} \\
  7200. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7201. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7202. \end{array}
  7203. }
  7204. \newcommand{\LifGrammarPython}{
  7205. \begin{array}{rcl}
  7206. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7207. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7208. \MID \key{not}~\Exp \\
  7209. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7210. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7211. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7212. \end{array}
  7213. }
  7214. \newcommand{\LifASTPython}{
  7215. \begin{array}{lcl}
  7216. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7217. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7218. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7219. \Exp &::=& \BOOL{\itm{bool}}
  7220. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7221. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7222. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7223. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7224. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7225. \end{array}
  7226. }
  7227. \begin{figure}[tp]
  7228. \centering
  7229. \begin{tcolorbox}[colback=white]
  7230. {\if\edition\racketEd
  7231. \[
  7232. \begin{array}{l}
  7233. \gray{\LintGrammarRacket{}} \\ \hline
  7234. \gray{\LvarGrammarRacket{}} \\ \hline
  7235. \LifGrammarRacket{} \\
  7236. \begin{array}{lcl}
  7237. \LangIfM{} &::=& \Exp
  7238. \end{array}
  7239. \end{array}
  7240. \]
  7241. \fi}
  7242. {\if\edition\pythonEd\pythonColor
  7243. \[
  7244. \begin{array}{l}
  7245. \gray{\LintGrammarPython} \\ \hline
  7246. \gray{\LvarGrammarPython} \\ \hline
  7247. \LifGrammarPython \\
  7248. \begin{array}{rcl}
  7249. \LangIfM{} &::=& \Stmt^{*}
  7250. \end{array}
  7251. \end{array}
  7252. \]
  7253. \fi}
  7254. \end{tcolorbox}
  7255. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7256. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7257. \label{fig:Lif-concrete-syntax}
  7258. \index{subject}{Lif@\LangIf{} concrete syntax}
  7259. \end{figure}
  7260. \begin{figure}[tp]
  7261. %\begin{minipage}{0.66\textwidth}
  7262. \begin{tcolorbox}[colback=white]
  7263. \centering
  7264. {\if\edition\racketEd
  7265. \[
  7266. \begin{array}{l}
  7267. \gray{\LintOpAST} \\ \hline
  7268. \gray{\LvarASTRacket{}} \\ \hline
  7269. \LifASTRacket{} \\
  7270. \begin{array}{lcl}
  7271. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7272. \end{array}
  7273. \end{array}
  7274. \]
  7275. \fi}
  7276. {\if\edition\pythonEd\pythonColor
  7277. \[
  7278. \begin{array}{l}
  7279. \gray{\LintASTPython} \\ \hline
  7280. \gray{\LvarASTPython} \\ \hline
  7281. \LifASTPython \\
  7282. \begin{array}{lcl}
  7283. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7284. \end{array}
  7285. \end{array}
  7286. \]
  7287. \fi}
  7288. \end{tcolorbox}
  7289. %\end{minipage}
  7290. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7291. \python{
  7292. \index{subject}{BoolOp@\texttt{BoolOp}}
  7293. \index{subject}{Compare@\texttt{Compare}}
  7294. \index{subject}{Lt@\texttt{Lt}}
  7295. \index{subject}{LtE@\texttt{LtE}}
  7296. \index{subject}{Gt@\texttt{Gt}}
  7297. \index{subject}{GtE@\texttt{GtE}}
  7298. }
  7299. \caption{The abstract syntax of \LangIf{}.}
  7300. \label{fig:Lif-syntax}
  7301. \index{subject}{Lif@\LangIf{} abstract syntax}
  7302. \end{figure}
  7303. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7304. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7305. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7306. evaluate to the corresponding Boolean values, behavior that is
  7307. inherited from the interpreter for \LangInt{}
  7308. (figure~\ref{fig:interp-Lint-class}).
  7309. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7310. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7311. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7312. \code{and}, \code{or}, and \code{not} behave according to propositional
  7313. logic. In addition, the \code{and} and \code{or} operations perform
  7314. \emph{short-circuit evaluation}.
  7315. %
  7316. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7317. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7318. %
  7319. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7320. evaluated if $e_1$ evaluates to \TRUE{}.
  7321. \racket{With the increase in the number of primitive operations, the
  7322. interpreter would become repetitive without some care. We refactor
  7323. the case for \code{Prim}, moving the code that differs with each
  7324. operation into the \code{interp\_op} method shown in
  7325. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7326. \code{or} operations separately because of their short-circuiting
  7327. behavior.}
  7328. \begin{figure}[tbp]
  7329. \begin{tcolorbox}[colback=white]
  7330. {\if\edition\racketEd
  7331. \begin{lstlisting}
  7332. (define interp-Lif-class
  7333. (class interp-Lvar-class
  7334. (super-new)
  7335. (define/public (interp_op op) ...)
  7336. (define/override ((interp_exp env) e)
  7337. (define recur (interp_exp env))
  7338. (match e
  7339. [(Bool b) b]
  7340. [(If cnd thn els)
  7341. (match (recur cnd)
  7342. [#t (recur thn)]
  7343. [#f (recur els)])]
  7344. [(Prim 'and (list e1 e2))
  7345. (match (recur e1)
  7346. [#t (match (recur e2) [#t #t] [#f #f])]
  7347. [#f #f])]
  7348. [(Prim 'or (list e1 e2))
  7349. (define v1 (recur e1))
  7350. (match v1
  7351. [#t #t]
  7352. [#f (match (recur e2) [#t #t] [#f #f])])]
  7353. [(Prim op args)
  7354. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7355. [else ((super interp_exp env) e)]))
  7356. ))
  7357. (define (interp_Lif p)
  7358. (send (new interp-Lif-class) interp_program p))
  7359. \end{lstlisting}
  7360. \fi}
  7361. {\if\edition\pythonEd\pythonColor
  7362. \begin{lstlisting}
  7363. class InterpLif(InterpLvar):
  7364. def interp_exp(self, e, env):
  7365. match e:
  7366. case IfExp(test, body, orelse):
  7367. if self.interp_exp(test, env):
  7368. return self.interp_exp(body, env)
  7369. else:
  7370. return self.interp_exp(orelse, env)
  7371. case UnaryOp(Not(), v):
  7372. return not self.interp_exp(v, env)
  7373. case BoolOp(And(), values):
  7374. if self.interp_exp(values[0], env):
  7375. return self.interp_exp(values[1], env)
  7376. else:
  7377. return False
  7378. case BoolOp(Or(), values):
  7379. if self.interp_exp(values[0], env):
  7380. return True
  7381. else:
  7382. return self.interp_exp(values[1], env)
  7383. case Compare(left, [cmp], [right]):
  7384. l = self.interp_exp(left, env)
  7385. r = self.interp_exp(right, env)
  7386. return self.interp_cmp(cmp)(l, r)
  7387. case _:
  7388. return super().interp_exp(e, env)
  7389. def interp_stmt(self, s, env, cont):
  7390. match s:
  7391. case If(test, body, orelse):
  7392. match self.interp_exp(test, env):
  7393. case True:
  7394. return self.interp_stmts(body + cont, env)
  7395. case False:
  7396. return self.interp_stmts(orelse + cont, env)
  7397. case _:
  7398. return super().interp_stmt(s, env, cont)
  7399. ...
  7400. \end{lstlisting}
  7401. \fi}
  7402. \end{tcolorbox}
  7403. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7404. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7405. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7406. \label{fig:interp-Lif}
  7407. \end{figure}
  7408. {\if\edition\racketEd
  7409. \begin{figure}[tbp]
  7410. \begin{tcolorbox}[colback=white]
  7411. \begin{lstlisting}
  7412. (define/public (interp_op op)
  7413. (match op
  7414. ['+ fx+]
  7415. ['- fx-]
  7416. ['read read-fixnum]
  7417. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7418. ['eq? (lambda (v1 v2)
  7419. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7420. (and (boolean? v1) (boolean? v2))
  7421. (and (vector? v1) (vector? v2)))
  7422. (eq? v1 v2)]))]
  7423. ['< (lambda (v1 v2)
  7424. (cond [(and (fixnum? v1) (fixnum? v2))
  7425. (< v1 v2)]))]
  7426. ['<= (lambda (v1 v2)
  7427. (cond [(and (fixnum? v1) (fixnum? v2))
  7428. (<= v1 v2)]))]
  7429. ['> (lambda (v1 v2)
  7430. (cond [(and (fixnum? v1) (fixnum? v2))
  7431. (> v1 v2)]))]
  7432. ['>= (lambda (v1 v2)
  7433. (cond [(and (fixnum? v1) (fixnum? v2))
  7434. (>= v1 v2)]))]
  7435. [else (error 'interp_op "unknown operator")]))
  7436. \end{lstlisting}
  7437. \end{tcolorbox}
  7438. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7439. \label{fig:interp-op-Lif}
  7440. \end{figure}
  7441. \fi}
  7442. {\if\edition\pythonEd\pythonColor
  7443. \begin{figure}
  7444. \begin{tcolorbox}[colback=white]
  7445. \begin{lstlisting}
  7446. class InterpLif(InterpLvar):
  7447. ...
  7448. def interp_cmp(self, cmp):
  7449. match cmp:
  7450. case Lt():
  7451. return lambda x, y: x < y
  7452. case LtE():
  7453. return lambda x, y: x <= y
  7454. case Gt():
  7455. return lambda x, y: x > y
  7456. case GtE():
  7457. return lambda x, y: x >= y
  7458. case Eq():
  7459. return lambda x, y: x == y
  7460. case NotEq():
  7461. return lambda x, y: x != y
  7462. \end{lstlisting}
  7463. \end{tcolorbox}
  7464. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7465. \label{fig:interp-cmp-Lif}
  7466. \end{figure}
  7467. \fi}
  7468. \section{Type Checking \LangIf{} Programs}
  7469. \label{sec:type-check-Lif}
  7470. It is helpful to think about type checking\index{subject}{type
  7471. checking} in two complementary ways. A type checker predicts the
  7472. type of value that will be produced by each expression in the program.
  7473. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7474. type checker should predict that {\if\edition\racketEd
  7475. \begin{lstlisting}
  7476. (+ 10 (- (+ 12 20)))
  7477. \end{lstlisting}
  7478. \fi}
  7479. {\if\edition\pythonEd\pythonColor
  7480. \begin{lstlisting}
  7481. 10 + -(12 + 20)
  7482. \end{lstlisting}
  7483. \fi}
  7484. \noindent produces a value of type \INTTY{}, whereas
  7485. {\if\edition\racketEd
  7486. \begin{lstlisting}
  7487. (and (not #f) #t)
  7488. \end{lstlisting}
  7489. \fi}
  7490. {\if\edition\pythonEd\pythonColor
  7491. \begin{lstlisting}
  7492. (not False) and True
  7493. \end{lstlisting}
  7494. \fi}
  7495. \noindent produces a value of type \BOOLTY{}.
  7496. A second way to think about type checking is that it enforces a set of
  7497. rules about which operators can be applied to which kinds of
  7498. values. For example, our type checker for \LangIf{} signals an error
  7499. for the following expression:
  7500. %
  7501. {\if\edition\racketEd
  7502. \begin{lstlisting}
  7503. (not (+ 10 (- (+ 12 20))))
  7504. \end{lstlisting}
  7505. \fi}
  7506. {\if\edition\pythonEd\pythonColor
  7507. \begin{lstlisting}
  7508. not (10 + -(12 + 20))
  7509. \end{lstlisting}
  7510. \fi}
  7511. \noindent The subexpression
  7512. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7513. \python{\code{(10 + -(12 + 20))}}
  7514. has type \INTTY{}, but the type checker enforces the rule that the
  7515. argument of \code{not} must be an expression of type \BOOLTY{}.
  7516. We implement type checking using classes and methods because they
  7517. provide the open recursion needed to reuse code as we extend the type
  7518. checker in subsequent chapters, analogous to the use of classes and methods
  7519. for the interpreters (section~\ref{sec:extensible-interp}).
  7520. We separate the type checker for the \LangVar{} subset into its own
  7521. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7522. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7523. from the type checker for \LangVar{}. These type checkers are in the
  7524. files
  7525. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7526. and
  7527. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7528. of the support code.
  7529. %
  7530. Each type checker is a structurally recursive function over the AST.
  7531. Given an input expression \code{e}, the type checker either signals an
  7532. error or returns \racket{an expression and its type.}\python{its type.}
  7533. %
  7534. \racket{It returns an expression because there are situations in which
  7535. we want to change or update the expression.}
  7536. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7537. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7538. constant is \INTTY{}. To handle variables, the type checker uses the
  7539. environment \code{env} to map variables to types.
  7540. %
  7541. \racket{Consider the case for \key{let}. We type check the
  7542. initializing expression to obtain its type \key{T} and then
  7543. associate type \code{T} with the variable \code{x} in the
  7544. environment used to type check the body of the \key{let}. Thus,
  7545. when the type checker encounters a use of variable \code{x}, it can
  7546. find its type in the environment.}
  7547. %
  7548. \python{Consider the case for assignment. We type check the
  7549. initializing expression to obtain its type \key{t}. If the variable
  7550. \code{id} is already in the environment because there was a
  7551. prior assignment, we check that this initializer has the same type
  7552. as the prior one. If this is the first assignment to the variable,
  7553. we associate type \code{t} with the variable \code{id} in the
  7554. environment. Thus, when the type checker encounters a use of
  7555. variable \code{x}, it can find its type in the environment.}
  7556. %
  7557. \racket{Regarding primitive operators, we recursively analyze the
  7558. arguments and then invoke \code{type\_check\_op} to check whether
  7559. the argument types are allowed.}
  7560. %
  7561. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7562. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7563. \racket{Several auxiliary methods are used in the type checker. The
  7564. method \code{operator-types} defines a dictionary that maps the
  7565. operator names to their parameter and return types. The
  7566. \code{type-equal?} method determines whether two types are equal,
  7567. which for now simply dispatches to \code{equal?} (deep
  7568. equality). The \code{check-type-equal?} method triggers an error if
  7569. the two types are not equal. The \code{type-check-op} method looks
  7570. up the operator in the \code{operator-types} dictionary and then
  7571. checks whether the argument types are equal to the parameter types.
  7572. The result is the return type of the operator.}
  7573. %
  7574. \python{The auxiliary method \code{check\_type\_equal} triggers
  7575. an error if the two types are not equal.}
  7576. \begin{figure}[tbp]
  7577. \begin{tcolorbox}[colback=white]
  7578. {\if\edition\racketEd
  7579. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7580. (define type-check-Lvar-class
  7581. (class object%
  7582. (super-new)
  7583. (define/public (operator-types)
  7584. '((+ . ((Integer Integer) . Integer))
  7585. (- . ((Integer Integer) . Integer))
  7586. (read . (() . Integer))))
  7587. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7588. (define/public (check-type-equal? t1 t2 e)
  7589. (unless (type-equal? t1 t2)
  7590. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7591. (define/public (type-check-op op arg-types e)
  7592. (match (dict-ref (operator-types) op)
  7593. [`(,param-types . ,return-type)
  7594. (for ([at arg-types] [pt param-types])
  7595. (check-type-equal? at pt e))
  7596. return-type]
  7597. [else (error 'type-check-op "unrecognized ~a" op)]))
  7598. (define/public (type-check-exp env)
  7599. (lambda (e)
  7600. (match e
  7601. [(Int n) (values (Int n) 'Integer)]
  7602. [(Var x) (values (Var x) (dict-ref env x))]
  7603. [(Let x e body)
  7604. (define-values (e^ Te) ((type-check-exp env) e))
  7605. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7606. (values (Let x e^ b) Tb)]
  7607. [(Prim op es)
  7608. (define-values (new-es ts)
  7609. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7610. (values (Prim op new-es) (type-check-op op ts e))]
  7611. [else (error 'type-check-exp "couldn't match" e)])))
  7612. (define/public (type-check-program e)
  7613. (match e
  7614. [(Program info body)
  7615. (define-values (body^ Tb) ((type-check-exp '()) body))
  7616. (check-type-equal? Tb 'Integer body)
  7617. (Program info body^)]
  7618. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7619. ))
  7620. (define (type-check-Lvar p)
  7621. (send (new type-check-Lvar-class) type-check-program p))
  7622. \end{lstlisting}
  7623. \fi}
  7624. {\if\edition\pythonEd\pythonColor
  7625. \begin{lstlisting}[escapechar=`]
  7626. class TypeCheckLvar:
  7627. def check_type_equal(self, t1, t2, e):
  7628. if t1 != t2:
  7629. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7630. raise Exception(msg)
  7631. def type_check_exp(self, e, env):
  7632. match e:
  7633. case BinOp(left, (Add() | Sub()), right):
  7634. l = self.type_check_exp(left, env)
  7635. check_type_equal(l, int, left)
  7636. r = self.type_check_exp(right, env)
  7637. check_type_equal(r, int, right)
  7638. return int
  7639. case UnaryOp(USub(), v):
  7640. t = self.type_check_exp(v, env)
  7641. check_type_equal(t, int, v)
  7642. return int
  7643. case Name(id):
  7644. return env[id]
  7645. case Constant(value) if isinstance(value, int):
  7646. return int
  7647. case Call(Name('input_int'), []):
  7648. return int
  7649. def type_check_stmts(self, ss, env):
  7650. if len(ss) == 0:
  7651. return
  7652. match ss[0]:
  7653. case Assign([Name(id)], value):
  7654. t = self.type_check_exp(value, env)
  7655. if id in env:
  7656. check_type_equal(env[id], t, value)
  7657. else:
  7658. env[id] = t
  7659. return self.type_check_stmts(ss[1:], env)
  7660. case Expr(Call(Name('print'), [arg])):
  7661. t = self.type_check_exp(arg, env)
  7662. check_type_equal(t, int, arg)
  7663. return self.type_check_stmts(ss[1:], env)
  7664. case Expr(value):
  7665. self.type_check_exp(value, env)
  7666. return self.type_check_stmts(ss[1:], env)
  7667. def type_check_P(self, p):
  7668. match p:
  7669. case Module(body):
  7670. self.type_check_stmts(body, {})
  7671. \end{lstlisting}
  7672. \fi}
  7673. \end{tcolorbox}
  7674. \caption{Type checker for the \LangVar{} language.}
  7675. \label{fig:type-check-Lvar}
  7676. \end{figure}
  7677. \begin{figure}[tbp]
  7678. \begin{tcolorbox}[colback=white]
  7679. {\if\edition\racketEd
  7680. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7681. (define type-check-Lif-class
  7682. (class type-check-Lvar-class
  7683. (super-new)
  7684. (inherit check-type-equal?)
  7685. (define/override (operator-types)
  7686. (append '((and . ((Boolean Boolean) . Boolean))
  7687. (or . ((Boolean Boolean) . Boolean))
  7688. (< . ((Integer Integer) . Boolean))
  7689. (<= . ((Integer Integer) . Boolean))
  7690. (> . ((Integer Integer) . Boolean))
  7691. (>= . ((Integer Integer) . Boolean))
  7692. (not . ((Boolean) . Boolean)))
  7693. (super operator-types)))
  7694. (define/override (type-check-exp env)
  7695. (lambda (e)
  7696. (match e
  7697. [(Bool b) (values (Bool b) 'Boolean)]
  7698. [(Prim 'eq? (list e1 e2))
  7699. (define-values (e1^ T1) ((type-check-exp env) e1))
  7700. (define-values (e2^ T2) ((type-check-exp env) e2))
  7701. (check-type-equal? T1 T2 e)
  7702. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7703. [(If cnd thn els)
  7704. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7705. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7706. (define-values (els^ Te) ((type-check-exp env) els))
  7707. (check-type-equal? Tc 'Boolean e)
  7708. (check-type-equal? Tt Te e)
  7709. (values (If cnd^ thn^ els^) Te)]
  7710. [else ((super type-check-exp env) e)])))
  7711. ))
  7712. (define (type-check-Lif p)
  7713. (send (new type-check-Lif-class) type-check-program p))
  7714. \end{lstlisting}
  7715. \fi}
  7716. {\if\edition\pythonEd\pythonColor
  7717. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7718. class TypeCheckLif(TypeCheckLvar):
  7719. def type_check_exp(self, e, env):
  7720. match e:
  7721. case Constant(value) if isinstance(value, bool):
  7722. return bool
  7723. case BinOp(left, Sub(), right):
  7724. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7725. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7726. return int
  7727. case UnaryOp(Not(), v):
  7728. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7729. return bool
  7730. case BoolOp(op, values):
  7731. left = values[0] ; right = values[1]
  7732. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7733. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7734. return bool
  7735. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7736. or isinstance(cmp, NotEq):
  7737. l = self.type_check_exp(left, env)
  7738. r = self.type_check_exp(right, env)
  7739. check_type_equal(l, r, e)
  7740. return bool
  7741. case Compare(left, [cmp], [right]):
  7742. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7743. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7744. return bool
  7745. case IfExp(test, body, orelse):
  7746. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7747. b = self.type_check_exp(body, env)
  7748. o = self.type_check_exp(orelse, env)
  7749. check_type_equal(b, o, e)
  7750. return b
  7751. case _:
  7752. return super().type_check_exp(e, env)
  7753. def type_check_stmts(self, ss, env):
  7754. if len(ss) == 0:
  7755. return
  7756. match ss[0]:
  7757. case If(test, body, orelse):
  7758. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7759. b = self.type_check_stmts(body, env)
  7760. o = self.type_check_stmts(orelse, env)
  7761. check_type_equal(b, o, ss[0])
  7762. return self.type_check_stmts(ss[1:], env)
  7763. case _:
  7764. return super().type_check_stmts(ss, env)
  7765. \end{lstlisting}
  7766. \fi}
  7767. \end{tcolorbox}
  7768. \caption{Type checker for the \LangIf{} language.}
  7769. \label{fig:type-check-Lif}
  7770. \end{figure}
  7771. The definition of the type checker for \LangIf{} is shown in
  7772. figure~\ref{fig:type-check-Lif}.
  7773. %
  7774. The type of a Boolean constant is \BOOLTY{}.
  7775. %
  7776. \racket{The \code{operator-types} function adds dictionary entries for
  7777. the new operators.}
  7778. %
  7779. \python{The logical \code{not} operator requires its argument to be a
  7780. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7781. and logical \code{or} operators.}
  7782. %
  7783. The equality operator requires the two arguments to have the same type,
  7784. and therefore we handle it separately from the other operators.
  7785. %
  7786. \python{The other comparisons (less-than, etc.) require their
  7787. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7788. %
  7789. The condition of an \code{if} must
  7790. be of \BOOLTY{} type, and the two branches must have the same type.
  7791. \begin{exercise}\normalfont\normalsize
  7792. Create ten new test programs in \LangIf{}. Half the programs should
  7793. have a type error.
  7794. \racket{For those programs, create an empty file with the
  7795. same base name and with file extension \code{.tyerr}. For example, if
  7796. the test \code{cond\_test\_14.rkt}
  7797. is expected to error, then create
  7798. an empty file named \code{cond\_test\_14.tyerr}.
  7799. This indicates to \code{interp-tests} and
  7800. \code{compiler-tests} that a type error is expected.}
  7801. %
  7802. The other half of the test programs should not have type errors.
  7803. %
  7804. \racket{In the \code{run-tests.rkt} script, change the second argument
  7805. of \code{interp-tests} and \code{compiler-tests} to
  7806. \code{type-check-Lif}, which causes the type checker to run prior to
  7807. the compiler passes. Temporarily change the \code{passes} to an
  7808. empty list and run the script, thereby checking that the new test
  7809. programs either type check or do not, as intended.}
  7810. %
  7811. Run the test script to check that these test programs type check as
  7812. expected.
  7813. \end{exercise}
  7814. \clearpage
  7815. \section{The \LangCIf{} Intermediate Language}
  7816. \label{sec:Cif}
  7817. {\if\edition\racketEd
  7818. %
  7819. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7820. comparison operators to the \Exp{} nonterminal and the literals
  7821. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7822. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7823. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7824. comparison operation and the branches are \code{goto} statements,
  7825. making it straightforward to compile \code{if} statements to x86. The
  7826. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7827. expressions. A \code{goto} statement transfers control to the $\Tail$
  7828. expression corresponding to its label.
  7829. %
  7830. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7831. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7832. defines its abstract syntax.
  7833. %
  7834. \fi}
  7835. %
  7836. {\if\edition\pythonEd\pythonColor
  7837. %
  7838. The output of \key{explicate\_control} is a language similar to the
  7839. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7840. \code{goto} statements, so we name it \LangCIf{}.
  7841. %
  7842. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7843. the arguments of operators are restricted to atomic expressions. The
  7844. \LangCIf{} language does not include \code{if} expressions, but it does
  7845. include a restricted form of \code{if} statement. The condition must be
  7846. a comparison, and the two branches may contain only \code{goto}
  7847. statements. These restrictions make it easier to translate \code{if}
  7848. statements to x86. The \LangCIf{} language also adds a \code{return}
  7849. statement to finish the program with a specified value.
  7850. %
  7851. The \key{CProgram} construct contains a dictionary mapping labels to
  7852. lists of statements that end with a \emph{tail} statement, which is
  7853. either a \code{return} statement, a \code{goto}, or an
  7854. \code{if} statement.
  7855. %
  7856. A \code{goto} transfers control to the sequence of statements
  7857. associated with its label.
  7858. %
  7859. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7860. and figure~\ref{fig:c1-syntax} shows its
  7861. abstract syntax.
  7862. %
  7863. \fi}
  7864. %
  7865. \newcommand{\CifGrammarRacket}{
  7866. \begin{array}{lcl}
  7867. \Atm &::=& \itm{bool} \\
  7868. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7869. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7870. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7871. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7872. \end{array}
  7873. }
  7874. \newcommand{\CifASTRacket}{
  7875. \begin{array}{lcl}
  7876. \Atm &::=& \BOOL{\itm{bool}} \\
  7877. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7878. \Exp &::= & \UNIOP{\key{\textquotesingle not}}{\Atm} \MID \BINOP{\key{\textquotesingle}\itm{cmp}}{\Atm}{\Atm} \\
  7879. \Tail &::= & \GOTO{\itm{label}} \\
  7880. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7881. \end{array}
  7882. }
  7883. \newcommand{\CifGrammarPython}{
  7884. \begin{array}{lcl}
  7885. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7886. \Exp &::= & \Atm \MID \CREAD{}
  7887. \MID \CUNIOP{\key{-}}{\Atm}
  7888. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7889. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7890. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7891. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7892. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7893. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7894. \end{array}
  7895. }
  7896. \newcommand{\CifASTPython}{
  7897. \begin{array}{lcl}
  7898. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7899. \Exp &::= & \Atm \MID \READ{}
  7900. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7901. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7902. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7903. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7904. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7905. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7906. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7907. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7908. \end{array}
  7909. }
  7910. \begin{figure}[tbp]
  7911. \begin{tcolorbox}[colback=white]
  7912. \small
  7913. {\if\edition\racketEd
  7914. \[
  7915. \begin{array}{l}
  7916. \gray{\CvarGrammarRacket} \\ \hline
  7917. \CifGrammarRacket \\
  7918. \begin{array}{lcl}
  7919. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7920. \end{array}
  7921. \end{array}
  7922. \]
  7923. \fi}
  7924. {\if\edition\pythonEd\pythonColor
  7925. \[
  7926. \begin{array}{l}
  7927. \CifGrammarPython \\
  7928. \begin{array}{lcl}
  7929. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7930. \end{array}
  7931. \end{array}
  7932. \]
  7933. \fi}
  7934. \end{tcolorbox}
  7935. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7936. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7937. \label{fig:c1-concrete-syntax}
  7938. \index{subject}{Cif@\LangCIf{} concrete syntax}
  7939. \end{figure}
  7940. \begin{figure}[tp]
  7941. \begin{tcolorbox}[colback=white]
  7942. \small
  7943. {\if\edition\racketEd
  7944. \[
  7945. \begin{array}{l}
  7946. \gray{\CvarASTRacket} \\ \hline
  7947. \CifASTRacket \\
  7948. \begin{array}{lcl}
  7949. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7950. \end{array}
  7951. \end{array}
  7952. \]
  7953. \fi}
  7954. {\if\edition\pythonEd\pythonColor
  7955. \[
  7956. \begin{array}{l}
  7957. \CifASTPython \\
  7958. \begin{array}{lcl}
  7959. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7960. \end{array}
  7961. \end{array}
  7962. \]
  7963. \fi}
  7964. \end{tcolorbox}
  7965. \racket{
  7966. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7967. }
  7968. \index{subject}{Goto@\texttt{Goto}}
  7969. \index{subject}{Return@\texttt{Return}}
  7970. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7971. (figure~\ref{fig:c0-syntax})}.}
  7972. \label{fig:c1-syntax}
  7973. \index{subject}{Cif@\LangCIf{} abstract syntax}
  7974. \end{figure}
  7975. \section{The \LangXIf{} Language}
  7976. \label{sec:x86-if}
  7977. \index{subject}{x86}
  7978. To implement Booleans, the new logical operations, the
  7979. comparison operations, and the \key{if} expression\python{ and
  7980. statement}, we delve further into the x86
  7981. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7982. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7983. subset of x86, which includes instructions for logical operations,
  7984. comparisons, and \racket{conditional} jumps.
  7985. %
  7986. \python{The abstract syntax for an \LangXIf{} program contains a
  7987. dictionary mapping labels to sequences of instructions, each of
  7988. which we refer to as a \emph{basic block}\index{subject}{basic
  7989. block}.}
  7990. As x86 does not provide direct support for Booleans, we take the usual
  7991. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7992. \code{False} as $0$.
  7993. Furthermore, x86 does not provide an instruction that directly
  7994. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7995. However, the \code{xorq} instruction can be used to encode \code{not}.
  7996. The \key{xorq} instruction takes two arguments, performs a pairwise
  7997. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7998. and writes the results into its second argument. Recall the following
  7999. truth table for exclusive-or:
  8000. \begin{center}
  8001. \begin{tabular}{l|cc}
  8002. & 0 & 1 \\ \hline
  8003. 0 & 0 & 1 \\
  8004. 1 & 1 & 0
  8005. \end{tabular}
  8006. \end{center}
  8007. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  8008. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  8009. for the bit $1$, the result is the opposite of the second bit. Thus,
  8010. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  8011. the first argument, as follows, where $\Arg$ is the translation of
  8012. $\Atm$ to x86:
  8013. \[
  8014. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  8015. \qquad\Rightarrow\qquad
  8016. \begin{array}{l}
  8017. \key{movq}~ \Arg\key{,} \Var\\
  8018. \key{xorq}~ \key{\$1,} \Var
  8019. \end{array}
  8020. \]
  8021. \newcommand{\GrammarXIfRacket}{
  8022. \begin{array}{lcl}
  8023. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8024. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8025. \Arg &::=& \key{\%}\itm{bytereg}\\
  8026. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8027. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8028. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8029. \MID \key{set}cc~\Arg
  8030. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8031. &\MID& \key{j}cc~\itm{label} \\
  8032. \end{array}
  8033. }
  8034. \newcommand{\GrammarXIfPython}{
  8035. \begin{array}{lcl}
  8036. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8037. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8038. \Arg &::=& \key{\%}\itm{bytereg}\\
  8039. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8040. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8041. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8042. \MID \key{set}cc~\Arg
  8043. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8044. &\MID& \key{jmp}\,\itm{label} \MID \key{j}cc~\itm{label}
  8045. \MID \itm{label}\key{:}\; \Instr
  8046. \end{array}
  8047. }
  8048. \begin{figure}[tp]
  8049. \begin{tcolorbox}[colback=white]
  8050. {\if\edition\racketEd
  8051. \[
  8052. \begin{array}{l}
  8053. \gray{\GrammarXIntRacket} \\ \hline
  8054. \GrammarXIfRacket \\
  8055. \begin{array}{lcl}
  8056. \LangXIfM{} &::= & \key{.globl main} \\
  8057. & & \key{main:} \; \Instr\ldots
  8058. \end{array}
  8059. \end{array}
  8060. \]
  8061. \fi}
  8062. {\if\edition\pythonEd
  8063. \[
  8064. \begin{array}{l}
  8065. \gray{\GrammarXIntPython} \\ \hline
  8066. \GrammarXIfPython \\
  8067. \begin{array}{lcl}
  8068. \LangXIfM{} &::= & \key{.globl main} \\
  8069. & & \key{main:} \; \Instr\ldots
  8070. \end{array}
  8071. \end{array}
  8072. \]
  8073. \fi}
  8074. \end{tcolorbox}
  8075. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  8076. \label{fig:x86-1-concrete}
  8077. \index{subject}{x86if@\LangXIf{} concrete syntax}
  8078. \end{figure}
  8079. \newcommand{\ASTXIfRacket}{
  8080. \begin{array}{lcl}
  8081. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8082. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8083. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8084. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8085. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8086. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8087. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8088. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8089. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8090. \end{array}
  8091. }
  8092. \newcommand{\ASTXIfPython}{
  8093. \begin{array}{lcl}
  8094. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8095. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8096. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8097. \MID \BYTEREG{\itm{bytereg}} \\
  8098. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8099. \Instr &::=& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8100. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8101. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8102. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8103. &\MID& \python{\JMP{\itm{label}}} \MID \JMPIF{\itm{cc}}{\itm{label}}
  8104. \end{array}
  8105. }
  8106. \begin{figure}[tp]
  8107. \begin{tcolorbox}[colback=white]
  8108. \small
  8109. {\if\edition\racketEd
  8110. \[\arraycolsep=3pt
  8111. \begin{array}{l}
  8112. \gray{\ASTXIntRacket} \\ \hline
  8113. \ASTXIfRacket \\
  8114. \begin{array}{lcl}
  8115. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8116. \end{array}
  8117. \end{array}
  8118. \]
  8119. \fi}
  8120. %
  8121. {\if\edition\pythonEd\pythonColor
  8122. \[
  8123. \begin{array}{l}
  8124. \gray{\ASTXIntPython} \\ \hline
  8125. \ASTXIfPython \\
  8126. \begin{array}{lcl}
  8127. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8128. \end{array}
  8129. \end{array}
  8130. \]
  8131. \fi}
  8132. \end{tcolorbox}
  8133. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8134. \label{fig:x86-1}
  8135. \index{subject}{x86if@\LangXIf{} abstract syntax}
  8136. \end{figure}
  8137. Next we consider the x86 instructions that are relevant for compiling
  8138. the comparison operations. The \key{cmpq} instruction compares its two
  8139. arguments to determine whether one argument is less than, equal to, or
  8140. greater than the other argument. The \key{cmpq} instruction is unusual
  8141. regarding the order of its arguments and where the result is
  8142. placed. The argument order is backward: if you want to test whether
  8143. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8144. \key{cmpq} is placed in the special EFLAGS register. This register
  8145. cannot be accessed directly, but it can be queried by a number of
  8146. instructions, including the \key{set} instruction. The instruction
  8147. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8148. depending on whether the contents of the EFLAGS register matches the
  8149. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8150. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8151. The \key{set} instruction has a quirk in that its destination argument
  8152. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8153. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8154. register. Thankfully, the \key{movzbq} instruction can be used to
  8155. move from a single-byte register to a normal 64-bit register. The
  8156. abstract syntax for the \code{set} instruction differs from the
  8157. concrete syntax in that it separates the instruction name from the
  8158. condition code.
  8159. \python{The x86 instructions for jumping are relevant to the
  8160. compilation of \key{if} expressions.}
  8161. %
  8162. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8163. counter to the address of the instruction after the specified
  8164. label.}
  8165. %
  8166. \racket{The x86 instruction for conditional jump is relevant to the
  8167. compilation of \key{if} expressions.}
  8168. %
  8169. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8170. counter to point to the instruction after \itm{label}, depending on
  8171. whether the result in the EFLAGS register matches the condition code
  8172. \itm{cc}; otherwise, the jump instruction falls through to the next
  8173. instruction. Like the abstract syntax for \code{set}, the abstract
  8174. syntax for conditional jump separates the instruction name from the
  8175. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8176. corresponds to \code{jle foo}. Because the conditional jump instruction
  8177. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8178. a \key{cmpq} instruction to set the EFLAGS register.
  8179. \section{Shrink the \LangIf{} Language}
  8180. \label{sec:shrink-Lif}
  8181. The \code{shrink} pass translates some of the language features into
  8182. other features, thereby reducing the kinds of expressions in the
  8183. language. For example, the short-circuiting nature of the \code{and}
  8184. and \code{or} logical operators can be expressed using \code{if} as
  8185. follows.
  8186. \begin{align*}
  8187. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8188. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8189. \end{align*}
  8190. By performing these translations in the front end of the compiler,
  8191. subsequent passes of the compiler can be shorter.
  8192. On the other hand, translations sometimes reduce the efficiency of the
  8193. generated code by increasing the number of instructions. For example,
  8194. expressing subtraction in terms of addition and negation
  8195. \[
  8196. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8197. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8198. \]
  8199. produces code with two x86 instructions (\code{negq} and \code{addq})
  8200. instead of just one (\code{subq}). Thus, we do not recommend
  8201. translating subtraction into addition and negation.
  8202. \begin{exercise}\normalfont\normalsize
  8203. %
  8204. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8205. the language by translating them to \code{if} expressions in \LangIf{}.
  8206. %
  8207. Create four test programs that involve these operators.
  8208. %
  8209. {\if\edition\racketEd
  8210. In the \code{run-tests.rkt} script, add the following entry for
  8211. \code{shrink} to the list of passes (it should be the only pass at
  8212. this point).
  8213. \begin{lstlisting}
  8214. (list "shrink" shrink interp_Lif type-check-Lif)
  8215. \end{lstlisting}
  8216. This instructs \code{interp-tests} to run the interpreter
  8217. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8218. output of \code{shrink}.
  8219. \fi}
  8220. %
  8221. Run the script to test your compiler on all the test programs.
  8222. \end{exercise}
  8223. {\if\edition\racketEd
  8224. \section{Uniquify Variables}
  8225. \label{sec:uniquify-Lif}
  8226. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8227. \code{if} expressions.
  8228. \begin{exercise}\normalfont\normalsize
  8229. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8230. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8231. \begin{lstlisting}
  8232. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8233. \end{lstlisting}
  8234. Run the script to test your compiler.
  8235. \end{exercise}
  8236. \fi}
  8237. \section{Remove Complex Operands}
  8238. \label{sec:remove-complex-opera-Lif}
  8239. The output language of \code{remove\_complex\_operands} is
  8240. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8241. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8242. but the \code{if} expression is not. All three subexpressions of an
  8243. \code{if} are allowed to be complex expressions, but the operands of
  8244. the \code{not} operator and comparison operators must be atomic.
  8245. %
  8246. \python{We add a new language form, the \code{Begin} expression, to aid
  8247. in the translation of \code{if} expressions. When we recursively
  8248. process the two branches of the \code{if}, we generate temporary
  8249. variables and their initializing expressions. However, these
  8250. expressions may contain side effects and should be executed only
  8251. when the condition of the \code{if} is true (for the ``then''
  8252. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8253. provides a way to initialize the temporary variables within the two branches
  8254. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8255. form executes the statements $ss$ and then returns the result of
  8256. expression $e$.}
  8257. \racket{Add cases to the \code{rco\_exp} and \code{rco\_atom}
  8258. functions for the new features in \LangIf{}. In recursively
  8259. processing subexpressions, recall that you should invoke
  8260. \code{rco\_atom} when the output needs to be an \Atm{} (as specified
  8261. in the grammar for \LangIfANF{}) and invoke \code{rco\_exp} when the
  8262. output should be \Exp{}.}
  8263. %
  8264. \python{Add cases to the \code{rco\_exp} function for the new features
  8265. in \LangIf{}. In recursively processing subexpressions, recall that
  8266. you should invoke \code{rco\_exp} with the extra argument
  8267. \code{True} when the output needs to be an \Atm{} (as specified in
  8268. the grammar for \LangIfANF{}) and \code{False} when the output
  8269. should be \Exp{}.}
  8270. %
  8271. Regarding \code{if}, it is particularly important \emph{not} to
  8272. replace its condition with a temporary variable, because that would
  8273. interfere with the generation of high-quality output in the upcoming
  8274. \code{explicate\_control} pass.
  8275. \newcommand{\LifMonadASTRacket}{
  8276. \begin{array}{rcl}
  8277. \Atm &::=& \BOOL{\itm{bool}}\\
  8278. \Exp &::=& \UNIOP{\key{\textquotesingle not}}{\Atm}
  8279. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8280. \MID \IF{\Exp}{\Exp}{\Exp}
  8281. \end{array}
  8282. }
  8283. \newcommand{\LifMonadASTPython}{
  8284. \begin{array}{rcl}
  8285. \Atm &::=& \BOOL{\itm{bool}}\\
  8286. \Exp &::=& \UNIOP{\key{Not()}}{\Atm}
  8287. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8288. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8289. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8290. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8291. \end{array}
  8292. }
  8293. \begin{figure}[tp]
  8294. \centering
  8295. \begin{tcolorbox}[colback=white]
  8296. {\if\edition\racketEd
  8297. \[
  8298. \begin{array}{l}
  8299. \gray{\LvarMonadASTRacket} \\ \hline
  8300. \LifMonadASTRacket \\
  8301. \begin{array}{rcl}
  8302. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8303. \end{array}
  8304. \end{array}
  8305. \]
  8306. \fi}
  8307. {\if\edition\pythonEd\pythonColor
  8308. \[
  8309. \begin{array}{l}
  8310. \gray{\LvarMonadASTPython} \\ \hline
  8311. \LifMonadASTPython \\
  8312. \begin{array}{rcl}
  8313. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8314. \end{array}
  8315. \end{array}
  8316. \]
  8317. \fi}
  8318. \end{tcolorbox}
  8319. \python{\index{subject}{Begin@\texttt{Begin}}}
  8320. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8321. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8322. \label{fig:Lif-anf-syntax}
  8323. \index{subject}{Lifmon@\LangIfANF{} abstract syntax}
  8324. \end{figure}
  8325. \begin{exercise}\normalfont\normalsize
  8326. %
  8327. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8328. and \code{rco\_exp} functions.
  8329. %
  8330. Create three new \LangIf{} programs that exercise the interesting
  8331. code in this pass.
  8332. %
  8333. {\if\edition\racketEd
  8334. In the \code{run-tests.rkt} script, add the following entry to the
  8335. list of \code{passes} and then run the script to test your compiler.
  8336. \begin{lstlisting}
  8337. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8338. \end{lstlisting}
  8339. \fi}
  8340. \end{exercise}
  8341. \section{Explicate Control}
  8342. \label{sec:explicate-control-Lif}
  8343. \racket{Recall that the purpose of \code{explicate\_control} is to
  8344. make the order of evaluation explicit in the syntax of the program.
  8345. With the addition of \key{if}, this becomes more interesting.}
  8346. %
  8347. The \code{explicate\_control} pass translates from \LangIfANF{} to \LangCIf{}.
  8348. %
  8349. The main challenge to overcome is that the condition of an \key{if}
  8350. can be an arbitrary expression in \LangIfANF{}, whereas in \LangCIf{} the
  8351. condition must be a comparison.
  8352. As a motivating example, consider the following program that has an
  8353. \key{if} expression nested in the condition of another \key{if}:%
  8354. \python{\footnote{Programmers rarely write nested \code{if}
  8355. expressions, but they do write nested expressions involving
  8356. logical \code{and}, which, as we have seen, translates to
  8357. \code{if}.}}
  8358. % cond_test_41.rkt, if_lt_eq.py
  8359. \begin{center}
  8360. \begin{minipage}{0.96\textwidth}
  8361. {\if\edition\racketEd
  8362. \begin{lstlisting}
  8363. (let ([x (read)])
  8364. (let ([y (read)])
  8365. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8366. (+ y 2)
  8367. (+ y 10))))
  8368. \end{lstlisting}
  8369. \fi}
  8370. {\if\edition\pythonEd\pythonColor
  8371. \begin{lstlisting}
  8372. x = input_int()
  8373. y = input_int()
  8374. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8375. \end{lstlisting}
  8376. \fi}
  8377. \end{minipage}
  8378. \end{center}
  8379. %
  8380. The naive way to compile \key{if} and the comparison operations would
  8381. be to handle each of them in isolation, regardless of their context.
  8382. Each comparison would be translated into a \key{cmpq} instruction
  8383. followed by several instructions to move the result from the EFLAGS
  8384. register into a general purpose register or stack location. Each
  8385. \key{if} would be translated into a \key{cmpq} instruction followed by
  8386. a conditional jump. The generated code for the inner \key{if} in this
  8387. example would be as follows:
  8388. \begin{center}
  8389. \begin{minipage}{0.96\textwidth}
  8390. \begin{lstlisting}
  8391. cmpq $1, x
  8392. setl %al
  8393. movzbq %al, tmp
  8394. cmpq $1, tmp
  8395. je then_branch_1
  8396. jmp else_branch_1
  8397. \end{lstlisting}
  8398. \end{minipage}
  8399. \end{center}
  8400. Notice that the three instructions starting with \code{setl} are
  8401. redundant; the conditional jump could come immediately after the first
  8402. \code{cmpq}.
  8403. Our goal is to compile \key{if} expressions so that the relevant
  8404. comparison instruction appears directly before the conditional jump.
  8405. For example, we want to generate the following code for the inner
  8406. \code{if}:
  8407. \begin{center}
  8408. \begin{minipage}{0.96\textwidth}
  8409. \begin{lstlisting}
  8410. cmpq $1, x
  8411. jl then_branch_1
  8412. jmp else_branch_1
  8413. \end{lstlisting}
  8414. \end{minipage}
  8415. \end{center}
  8416. One way to achieve this goal is to reorganize the code at the level of
  8417. \LangIf{} or \LangIfANF{}, pushing the outer \key{if} inside the inner one, yielding
  8418. the following code:
  8419. \begin{center}
  8420. \begin{minipage}{0.96\textwidth}
  8421. {\if\edition\racketEd
  8422. \begin{lstlisting}
  8423. (let ([x (read)])
  8424. (let ([y (read)])
  8425. (if (< x 1)
  8426. (if (eq? x 0)
  8427. (+ y 2)
  8428. (+ y 10))
  8429. (if (eq? x 2)
  8430. (+ y 2)
  8431. (+ y 10)))))
  8432. \end{lstlisting}
  8433. \fi}
  8434. {\if\edition\pythonEd\pythonColor
  8435. \begin{lstlisting}
  8436. x = input_int()
  8437. y = input_int()
  8438. print(((y + 2) if x == 0 else (y + 10)) \
  8439. if (x < 1) \
  8440. else ((y + 2) if (x == 2) else (y + 10)))
  8441. \end{lstlisting}
  8442. \fi}
  8443. \end{minipage}
  8444. \end{center}
  8445. Unfortunately, this approach duplicates the two branches from the
  8446. outer \code{if}, and a compiler must never duplicate code! After all,
  8447. the two branches could be very large expressions.
  8448. How can we apply this transformation without duplicating code? In
  8449. other words, how can two different parts of a program refer to one
  8450. piece of code?
  8451. %
  8452. The answer is that we must move away from abstract syntax \emph{trees}
  8453. and instead use \emph{graphs}.
  8454. %
  8455. At the level of x86 assembly, this is straightforward because we can
  8456. label the code for each branch and insert jumps in all the places that
  8457. need to execute the branch. In this way, jump instructions are edges
  8458. in the graph and the basic blocks are the nodes.
  8459. %
  8460. Likewise, our language \LangCIf{} provides the ability to label a
  8461. sequence of statements and to jump to a label via \code{goto}.
  8462. As a preview of what \code{explicate\_control} will do,
  8463. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8464. \code{explicate\_control} on this example. Note how the condition of
  8465. every \code{if} is a comparison operation and that we have not
  8466. duplicated any code but instead have used labels and \code{goto} to
  8467. enable sharing of code.
  8468. \begin{figure}[tbp]
  8469. \begin{tcolorbox}[colback=white]
  8470. {\if\edition\racketEd
  8471. \begin{tabular}{lll}
  8472. \begin{minipage}{0.4\textwidth}
  8473. % cond_test_41.rkt
  8474. \begin{lstlisting}
  8475. (let ([x (read)])
  8476. (let ([y (read)])
  8477. (if (if (< x 1)
  8478. (eq? x 0)
  8479. (eq? x 2))
  8480. (+ y 2)
  8481. (+ y 10))))
  8482. \end{lstlisting}
  8483. \end{minipage}
  8484. &
  8485. $\Rightarrow$
  8486. &
  8487. \begin{minipage}{0.55\textwidth}
  8488. \begin{lstlisting}
  8489. start:
  8490. x = (read);
  8491. y = (read);
  8492. if (< x 1)
  8493. goto block_4;
  8494. else
  8495. goto block_5;
  8496. block_4:
  8497. if (eq? x 0)
  8498. goto block_2;
  8499. else
  8500. goto block_3;
  8501. block_5:
  8502. if (eq? x 2)
  8503. goto block_2;
  8504. else
  8505. goto block_3;
  8506. block_2:
  8507. return (+ y 2);
  8508. block_3:
  8509. return (+ y 10);
  8510. \end{lstlisting}
  8511. \end{minipage}
  8512. \end{tabular}
  8513. \fi}
  8514. {\if\edition\pythonEd\pythonColor
  8515. \begin{tabular}{lll}
  8516. \begin{minipage}{0.4\textwidth}
  8517. % tests/if/if_lt_eq.py
  8518. \begin{lstlisting}
  8519. x = input_int()
  8520. y = input_int()
  8521. print(y + 2 \
  8522. if (x == 0 \
  8523. if x < 1 \
  8524. else x == 2) \
  8525. else y + 10)
  8526. \end{lstlisting}
  8527. \end{minipage}
  8528. &
  8529. $\Rightarrow\qquad$
  8530. &
  8531. \begin{minipage}{0.55\textwidth}
  8532. \begin{lstlisting}
  8533. start:
  8534. x = input_int()
  8535. y = input_int()
  8536. if x < 1:
  8537. goto block_6
  8538. else:
  8539. goto block_7
  8540. block_6:
  8541. if x == 0:
  8542. goto block_4
  8543. else:
  8544. goto block_5
  8545. block_7:
  8546. if x == 2:
  8547. goto block_4
  8548. else:
  8549. goto block_5
  8550. block_4:
  8551. tmp.82 = (y + 2)
  8552. goto block_3
  8553. block_5:
  8554. tmp.82 = (y + 10)
  8555. goto block_3
  8556. block_3:
  8557. print(tmp.82)
  8558. return 0
  8559. \end{lstlisting}
  8560. \end{minipage}
  8561. \end{tabular}
  8562. \fi}
  8563. \end{tcolorbox}
  8564. \caption{Translation from \LangIfANF{} to \LangCIf{}
  8565. via the \code{explicate\_control}.}
  8566. \label{fig:explicate-control-s1-38}
  8567. \end{figure}
  8568. {\if\edition\racketEd
  8569. %
  8570. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8571. \code{explicate\_control} for \LangVarANF{} using two recursive
  8572. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8573. former function translates expressions in tail position, whereas the
  8574. latter function translates expressions on the right-hand side of a
  8575. \key{let}. With the addition of \key{if} expression to \LangIfANF{} we
  8576. have a new kind of position to deal with: the predicate position of
  8577. the \key{if}. We need another function, \code{explicate\_pred}, that
  8578. decides how to compile an \key{if} by analyzing its condition. So,
  8579. \code{explicate\_pred} takes an \LangIfANF{} expression and two
  8580. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8581. and outputs a tail. In the following paragraphs we discuss specific
  8582. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8583. \code{explicate\_pred} functions.
  8584. %
  8585. \fi}
  8586. %
  8587. {\if\edition\pythonEd\pythonColor
  8588. %
  8589. We recommend implementing \code{explicate\_control} using the
  8590. following four auxiliary functions.
  8591. \begin{description}
  8592. \item[\code{explicate\_effect}] generates code for expressions as
  8593. statements, so their result is ignored and only their side effects
  8594. matter.
  8595. \item[\code{explicate\_assign}] generates code for expressions
  8596. on the right-hand side of an assignment.
  8597. \item[\code{explicate\_pred}] generates code for an \code{if}
  8598. expression or statement by analyzing the condition expression.
  8599. \item[\code{explicate\_stmt}] generates code for statements.
  8600. \end{description}
  8601. These four functions should build the dictionary of basic blocks. The
  8602. following auxiliary function \code{create\_block} is used to create a
  8603. new basic block from a list of statements. If the list just contains a
  8604. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8605. \code{create\_block} creates a new basic block and returns a
  8606. \code{goto} to its label.
  8607. \begin{center}
  8608. \begin{minipage}{\textwidth}
  8609. \begin{lstlisting}
  8610. def create_block(stmts, basic_blocks):
  8611. match stmts:
  8612. case [Goto(l)]:
  8613. return stmts
  8614. case _:
  8615. label = label_name(generate_name('block'))
  8616. basic_blocks[label] = stmts
  8617. return [Goto(label)]
  8618. \end{lstlisting}
  8619. \end{minipage}
  8620. \end{center}
  8621. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8622. \code{explicate\_control} pass.
  8623. The \code{explicate\_effect} function has three parameters: (1) the
  8624. expression to be compiled; (2) the already-compiled code for this
  8625. expression's \emph{continuation}, that is, the list of statements that
  8626. should execute after this expression; and (3) the dictionary of
  8627. generated basic blocks. The \code{explicate\_effect} function returns
  8628. a list of \LangCIf{} statements and it may add to the dictionary of
  8629. basic blocks.
  8630. %
  8631. Let's consider a few of the cases for the expression to be compiled.
  8632. If the expression to be compiled is a constant, then it can be
  8633. discarded because it has no side effects. If it's a \CREAD{}, then it
  8634. has a side effect and should be preserved. So the expression should be
  8635. translated into a statement using the \code{Expr} AST class. If the
  8636. expression to be compiled is an \code{if} expression, we translate the
  8637. two branches using \code{explicate\_effect} and then translate the
  8638. condition expression using \code{explicate\_pred}, which generates
  8639. code for the entire \code{if}.
  8640. The \code{explicate\_assign} function has four parameters: (1) the
  8641. right-hand side of the assignment, (2) the left-hand side of the
  8642. assignment (the variable), (3) the continuation, and (4) the dictionary
  8643. of basic blocks. The \code{explicate\_assign} function returns a list
  8644. of \LangCIf{} statements, and it may add to the dictionary of basic
  8645. blocks.
  8646. When the right-hand side is an \code{if} expression, there is some
  8647. work to do. In particular, the two branches should be translated using
  8648. \code{explicate\_assign}, and the condition expression should be
  8649. translated using \code{explicate\_pred}. Otherwise we can simply
  8650. generate an assignment statement, with the given left- and right-hand
  8651. sides, concatenated with its continuation.
  8652. \begin{figure}[tbp]
  8653. \begin{tcolorbox}[colback=white]
  8654. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8655. def explicate_effect(e, cont, basic_blocks):
  8656. match e:
  8657. case IfExp(test, body, orelse):
  8658. ...
  8659. case Call(func, args):
  8660. ...
  8661. case Begin(body, result):
  8662. ...
  8663. case _:
  8664. ...
  8665. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8666. match rhs:
  8667. case IfExp(test, body, orelse):
  8668. ...
  8669. case Begin(body, result):
  8670. ...
  8671. case _:
  8672. return [Assign([lhs], rhs)] + cont
  8673. def explicate_pred(cnd, thn, els, basic_blocks):
  8674. match cnd:
  8675. case Compare(left, [op], [right]):
  8676. goto_thn = create_block(thn, basic_blocks)
  8677. goto_els = create_block(els, basic_blocks)
  8678. return [If(cnd, goto_thn, goto_els)]
  8679. case Constant(True):
  8680. return thn;
  8681. case Constant(False):
  8682. return els;
  8683. case UnaryOp(Not(), operand):
  8684. ...
  8685. case IfExp(test, body, orelse):
  8686. ...
  8687. case Begin(body, result):
  8688. ...
  8689. case _:
  8690. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8691. create_block(els, basic_blocks),
  8692. create_block(thn, basic_blocks))]
  8693. def explicate_stmt(s, cont, basic_blocks):
  8694. match s:
  8695. case Assign([lhs], rhs):
  8696. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8697. case Expr(value):
  8698. return explicate_effect(value, cont, basic_blocks)
  8699. case If(test, body, orelse):
  8700. ...
  8701. def explicate_control(p):
  8702. match p:
  8703. case Module(body):
  8704. new_body = [Return(Constant(0))]
  8705. basic_blocks = {}
  8706. for s in reversed(body):
  8707. new_body = explicate_stmt(s, new_body, basic_blocks)
  8708. basic_blocks[label_name('start')] = new_body
  8709. return CProgram(basic_blocks)
  8710. \end{lstlisting}
  8711. \end{tcolorbox}
  8712. \caption{Skeleton for the \code{explicate\_control} pass.}
  8713. \label{fig:explicate-control-Lif}
  8714. \end{figure}
  8715. \fi}
  8716. {\if\edition\racketEd
  8717. \subsection{Explicate Tail and Assign}
  8718. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8719. additional cases for Boolean constants and \key{if}. The cases for
  8720. \code{if} should recursively compile the two branches using either
  8721. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8722. cases should then invoke \code{explicate\_pred} on the condition
  8723. expression, passing in the generated code for the two branches. For
  8724. example, consider the following program with an \code{if} in tail
  8725. position.
  8726. % cond_test_6.rkt
  8727. \begin{lstlisting}
  8728. (let ([x (read)])
  8729. (if (eq? x 0) 42 777))
  8730. \end{lstlisting}
  8731. The two branches are recursively compiled to return statements. We
  8732. then delegate to \code{explicate\_pred}, passing the condition
  8733. \code{(eq? x 0)} and the two return statements. We return to this
  8734. example shortly when we discuss \code{explicate\_pred}.
  8735. Next let us consider a program with an \code{if} on the right-hand
  8736. side of a \code{let}.
  8737. \begin{lstlisting}
  8738. (let ([y (read)])
  8739. (let ([x (if (eq? y 0) 40 777)])
  8740. (+ x 2)))
  8741. \end{lstlisting}
  8742. Note that the body of the inner \code{let} will have already been
  8743. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8744. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8745. to recursively process both branches of the \code{if}, and we do not
  8746. want to duplicate code, so we generate the following block using an
  8747. auxiliary function named \code{create\_block}, discussed in the next
  8748. section.
  8749. \begin{lstlisting}
  8750. block_6:
  8751. return (+ x 2)
  8752. \end{lstlisting}
  8753. We then use \code{goto block\_6;} as the \code{cont} argument for
  8754. compiling the branches. So the two branches compile to
  8755. \begin{center}
  8756. \begin{minipage}{0.2\textwidth}
  8757. \begin{lstlisting}
  8758. x = 40;
  8759. goto block_6;
  8760. \end{lstlisting}
  8761. \end{minipage}
  8762. \hspace{0.5in} and \hspace{0.5in}
  8763. \begin{minipage}{0.2\textwidth}
  8764. \begin{lstlisting}
  8765. x = 777;
  8766. goto block_6;
  8767. \end{lstlisting}
  8768. \end{minipage}
  8769. \end{center}
  8770. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8771. \code{(eq? y 0)} and the previously presented code for the branches.
  8772. \subsection{Create Block}
  8773. We recommend implementing the \code{create\_block} auxiliary function
  8774. as follows, using a global variable \code{basic-blocks} to store a
  8775. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8776. that \code{create\_block} generates a new label and then associates
  8777. the given \code{tail} with the new label in the \code{basic-blocks}
  8778. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8779. new label. However, if the given \code{tail} is already a \code{Goto},
  8780. then there is no need to generate a new label and entry in
  8781. \code{basic-blocks}; we can simply return that \code{Goto}.
  8782. %
  8783. \begin{lstlisting}
  8784. (define (create_block tail)
  8785. (match tail
  8786. [(Goto label) (Goto label)]
  8787. [else
  8788. (let ([label (gensym 'block)])
  8789. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8790. (Goto label))]))
  8791. \end{lstlisting}
  8792. \fi}
  8793. {\if\edition\racketEd
  8794. \subsection{Explicate Predicate}
  8795. The skeleton for the \code{explicate\_pred} function is given in
  8796. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8797. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8798. the code generated by explicate for the \emph{then} branch; and (3)
  8799. \code{els}, the code generated by explicate for the \emph{else}
  8800. branch. The \code{explicate\_pred} function should match on
  8801. \code{cnd} with a case for every kind of expression that can have type
  8802. \BOOLTY{}.
  8803. \begin{figure}[tbp]
  8804. \begin{tcolorbox}[colback=white]
  8805. \begin{lstlisting}
  8806. (define (explicate_pred cnd thn els)
  8807. (match cnd
  8808. [(Var x) ___]
  8809. [(Let x rhs body) ___]
  8810. [(Prim 'not (list e)) ___]
  8811. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8812. (IfStmt (Prim op es) (create_block thn)
  8813. (create_block els))]
  8814. [(Bool b) (if b thn els)]
  8815. [(If cnd^ thn^ els^) ___]
  8816. [else (error "explicate_pred unhandled case" cnd)]))
  8817. \end{lstlisting}
  8818. \end{tcolorbox}
  8819. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8820. \label{fig:explicate-pred}
  8821. \end{figure}
  8822. \fi}
  8823. %
  8824. {\if\edition\pythonEd\pythonColor
  8825. The \code{explicate\_pred} function has four parameters: (1) the
  8826. condition expression, (2) the generated statements for the \emph{then}
  8827. branch, (3) the generated statements for the \emph{else} branch, and
  8828. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8829. function returns a list of statements, and it adds to the dictionary
  8830. of basic blocks.
  8831. \fi}
  8832. Consider the case for comparison operators. We translate the
  8833. comparison to an \code{if} statement whose branches are \code{goto}
  8834. statements created by applying \code{create\_block} to the \code{thn}
  8835. and \code{els} parameters. Let us illustrate this translation by
  8836. returning to the program with an \code{if} expression in tail
  8837. position, shown next. We invoke \code{explicate\_pred} on its
  8838. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8839. %
  8840. {\if\edition\racketEd
  8841. \begin{lstlisting}
  8842. (let ([x (read)])
  8843. (if (eq? x 0) 42 777))
  8844. \end{lstlisting}
  8845. \fi}
  8846. %
  8847. {\if\edition\pythonEd\pythonColor
  8848. \begin{lstlisting}
  8849. x = input_int()
  8850. 42 if x == 0 else 777
  8851. \end{lstlisting}
  8852. \fi}
  8853. %
  8854. \noindent The two branches \code{42} and \code{777} were already
  8855. compiled to \code{return} statements, from which we now create the
  8856. following blocks:
  8857. %
  8858. \begin{center}
  8859. \begin{minipage}{\textwidth}
  8860. \begin{lstlisting}
  8861. block_1:
  8862. return 42;
  8863. block_2:
  8864. return 777;
  8865. \end{lstlisting}
  8866. \end{minipage}
  8867. \end{center}
  8868. %
  8869. After that, \code{explicate\_pred} compiles the comparison
  8870. \racket{\code{(eq? x 0)}}
  8871. \python{\code{x == 0}}
  8872. to the following \code{if} statement:
  8873. %
  8874. {\if\edition\racketEd
  8875. \begin{center}
  8876. \begin{minipage}{\textwidth}
  8877. \begin{lstlisting}
  8878. if (eq? x 0)
  8879. goto block_1;
  8880. else
  8881. goto block_2;
  8882. \end{lstlisting}
  8883. \end{minipage}
  8884. \end{center}
  8885. \fi}
  8886. {\if\edition\pythonEd\pythonColor
  8887. \begin{center}
  8888. \begin{minipage}{\textwidth}
  8889. \begin{lstlisting}
  8890. if x == 0:
  8891. goto block_1;
  8892. else
  8893. goto block_2;
  8894. \end{lstlisting}
  8895. \end{minipage}
  8896. \end{center}
  8897. \fi}
  8898. Next consider the case for Boolean constants. We perform a kind of
  8899. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8900. either the \code{thn} or \code{els} parameter, depending on whether the
  8901. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8902. following program:
  8903. {\if\edition\racketEd
  8904. \begin{lstlisting}
  8905. (if #t 42 777)
  8906. \end{lstlisting}
  8907. \fi}
  8908. {\if\edition\pythonEd\pythonColor
  8909. \begin{lstlisting}
  8910. 42 if True else 777
  8911. \end{lstlisting}
  8912. \fi}
  8913. %
  8914. \noindent Again, the two branches \code{42} and \code{777} were
  8915. compiled to \code{return} statements, so \code{explicate\_pred}
  8916. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8917. code for the \emph{then} branch.
  8918. \begin{lstlisting}
  8919. return 42;
  8920. \end{lstlisting}
  8921. This case demonstrates that we sometimes discard the \code{thn} or
  8922. \code{els} blocks that are input to \code{explicate\_pred}.
  8923. The case for \key{if} expressions in \code{explicate\_pred} is
  8924. particularly illuminating because it deals with the challenges
  8925. discussed previously regarding nested \key{if} expressions
  8926. (figure~\ref{fig:explicate-control-s1-38}). The
  8927. \racket{\lstinline{thn^}}\python{\code{body}} and
  8928. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8929. \key{if} inherit their context from the current one, that is,
  8930. predicate context. So, you should recursively apply
  8931. \code{explicate\_pred} to the
  8932. \racket{\lstinline{thn^}}\python{\code{body}} and
  8933. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8934. those recursive calls, pass \code{thn} and \code{els} as the extra
  8935. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8936. inside each recursive call. As discussed previously, to avoid
  8937. duplicating code, we need to add them to the dictionary of basic
  8938. blocks so that we can instead refer to them by name and execute them
  8939. with a \key{goto}.
  8940. {\if\edition\pythonEd\pythonColor
  8941. %
  8942. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8943. three parameters: (1) the statement to be compiled, (2) the code for its
  8944. continuation, and (3) the dictionary of basic blocks. The
  8945. \code{explicate\_stmt} returns a list of statements, and it may add to
  8946. the dictionary of basic blocks. The cases for assignment and an
  8947. expression-statement are given in full in the skeleton code: they
  8948. simply dispatch to \code{explicate\_assign} and
  8949. \code{explicate\_effect}, respectively. The case for \code{if}
  8950. statements is not given; it is similar to the case for \code{if}
  8951. expressions.
  8952. The \code{explicate\_control} function itself is given in
  8953. figure~\ref{fig:explicate-control-Lif}. It applies
  8954. \code{explicate\_stmt} to each statement in the program, from back to
  8955. front. Thus, the result so far, stored in \code{new\_body}, can be
  8956. used as the continuation parameter in the next call to
  8957. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8958. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8959. the dictionary of basic blocks, labeling it the ``start'' block.
  8960. %
  8961. \fi}
  8962. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8963. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8964. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8965. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8966. %% results from the two recursive calls. We complete the case for
  8967. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8968. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8969. %% the result $B_5$.
  8970. %% \[
  8971. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8972. %% \quad\Rightarrow\quad
  8973. %% B_5
  8974. %% \]
  8975. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8976. %% inherit the current context, so they are in tail position. Thus, the
  8977. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8978. %% \code{explicate\_tail}.
  8979. %% %
  8980. %% We need to pass $B_0$ as the accumulator argument for both of these
  8981. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8982. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8983. %% to the control-flow graph and obtain a promised goto $G_0$.
  8984. %% %
  8985. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8986. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8987. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8988. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8989. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8990. %% \[
  8991. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8992. %% \]
  8993. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8994. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8995. %% should not be confused with the labels for the blocks that appear in
  8996. %% the generated code. We initially construct unlabeled blocks; we only
  8997. %% attach labels to blocks when we add them to the control-flow graph, as
  8998. %% we see in the next case.
  8999. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  9000. %% function. The context of the \key{if} is an assignment to some
  9001. %% variable $x$ and then the control continues to some promised block
  9002. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  9003. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  9004. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  9005. %% branches of the \key{if} inherit the current context, so they are in
  9006. %% assignment positions. Let $B_2$ be the result of applying
  9007. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  9008. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  9009. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  9010. %% the result of applying \code{explicate\_pred} to the predicate
  9011. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  9012. %% translates to the promise $B_4$.
  9013. %% \[
  9014. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  9015. %% \]
  9016. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  9017. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  9018. \code{remove\_complex\_operands} pass and then the
  9019. \code{explicate\_control} pass on the example program. We walk through
  9020. the output program.
  9021. %
  9022. Following the order of evaluation in the output of
  9023. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  9024. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  9025. in the predicate of the inner \key{if}. In the output of
  9026. \code{explicate\_control}, in the
  9027. block labeled \code{start}, two assignment statements are followed by an
  9028. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  9029. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  9030. The blocks associated with those labels contain the
  9031. translations of the code
  9032. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9033. and
  9034. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  9035. respectively. In particular, we start
  9036. \racket{\code{block\_4}}\python{\code{block\_6}}
  9037. with the comparison
  9038. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9039. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  9040. or \racket{\code{block\_3}}\python{\code{block\_5}},
  9041. which correspond to the two branches of the outer \key{if}, that is,
  9042. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  9043. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  9044. %
  9045. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  9046. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  9047. %
  9048. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  9049. {\if\edition\racketEd
  9050. \subsection{Interactions between Explicate and Shrink}
  9051. The way in which the \code{shrink} pass transforms logical operations
  9052. such as \code{and} and \code{or} can impact the quality of code
  9053. generated by \code{explicate\_control}. For example, consider the
  9054. following program:
  9055. % cond_test_21.rkt, and_eq_input.py
  9056. \begin{lstlisting}
  9057. (if (and (eq? (read) 0) (eq? (read) 1))
  9058. 0
  9059. 42)
  9060. \end{lstlisting}
  9061. The \code{and} operation should transform into something that the
  9062. \code{explicate\_pred} function can analyze and descend through to
  9063. reach the underlying \code{eq?} conditions. Ideally, for this program
  9064. your \code{explicate\_control} pass should generate code similar to
  9065. the following:
  9066. \begin{center}
  9067. \begin{minipage}{\textwidth}
  9068. \begin{lstlisting}
  9069. start:
  9070. tmp1 = (read);
  9071. if (eq? tmp1 0) goto block40;
  9072. else goto block39;
  9073. block40:
  9074. tmp2 = (read);
  9075. if (eq? tmp2 1) goto block38;
  9076. else goto block39;
  9077. block38:
  9078. return 0;
  9079. block39:
  9080. return 42;
  9081. \end{lstlisting}
  9082. \end{minipage}
  9083. \end{center}
  9084. \fi}
  9085. \begin{exercise}\normalfont\normalsize
  9086. \racket{
  9087. Implement the pass \code{explicate\_control} by adding the cases for
  9088. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9089. \code{explicate\_assign} functions. Implement the auxiliary function
  9090. \code{explicate\_pred} for predicate contexts.}
  9091. \python{Implement \code{explicate\_control} pass with its
  9092. four auxiliary functions.}
  9093. %
  9094. Create test cases that exercise all the new cases in the code for
  9095. this pass.
  9096. %
  9097. {\if\edition\racketEd
  9098. Add the following entry to the list of \code{passes} in
  9099. \code{run-tests.rkt}:
  9100. \begin{lstlisting}
  9101. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9102. \end{lstlisting}
  9103. and then run \code{run-tests.rkt} to test your compiler.
  9104. \fi}
  9105. \end{exercise}
  9106. \section{Select Instructions}
  9107. \label{sec:select-Lif}
  9108. \index{subject}{select instructions}
  9109. The \code{select\_instructions} pass translates \LangCIf{} to
  9110. \LangXIfVar{}.
  9111. %
  9112. \racket{Recall that we implement this pass using three auxiliary
  9113. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9114. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9115. %
  9116. \racket{For $\Atm$, we have new cases for the Booleans.}
  9117. %
  9118. \python{We begin with the Boolean constants.}
  9119. As previously discussed, we encode them as integers.
  9120. \[
  9121. \TRUE{} \quad\Rightarrow\quad \key{1}
  9122. \qquad\qquad
  9123. \FALSE{} \quad\Rightarrow\quad \key{0}
  9124. \]
  9125. For translating statements, we discuss some of the cases. The
  9126. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9127. discussed at the beginning of this section. Given an assignment, if
  9128. the left-hand-side variable is the same as the argument of \code{not},
  9129. then just the \code{xorq} instruction suffices.
  9130. \[
  9131. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9132. \quad\Rightarrow\quad
  9133. \key{xorq}~\key{\$}1\key{,}~\Var
  9134. \]
  9135. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9136. semantics of x86. In the following translation, let $\Arg$ be the
  9137. result of translating $\Atm$ to x86.
  9138. \[
  9139. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9140. \quad\Rightarrow\quad
  9141. \begin{array}{l}
  9142. \key{movq}~\Arg\key{,}~\Var\\
  9143. \key{xorq}~\key{\$}1\key{,}~\Var
  9144. \end{array}
  9145. \]
  9146. Next consider the cases for equality comparisons. Translating this
  9147. operation to x86 is slightly involved due to the unusual nature of the
  9148. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9149. We recommend translating an assignment with an equality on the
  9150. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9151. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9152. \begin{tabular}{lll}
  9153. \begin{minipage}{0.4\textwidth}
  9154. $\CASSIGN{\Var}{ \CEQ{\Atm_1}{\Atm_2} }$
  9155. \end{minipage}
  9156. &
  9157. $\Rightarrow$
  9158. &
  9159. \begin{minipage}{0.4\textwidth}
  9160. \begin{lstlisting}
  9161. cmpq |$\Arg_2$|, |$\Arg_1$|
  9162. sete %al
  9163. movzbq %al, |$\Var$|
  9164. \end{lstlisting}
  9165. \end{minipage}
  9166. \end{tabular} \\
  9167. The translations for the other comparison operators are similar to
  9168. this but use different condition codes for the \code{set} instruction.
  9169. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9170. \key{goto} and \key{if} statements. Both are straightforward to
  9171. translate to x86.}
  9172. %
  9173. A \key{goto} statement becomes a jump instruction.
  9174. \[
  9175. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9176. \]
  9177. %
  9178. An \key{if} statement becomes a compare instruction followed by a
  9179. conditional jump (for the \emph{then} branch), and the fall-through is to
  9180. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9181. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9182. \begin{tabular}{lll}
  9183. \begin{minipage}{0.4\textwidth}
  9184. \begin{lstlisting}
  9185. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9186. goto |$\ell_1$||$\racket{\key{;}}$|
  9187. else|$\python{\key{:}}$|
  9188. goto |$\ell_2$||$\racket{\key{;}}$|
  9189. \end{lstlisting}
  9190. \end{minipage}
  9191. &
  9192. $\Rightarrow$
  9193. &
  9194. \begin{minipage}{0.4\textwidth}
  9195. \begin{lstlisting}
  9196. cmpq |$\Arg_2$|, |$\Arg_1$|
  9197. je |$\ell_1$|
  9198. jmp |$\ell_2$|
  9199. \end{lstlisting}
  9200. \end{minipage}
  9201. \end{tabular} \\
  9202. Again, the translations for the other comparison operators are similar to this
  9203. but use different condition codes for the conditional jump instruction.
  9204. \python{Regarding the \key{return} statement, we recommend treating it
  9205. as an assignment to the \key{rax} register followed by a jump to the
  9206. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9207. \begin{exercise}\normalfont\normalsize
  9208. Expand your \code{select\_instructions} pass to handle the new
  9209. features of the \LangCIf{} language.
  9210. %
  9211. {\if\edition\racketEd
  9212. Add the following entry to the list of \code{passes} in
  9213. \code{run-tests.rkt}
  9214. \begin{lstlisting}
  9215. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9216. \end{lstlisting}
  9217. \fi}
  9218. %
  9219. Run the script to test your compiler on all the test programs.
  9220. \end{exercise}
  9221. \section{Register Allocation}
  9222. \label{sec:register-allocation-Lif}
  9223. \index{subject}{register allocation}
  9224. The changes required for compiling \LangIf{} affect liveness analysis,
  9225. building the interference graph, and assigning homes, but the graph
  9226. coloring algorithm itself does not change.
  9227. \subsection{Liveness Analysis}
  9228. \label{sec:liveness-analysis-Lif}
  9229. \index{subject}{liveness analysis}
  9230. Recall that for \LangVar{} we implemented liveness analysis for a
  9231. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9232. the addition of \key{if} expressions to \LangIf{},
  9233. \code{explicate\_control} produces many basic blocks.
  9234. %% We recommend that you create a new auxiliary function named
  9235. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9236. %% control-flow graph.
  9237. The first question is, in what order should we process the basic blocks?
  9238. Recall that to perform liveness analysis on a basic block we need to
  9239. know the live-after set for the last instruction in the block. If a
  9240. basic block has no successors (i.e., contains no jumps to other
  9241. blocks), then it has an empty live-after set and we can immediately
  9242. apply liveness analysis to it. If a basic block has some successors,
  9243. then we need to complete liveness analysis on those blocks
  9244. first. These ordering constraints are the reverse of a
  9245. \emph{topological order}\index{subject}{topological order} on a graph
  9246. representation of the program. In particular, the \emph{control flow
  9247. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9248. of a program has a node for each basic block and an edge for each jump
  9249. from one block to another. It is straightforward to generate a CFG
  9250. from the dictionary of basic blocks. One then transposes the CFG and
  9251. applies the topological sort algorithm.
  9252. %
  9253. %
  9254. \racket{We recommend using the \code{tsort} and \code{transpose}
  9255. functions of the Racket \code{graph} package to accomplish this.}
  9256. %
  9257. \python{We provide implementations of \code{topological\_sort} and
  9258. \code{transpose} in the file \code{graph.py} of the support code.}
  9259. %
  9260. As an aside, a topological ordering is only guaranteed to exist if the
  9261. graph does not contain any cycles. This is the case for the
  9262. control-flow graphs that we generate from \LangIf{} programs.
  9263. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9264. and learn how to handle cycles in the control-flow graph.
  9265. \racket{You need to construct a directed graph to represent the
  9266. control-flow graph. Do not use the \code{directed-graph} of the
  9267. \code{graph} package because that allows at most one edge
  9268. between each pair of vertices, whereas a control-flow graph may have
  9269. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9270. file in the support code implements a graph representation that
  9271. allows multiple edges between a pair of vertices.}
  9272. {\if\edition\racketEd
  9273. The next question is how to analyze jump instructions. Recall that in
  9274. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9275. \code{label->live} that maps each label to the set of live locations
  9276. at the beginning of its block. We use \code{label->live} to determine
  9277. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9278. that we have many basic blocks, \code{label->live} needs to be updated
  9279. as we process the blocks. In particular, after performing liveness
  9280. analysis on a block, we take the live-before set of its first
  9281. instruction and associate that with the block's label in the
  9282. \code{label->live} alist.
  9283. \fi}
  9284. %
  9285. {\if\edition\pythonEd\pythonColor
  9286. %
  9287. The next question is how to analyze jump instructions. The locations
  9288. that are live before a \code{jmp} should be the locations in
  9289. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9290. maintaining a dictionary named \code{live\_before\_block} that maps each
  9291. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9292. block. After performing liveness analysis on each block, we take the
  9293. live-before set of its first instruction and associate that with the
  9294. block's label in the \code{live\_before\_block} dictionary.
  9295. %
  9296. \fi}
  9297. In \LangXIfVar{} we also have the conditional jump
  9298. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9299. this instruction is particularly interesting because during
  9300. compilation, we do not know which way a conditional jump will go. Thus
  9301. we do not know whether to use the live-before set for the block
  9302. associated with the $\itm{label}$ or the live-before set for the
  9303. following instruction. So we use both, by taking the union of the
  9304. live-before sets from the following instruction and from the mapping
  9305. for $\itm{label}$ in
  9306. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9307. The auxiliary functions for computing the variables in an
  9308. instruction's argument and for computing the variables read-from ($R$)
  9309. or written-to ($W$) by an instruction need to be updated to handle the
  9310. new kinds of arguments and instructions in \LangXIfVar{}.
  9311. \begin{exercise}\normalfont\normalsize
  9312. {\if\edition\racketEd
  9313. %
  9314. Update the \code{uncover\_live} pass to apply liveness analysis to
  9315. every basic block in the program.
  9316. %
  9317. Add the following entry to the list of \code{passes} in the
  9318. \code{run-tests.rkt} script:
  9319. \begin{lstlisting}
  9320. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9321. \end{lstlisting}
  9322. \fi}
  9323. {\if\edition\pythonEd\pythonColor
  9324. %
  9325. Update the \code{uncover\_live} function to perform liveness analysis,
  9326. in reverse topological order, on all the basic blocks in the
  9327. program.
  9328. %
  9329. \fi}
  9330. % Check that the live-after sets that you generate for
  9331. % example X matches the following... -Jeremy
  9332. \end{exercise}
  9333. \subsection{Build the Interference Graph}
  9334. \label{sec:build-interference-Lif}
  9335. Many of the new instructions in \LangXIfVar{} can be handled in the
  9336. same way as the instructions in \LangXVar{}.
  9337. % Thus, if your code was
  9338. % already quite general, it will not need to be changed to handle the
  9339. % new instructions. If your code is not general enough, we recommend that
  9340. % you change your code to be more general. For example, you can factor
  9341. % out the computing of the the read and write sets for each kind of
  9342. % instruction into auxiliary functions.
  9343. %
  9344. Some instructions, such as the \key{movzbq} instruction, require special care,
  9345. similar to the \key{movq} instruction. Refer to rule number 1 in
  9346. section~\ref{sec:build-interference}.
  9347. \begin{exercise}\normalfont\normalsize
  9348. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9349. {\if\edition\racketEd
  9350. Add the following entries to the list of \code{passes} in the
  9351. \code{run-tests.rkt} script:
  9352. \begin{lstlisting}
  9353. (list "build_interference" build_interference interp-pseudo-x86-1)
  9354. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9355. \end{lstlisting}
  9356. \fi}
  9357. % Check that the interference graph that you generate for
  9358. % example X matches the following graph G... -Jeremy
  9359. \end{exercise}
  9360. \section{Patch Instructions}
  9361. The new instructions \key{cmpq} and \key{movzbq} have some special
  9362. restrictions that need to be handled in the \code{patch\_instructions}
  9363. pass.
  9364. %
  9365. The second argument of the \key{cmpq} instruction must not be an
  9366. immediate value (such as an integer). So, if you are comparing two
  9367. immediates, we recommend inserting a \key{movq} instruction to put the
  9368. second argument in \key{rax}. On the other hand, if you implemented
  9369. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9370. update it for \LangIf{} and then this situation would not arise.
  9371. %
  9372. As usual, \key{cmpq} may have at most one memory reference.
  9373. %
  9374. The second argument of the \key{movzbq} must be a register.
  9375. \begin{exercise}\normalfont\normalsize
  9376. %
  9377. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9378. %
  9379. {\if\edition\racketEd
  9380. Add the following entry to the list of \code{passes} in
  9381. \code{run-tests.rkt}, and then run this script to test your compiler.
  9382. \begin{lstlisting}
  9383. (list "patch_instructions" patch_instructions interp-x86-1)
  9384. \end{lstlisting}
  9385. \fi}
  9386. \end{exercise}
  9387. {\if\edition\pythonEd\pythonColor
  9388. \section{Generate Prelude and Conclusion}
  9389. \label{sec:prelude-conclusion-cond}
  9390. The generation of the \code{main} function with its prelude and
  9391. conclusion must change to accommodate how the program now consists of
  9392. one or more basic blocks. After the prelude in \code{main}, jump to
  9393. the \code{start} block. Place the conclusion in a basic block labeled
  9394. with \code{conclusion}.
  9395. \fi}
  9396. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9397. \LangIf{} translated to x86, showing the results of
  9398. \code{explicate\_control}, \code{select\_instructions}, and the final
  9399. x86 assembly.
  9400. \begin{figure}[tbp]
  9401. \begin{tcolorbox}[colback=white]
  9402. {\if\edition\racketEd
  9403. \begin{tabular}{lll}
  9404. \begin{minipage}{0.4\textwidth}
  9405. % cond_test_20.rkt, eq_input.py
  9406. \begin{lstlisting}
  9407. (if (eq? (read) 1) 42 0)
  9408. \end{lstlisting}
  9409. $\Downarrow$
  9410. \begin{lstlisting}
  9411. start:
  9412. tmp7951 = (read);
  9413. if (eq? tmp7951 1)
  9414. goto block7952;
  9415. else
  9416. goto block7953;
  9417. block7952:
  9418. return 42;
  9419. block7953:
  9420. return 0;
  9421. \end{lstlisting}
  9422. $\Downarrow$
  9423. \begin{lstlisting}
  9424. start:
  9425. callq read_int
  9426. movq %rax, tmp7951
  9427. cmpq $1, tmp7951
  9428. je block7952
  9429. jmp block7953
  9430. block7953:
  9431. movq $0, %rax
  9432. jmp conclusion
  9433. block7952:
  9434. movq $42, %rax
  9435. jmp conclusion
  9436. \end{lstlisting}
  9437. \end{minipage}
  9438. &
  9439. $\Rightarrow\qquad$
  9440. \begin{minipage}{0.4\textwidth}
  9441. \begin{lstlisting}
  9442. start:
  9443. callq read_int
  9444. movq %rax, %rcx
  9445. cmpq $1, %rcx
  9446. je block7952
  9447. jmp block7953
  9448. block7953:
  9449. movq $0, %rax
  9450. jmp conclusion
  9451. block7952:
  9452. movq $42, %rax
  9453. jmp conclusion
  9454. .globl main
  9455. main:
  9456. pushq %rbp
  9457. movq %rsp, %rbp
  9458. pushq %r13
  9459. pushq %r12
  9460. pushq %rbx
  9461. pushq %r14
  9462. subq $0, %rsp
  9463. jmp start
  9464. conclusion:
  9465. addq $0, %rsp
  9466. popq %r14
  9467. popq %rbx
  9468. popq %r12
  9469. popq %r13
  9470. popq %rbp
  9471. retq
  9472. \end{lstlisting}
  9473. \end{minipage}
  9474. \end{tabular}
  9475. \fi}
  9476. {\if\edition\pythonEd\pythonColor
  9477. \begin{tabular}{lll}
  9478. \begin{minipage}{0.4\textwidth}
  9479. % cond_test_20.rkt, eq_input.py
  9480. \begin{lstlisting}
  9481. print(42 if input_int() == 1 else 0)
  9482. \end{lstlisting}
  9483. $\Downarrow$
  9484. \begin{lstlisting}
  9485. start:
  9486. tmp_0 = input_int()
  9487. if tmp_0 == 1:
  9488. goto block_3
  9489. else:
  9490. goto block_4
  9491. block_3:
  9492. tmp_1 = 42
  9493. goto block_2
  9494. block_4:
  9495. tmp_1 = 0
  9496. goto block_2
  9497. block_2:
  9498. print(tmp_1)
  9499. return 0
  9500. \end{lstlisting}
  9501. $\Downarrow$
  9502. \begin{lstlisting}
  9503. start:
  9504. callq read_int
  9505. movq %rax, tmp_0
  9506. cmpq 1, tmp_0
  9507. je block_3
  9508. jmp block_4
  9509. block_3:
  9510. movq 42, tmp_1
  9511. jmp block_2
  9512. block_4:
  9513. movq 0, tmp_1
  9514. jmp block_2
  9515. block_2:
  9516. movq tmp_1, %rdi
  9517. callq print_int
  9518. movq 0, %rax
  9519. jmp conclusion
  9520. \end{lstlisting}
  9521. \end{minipage}
  9522. &
  9523. $\Rightarrow\qquad$
  9524. \begin{minipage}{0.4\textwidth}
  9525. \begin{lstlisting}
  9526. .globl main
  9527. main:
  9528. pushq %rbp
  9529. movq %rsp, %rbp
  9530. subq $0, %rsp
  9531. jmp start
  9532. start:
  9533. callq read_int
  9534. movq %rax, %rcx
  9535. cmpq $1, %rcx
  9536. je block_3
  9537. jmp block_4
  9538. block_3:
  9539. movq $42, %rcx
  9540. jmp block_2
  9541. block_4:
  9542. movq $0, %rcx
  9543. jmp block_2
  9544. block_2:
  9545. movq %rcx, %rdi
  9546. callq print_int
  9547. movq $0, %rax
  9548. jmp conclusion
  9549. conclusion:
  9550. addq $0, %rsp
  9551. popq %rbp
  9552. retq
  9553. \end{lstlisting}
  9554. \end{minipage}
  9555. \end{tabular}
  9556. \fi}
  9557. \end{tcolorbox}
  9558. \caption{Example compilation of an \key{if} expression to x86, showing
  9559. the results of \code{explicate\_control},
  9560. \code{select\_instructions}, and the final x86 assembly code. }
  9561. \label{fig:if-example-x86}
  9562. \end{figure}
  9563. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9564. compilation of \LangIf{}.
  9565. \begin{figure}[htbp]
  9566. \begin{tcolorbox}[colback=white]
  9567. {\if\edition\racketEd
  9568. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9569. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9570. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9571. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9572. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9573. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9574. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9575. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9576. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9577. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9578. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9579. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9580. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9581. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9582. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9583. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9584. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9585. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9586. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9587. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9588. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9589. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9590. \end{tikzpicture}
  9591. \fi}
  9592. {\if\edition\pythonEd\pythonColor
  9593. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9594. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9595. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9596. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9597. \node (C-1) at (0,0) {\large \LangCIf{}};
  9598. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9599. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9600. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9601. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9602. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9603. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9604. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9605. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9606. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9607. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9608. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9609. \end{tikzpicture}
  9610. \fi}
  9611. \end{tcolorbox}
  9612. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9613. \label{fig:Lif-passes}
  9614. \end{figure}
  9615. \section{Challenge: Optimize Blocks and Remove Jumps}
  9616. \label{sec:opt-jumps}
  9617. We discuss two challenges that involve optimizing the control-flow of
  9618. the program.
  9619. \subsection{Optimize Blocks}
  9620. The algorithm for \code{explicate\_control} that we discussed in
  9621. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9622. blocks. It creates a block whenever a continuation \emph{might} get
  9623. used more than once (for example, whenever the \code{cont} parameter
  9624. is passed into two or more recursive calls). However, some
  9625. continuation arguments may not be used at all. Consider the case for
  9626. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9627. the \code{els} continuation.
  9628. %
  9629. {\if\edition\racketEd
  9630. The following example program falls into this
  9631. case, and it creates two unused blocks.
  9632. \begin{center}
  9633. \begin{tabular}{lll}
  9634. \begin{minipage}{0.4\textwidth}
  9635. % cond_test_82.rkt
  9636. \begin{lstlisting}
  9637. (let ([y (if #t
  9638. (read)
  9639. (if (eq? (read) 0)
  9640. 777
  9641. (let ([x (read)])
  9642. (+ 1 x))))])
  9643. (+ y 2))
  9644. \end{lstlisting}
  9645. \end{minipage}
  9646. &
  9647. $\Rightarrow$
  9648. &
  9649. \begin{minipage}{0.4\textwidth}
  9650. \begin{lstlisting}
  9651. start:
  9652. y = (read);
  9653. goto block_5;
  9654. block_5:
  9655. return (+ y 2);
  9656. block_6:
  9657. y = 777;
  9658. goto block_5;
  9659. block_7:
  9660. x = (read);
  9661. y = (+ 1 x2);
  9662. goto block_5;
  9663. \end{lstlisting}
  9664. \end{minipage}
  9665. \end{tabular}
  9666. \end{center}
  9667. \fi}
  9668. {\if\edition\pythonEd
  9669. The following example program falls into this
  9670. case, and it creates the unused \code{block\_9}.
  9671. \begin{center}
  9672. \begin{minipage}{0.4\textwidth}
  9673. % if/if_true.py
  9674. \begin{lstlisting}
  9675. if True:
  9676. print(0)
  9677. else:
  9678. x = 1 if False else 2
  9679. print(x)
  9680. \end{lstlisting}
  9681. \end{minipage}
  9682. $\Rightarrow\qquad\qquad$
  9683. \begin{minipage}{0.4\textwidth}
  9684. \begin{lstlisting}
  9685. start:
  9686. print(0)
  9687. goto block_8
  9688. block_9:
  9689. print(x)
  9690. goto block_8
  9691. block_8:
  9692. return 0
  9693. \end{lstlisting}
  9694. \end{minipage}
  9695. \end{center}
  9696. \fi}
  9697. The question is, how can we decide whether to create a basic block?
  9698. \emph{Lazy evaluation}\index{subject}{lazy
  9699. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9700. delaying the creation of a basic block until the point in time at which
  9701. we know that it will be used.
  9702. %
  9703. {\if\edition\racketEd
  9704. %
  9705. Racket provides support for
  9706. lazy evaluation with the
  9707. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9708. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9709. \index{subject}{delay} creates a
  9710. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9711. expressions is postponed. When \key{(force}
  9712. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9713. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9714. result of $e_n$ is cached in the promise and returned. If \code{force}
  9715. is applied again to the same promise, then the cached result is
  9716. returned. If \code{force} is applied to an argument that is not a
  9717. promise, \code{force} simply returns the argument.
  9718. %
  9719. \fi}
  9720. %
  9721. {\if\edition\pythonEd\pythonColor
  9722. %
  9723. Although Python does not provide direct support for lazy evaluation,
  9724. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9725. by wrapping it inside a function with no parameters. We \emph{force}
  9726. its evaluation by calling the function. However, we might need to
  9727. force multiple times, so we store the result of calling the
  9728. function instead of recomputing it each time. The following
  9729. \code{Promise} class handles this memoization process.
  9730. \begin{minipage}{0.8\textwidth}
  9731. \begin{lstlisting}
  9732. @dataclass
  9733. class Promise:
  9734. fun : typing.Any
  9735. cache : list[stmt] = None
  9736. def force(self):
  9737. if self.cache is None:
  9738. self.cache = self.fun(); return self.cache
  9739. else:
  9740. return self.cache
  9741. \end{lstlisting}
  9742. \end{minipage}
  9743. \noindent However, in some cases of \code{explicate\_pred}, we return
  9744. a list of statements, and in other cases we return a function that
  9745. computes a list of statements. To uniformly deal with both regular
  9746. data and promises, we define the following \code{force} function that
  9747. checks whether its input is delayed (i.e., whether it is a
  9748. \code{Promise}) and then either (1) forces the promise or (2) returns
  9749. the input.
  9750. %
  9751. \begin{lstlisting}
  9752. def force(promise):
  9753. if isinstance(promise, Promise):
  9754. return promise.force()
  9755. else:
  9756. return promise
  9757. \end{lstlisting}
  9758. %
  9759. \fi}
  9760. We use promises for the input and output of the functions
  9761. \code{explicate\_pred}, \code{explicate\_assign},
  9762. %
  9763. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9764. %
  9765. So, instead of taking and returning \racket{$\Tail$
  9766. expressions}\python{lists of statements}, they take and return
  9767. promises. Furthermore, when we come to a situation in which a
  9768. continuation might be used more than once, as in the case for
  9769. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9770. that creates a basic block for each continuation (if there is not
  9771. already one) and then returns a \code{goto} statement to that basic
  9772. block. When we come to a situation in which we have a promise but need an
  9773. actual piece of code, for example, to create a larger piece of code with a
  9774. constructor such as \code{Seq}, then insert a call to \code{force}.
  9775. %
  9776. {\if\edition\racketEd
  9777. %
  9778. Also, we must modify the \code{create\_block} function to begin with
  9779. \code{delay} to create a promise. When forced, this promise forces the
  9780. original promise. If that returns a \code{Goto} (because the block was
  9781. already added to \code{basic-blocks}), then we return the
  9782. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9783. return a \code{Goto} to the new label.
  9784. \begin{center}
  9785. \begin{minipage}{\textwidth}
  9786. \begin{lstlisting}
  9787. (define (create_block tail)
  9788. (delay
  9789. (define t (force tail))
  9790. (match t
  9791. [(Goto label) (Goto label)]
  9792. [else
  9793. (let ([label (gensym 'block)])
  9794. (set! basic-blocks (cons (cons label t) basic-blocks))
  9795. (Goto label))])))
  9796. \end{lstlisting}
  9797. \end{minipage}
  9798. \end{center}
  9799. \fi}
  9800. {\if\edition\pythonEd\pythonColor
  9801. %
  9802. Here is the new version of the \code{create\_block} auxiliary function
  9803. that delays the creation of the new basic block.\\
  9804. \begin{minipage}{\textwidth}
  9805. \begin{lstlisting}
  9806. def create_block(promise, basic_blocks):
  9807. def delay():
  9808. stmts = force(promise)
  9809. match stmts:
  9810. case [Goto(l)]:
  9811. return [Goto(l)]
  9812. case _:
  9813. label = label_name(generate_name('block'))
  9814. basic_blocks[label] = stmts
  9815. return [Goto(label)]
  9816. return Promise(delay)
  9817. \end{lstlisting}
  9818. \end{minipage}
  9819. \fi}
  9820. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9821. improved \code{explicate\_control} on this example.
  9822. \racket{As you can see, the number of basic blocks has been reduced
  9823. from four blocks to two blocks.}%
  9824. \python{As you can see, the number of basic blocks has been reduced
  9825. from three blocks to two blocks.}
  9826. \begin{figure}[tbp]
  9827. \begin{tcolorbox}[colback=white]
  9828. {\if\edition\racketEd
  9829. \begin{tabular}{lll}
  9830. \begin{minipage}{0.45\textwidth}
  9831. % cond_test_82.rkt
  9832. \begin{lstlisting}
  9833. (let ([y (if #t
  9834. (read)
  9835. (if (eq? (read) 0)
  9836. 777
  9837. (let ([x (read)])
  9838. (+ 1 x))))])
  9839. (+ y 2))
  9840. \end{lstlisting}
  9841. \end{minipage}
  9842. &
  9843. $\quad\Rightarrow\quad$
  9844. &
  9845. \begin{minipage}{0.4\textwidth}
  9846. \begin{lstlisting}
  9847. start:
  9848. y = (read);
  9849. goto block_5;
  9850. block_5:
  9851. return (+ y 2);
  9852. \end{lstlisting}
  9853. \end{minipage}
  9854. \end{tabular}
  9855. \fi}
  9856. {\if\edition\pythonEd\pythonColor
  9857. \begin{tabular}{lll}
  9858. \begin{minipage}{0.4\textwidth}
  9859. % if/if_true.py
  9860. \begin{lstlisting}
  9861. if True:
  9862. print(0)
  9863. else:
  9864. x = 1 if False else 2
  9865. print(x)
  9866. \end{lstlisting}
  9867. \end{minipage}
  9868. &
  9869. $\Rightarrow$
  9870. &
  9871. \begin{minipage}{0.55\textwidth}
  9872. \begin{lstlisting}
  9873. start:
  9874. print(0)
  9875. goto block_4
  9876. block_4:
  9877. return 0
  9878. \end{lstlisting}
  9879. \end{minipage}
  9880. \end{tabular}
  9881. \fi}
  9882. \end{tcolorbox}
  9883. \caption{Translation from \LangIf{} to \LangCIf{}
  9884. via the improved \code{explicate\_control}.}
  9885. \label{fig:explicate-control-challenge}
  9886. \end{figure}
  9887. %% Recall that in the example output of \code{explicate\_control} in
  9888. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9889. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9890. %% block. The first goal of this challenge assignment is to remove those
  9891. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9892. %% \code{explicate\_control} on the left and shows the result of bypassing
  9893. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9894. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9895. %% \code{block55}. The optimized code on the right of
  9896. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9897. %% \code{then} branch jumping directly to \code{block55}. The story is
  9898. %% similar for the \code{else} branch, as well as for the two branches in
  9899. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9900. %% have been optimized in this way, there are no longer any jumps to
  9901. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9902. %% \begin{figure}[tbp]
  9903. %% \begin{tabular}{lll}
  9904. %% \begin{minipage}{0.4\textwidth}
  9905. %% \begin{lstlisting}
  9906. %% block62:
  9907. %% tmp54 = (read);
  9908. %% if (eq? tmp54 2) then
  9909. %% goto block59;
  9910. %% else
  9911. %% goto block60;
  9912. %% block61:
  9913. %% tmp53 = (read);
  9914. %% if (eq? tmp53 0) then
  9915. %% goto block57;
  9916. %% else
  9917. %% goto block58;
  9918. %% block60:
  9919. %% goto block56;
  9920. %% block59:
  9921. %% goto block55;
  9922. %% block58:
  9923. %% goto block56;
  9924. %% block57:
  9925. %% goto block55;
  9926. %% block56:
  9927. %% return (+ 700 77);
  9928. %% block55:
  9929. %% return (+ 10 32);
  9930. %% start:
  9931. %% tmp52 = (read);
  9932. %% if (eq? tmp52 1) then
  9933. %% goto block61;
  9934. %% else
  9935. %% goto block62;
  9936. %% \end{lstlisting}
  9937. %% \end{minipage}
  9938. %% &
  9939. %% $\Rightarrow$
  9940. %% &
  9941. %% \begin{minipage}{0.55\textwidth}
  9942. %% \begin{lstlisting}
  9943. %% block62:
  9944. %% tmp54 = (read);
  9945. %% if (eq? tmp54 2) then
  9946. %% goto block55;
  9947. %% else
  9948. %% goto block56;
  9949. %% block61:
  9950. %% tmp53 = (read);
  9951. %% if (eq? tmp53 0) then
  9952. %% goto block55;
  9953. %% else
  9954. %% goto block56;
  9955. %% block56:
  9956. %% return (+ 700 77);
  9957. %% block55:
  9958. %% return (+ 10 32);
  9959. %% start:
  9960. %% tmp52 = (read);
  9961. %% if (eq? tmp52 1) then
  9962. %% goto block61;
  9963. %% else
  9964. %% goto block62;
  9965. %% \end{lstlisting}
  9966. %% \end{minipage}
  9967. %% \end{tabular}
  9968. %% \caption{Optimize jumps by removing trivial blocks.}
  9969. %% \label{fig:optimize-jumps}
  9970. %% \end{figure}
  9971. %% The name of this pass is \code{optimize-jumps}. We recommend
  9972. %% implementing this pass in two phases. The first phrase builds a hash
  9973. %% table that maps labels to possibly improved labels. The second phase
  9974. %% changes the target of each \code{goto} to use the improved label. If
  9975. %% the label is for a trivial block, then the hash table should map the
  9976. %% label to the first non-trivial block that can be reached from this
  9977. %% label by jumping through trivial blocks. If the label is for a
  9978. %% non-trivial block, then the hash table should map the label to itself;
  9979. %% we do not want to change jumps to non-trivial blocks.
  9980. %% The first phase can be accomplished by constructing an empty hash
  9981. %% table, call it \code{short-cut}, and then iterating over the control
  9982. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9983. %% then update the hash table, mapping the block's source to the target
  9984. %% of the \code{goto}. Also, the hash table may already have mapped some
  9985. %% labels to the block's source, to you must iterate through the hash
  9986. %% table and update all of those so that they instead map to the target
  9987. %% of the \code{goto}.
  9988. %% For the second phase, we recommend iterating through the $\Tail$ of
  9989. %% each block in the program, updating the target of every \code{goto}
  9990. %% according to the mapping in \code{short-cut}.
  9991. \begin{exercise}\normalfont\normalsize
  9992. Implement the improvements to the \code{explicate\_control} pass.
  9993. Check that it removes trivial blocks in a few example programs. Then
  9994. check that your compiler still passes all your tests.
  9995. \end{exercise}
  9996. \subsection{Remove Jumps}
  9997. There is an opportunity for removing jumps that is apparent in the
  9998. example of figure~\ref{fig:explicate-control-challenge}. The
  9999. \code{start} block ends with a jump to
  10000. \racket{\code{block\_5}}\python{\code{block\_4}}, and there are no
  10001. other jumps to \racket{\code{block\_5}}\python{\code{block\_4}} in
  10002. the rest of the program. In this situation we can avoid the runtime
  10003. overhead of this jump by merging
  10004. \racket{\code{block\_5}}\python{\code{block\_4}} into the preceding
  10005. block, which in this case is the \code{start} block.
  10006. Figure~\ref{fig:remove-jumps} shows the output of
  10007. \code{allocate\_registers} on the left and the result of this
  10008. optimization on the right.
  10009. \begin{figure}[tbp]
  10010. \begin{tcolorbox}[colback=white]
  10011. {\if\edition\racketEd
  10012. \begin{tabular}{lll}
  10013. \begin{minipage}{0.5\textwidth}
  10014. % cond_test_82.rkt
  10015. \begin{lstlisting}
  10016. start:
  10017. callq read_int
  10018. movq %rax, %rcx
  10019. jmp block_5
  10020. block_5:
  10021. movq %rcx, %rax
  10022. addq $2, %rax
  10023. jmp conclusion
  10024. \end{lstlisting}
  10025. \end{minipage}
  10026. &
  10027. $\Rightarrow\qquad$
  10028. \begin{minipage}{0.4\textwidth}
  10029. \begin{lstlisting}
  10030. start:
  10031. callq read_int
  10032. movq %rax, %rcx
  10033. movq %rcx, %rax
  10034. addq $2, %rax
  10035. jmp conclusion
  10036. \end{lstlisting}
  10037. \end{minipage}
  10038. \end{tabular}
  10039. \fi}
  10040. {\if\edition\pythonEd\pythonColor
  10041. \begin{tabular}{lll}
  10042. \begin{minipage}{0.5\textwidth}
  10043. % cond_test_20.rkt
  10044. \begin{lstlisting}
  10045. start:
  10046. callq read_int
  10047. movq %rax, tmp_0
  10048. cmpq 1, tmp_0
  10049. je block_3
  10050. jmp block_4
  10051. block_3:
  10052. movq 42, tmp_1
  10053. jmp block_2
  10054. block_4:
  10055. movq 0, tmp_1
  10056. jmp block_2
  10057. block_2:
  10058. movq tmp_1, %rdi
  10059. callq print_int
  10060. movq 0, %rax
  10061. jmp conclusion
  10062. \end{lstlisting}
  10063. \end{minipage}
  10064. &
  10065. $\Rightarrow\qquad$
  10066. \begin{minipage}{0.4\textwidth}
  10067. \begin{lstlisting}
  10068. start:
  10069. callq read_int
  10070. movq %rax, tmp_0
  10071. cmpq 1, tmp_0
  10072. je block_3
  10073. movq 0, tmp_1
  10074. jmp block_2
  10075. block_3:
  10076. movq 42, tmp_1
  10077. jmp block_2
  10078. block_2:
  10079. movq tmp_1, %rdi
  10080. callq print_int
  10081. movq 0, %rax
  10082. jmp conclusion
  10083. \end{lstlisting}
  10084. \end{minipage}
  10085. \end{tabular}
  10086. \fi}
  10087. \end{tcolorbox}
  10088. \caption{Merging basic blocks by removing unnecessary jumps.}
  10089. \label{fig:remove-jumps}
  10090. \end{figure}
  10091. \begin{exercise}\normalfont\normalsize
  10092. %
  10093. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10094. into their preceding basic block, when there is only one preceding
  10095. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10096. %
  10097. {\if\edition\racketEd
  10098. In the \code{run-tests.rkt} script, add the following entry to the
  10099. list of \code{passes} between \code{allocate\_registers}
  10100. and \code{patch\_instructions}:
  10101. \begin{lstlisting}
  10102. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10103. \end{lstlisting}
  10104. \fi}
  10105. %
  10106. Run the script to test your compiler.
  10107. %
  10108. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10109. blocks on several test programs.
  10110. \end{exercise}
  10111. \section{Further Reading}
  10112. \label{sec:cond-further-reading}
  10113. The algorithm for \code{explicate\_control} is based on the
  10114. \code{expose-basic-blocks} pass in the course notes of
  10115. \citet{Dybvig:2010aa}.
  10116. %
  10117. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10118. \citet{Appel:2003fk}, and is related to translations into continuation
  10119. passing
  10120. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10121. %
  10122. The treatment of conditionals in the \code{explicate\_control} pass is
  10123. similar to short-cut Boolean
  10124. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10125. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10126. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10127. \chapter{Loops and Dataflow Analysis}
  10128. \label{ch:Lwhile}
  10129. \setcounter{footnote}{0}
  10130. % TODO: define R'_8
  10131. % TODO: multi-graph
  10132. {\if\edition\racketEd
  10133. %
  10134. In this chapter we study two features that are the hallmarks of
  10135. imperative programming languages: loops and assignments to local
  10136. variables. The following example demonstrates these new features by
  10137. computing the sum of the first five positive integers:
  10138. % similar to loop_test_1.rkt
  10139. \begin{lstlisting}
  10140. (let ([sum 0])
  10141. (let ([i 5])
  10142. (begin
  10143. (while (> i 0)
  10144. (begin
  10145. (set! sum (+ sum i))
  10146. (set! i (- i 1))))
  10147. sum)))
  10148. \end{lstlisting}
  10149. The \code{while} loop consists of a condition and a
  10150. body.\footnote{The \code{while} loop is not a built-in
  10151. feature of the Racket language, but Racket includes many looping
  10152. constructs and it is straightforward to define \code{while} as a
  10153. macro.} The body is evaluated repeatedly so long as the condition
  10154. remains true.
  10155. %
  10156. The \code{set!} consists of a variable and a right-hand side
  10157. expression. The \code{set!} updates value of the variable to the
  10158. value of the right-hand side.
  10159. %
  10160. The primary purpose of both the \code{while} loop and \code{set!} is
  10161. to cause side effects, so they do not give a meaningful result
  10162. value. Instead, their result is the \code{\#<void>} value. The
  10163. expression \code{(void)} is an explicit way to create the
  10164. \code{\#<void>} value, and it has type \code{Void}. The
  10165. \code{\#<void>} value can be passed around just like other values
  10166. inside an \LangLoop{} program, and it can be compared for equality with
  10167. another \code{\#<void>} value. However, there are no other operations
  10168. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10169. Racket defines the \code{void?} predicate that returns \code{\#t}
  10170. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10171. %
  10172. \footnote{Racket's \code{Void} type corresponds to what is often
  10173. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10174. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10175. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10176. %
  10177. With the addition of side effect-producing features such as
  10178. \code{while} loop and \code{set!}, it is helpful to include a language
  10179. feature for sequencing side effects: the \code{begin} expression. It
  10180. consists of one or more subexpressions that are evaluated
  10181. left to right.
  10182. %
  10183. \fi}
  10184. {\if\edition\pythonEd\pythonColor
  10185. %
  10186. In this chapter we study loops, one of the hallmarks of imperative
  10187. programming languages. The following example demonstrates the
  10188. \code{while} loop by computing the sum of the first five positive
  10189. integers.
  10190. \begin{lstlisting}
  10191. sum = 0
  10192. i = 5
  10193. while i > 0:
  10194. sum = sum + i
  10195. i = i - 1
  10196. print(sum)
  10197. \end{lstlisting}
  10198. The \code{while} loop consists of a condition and a body (a sequence
  10199. of statements). The body is evaluated repeatedly so long as the
  10200. condition remains true.
  10201. %
  10202. \fi}
  10203. \section{The \LangLoop{} Language}
  10204. \newcommand{\LwhileGrammarRacket}{
  10205. \begin{array}{lcl}
  10206. \Type &::=& \key{Void}\\
  10207. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10208. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10209. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10210. \end{array}
  10211. }
  10212. \newcommand{\LwhileASTRacket}{
  10213. \begin{array}{lcl}
  10214. \Type &::=& \key{Void}\\
  10215. \Exp &::=& \SETBANG{\Var}{\Exp}
  10216. \MID \BEGIN{\Exp^{*}}{\Exp}
  10217. \MID \WHILE{\Exp}{\Exp}
  10218. \MID \VOID{}
  10219. \end{array}
  10220. }
  10221. \newcommand{\LwhileGrammarPython}{
  10222. \begin{array}{rcl}
  10223. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10224. \end{array}
  10225. }
  10226. \newcommand{\LwhileASTPython}{
  10227. \begin{array}{lcl}
  10228. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10229. \end{array}
  10230. }
  10231. \begin{figure}[tp]
  10232. \centering
  10233. \begin{tcolorbox}[colback=white]
  10234. \small
  10235. {\if\edition\racketEd
  10236. \[
  10237. \begin{array}{l}
  10238. \gray{\LintGrammarRacket{}} \\ \hline
  10239. \gray{\LvarGrammarRacket{}} \\ \hline
  10240. \gray{\LifGrammarRacket{}} \\ \hline
  10241. \LwhileGrammarRacket \\
  10242. \begin{array}{lcl}
  10243. \LangLoopM{} &::=& \Exp
  10244. \end{array}
  10245. \end{array}
  10246. \]
  10247. \fi}
  10248. {\if\edition\pythonEd\pythonColor
  10249. \[
  10250. \begin{array}{l}
  10251. \gray{\LintGrammarPython} \\ \hline
  10252. \gray{\LvarGrammarPython} \\ \hline
  10253. \gray{\LifGrammarPython} \\ \hline
  10254. \LwhileGrammarPython \\
  10255. \begin{array}{rcl}
  10256. \LangLoopM{} &::=& \Stmt^{*}
  10257. \end{array}
  10258. \end{array}
  10259. \]
  10260. \fi}
  10261. \end{tcolorbox}
  10262. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10263. \label{fig:Lwhile-concrete-syntax}
  10264. \index{subject}{Lwhile@\LangLoop{} concrete syntax}
  10265. \end{figure}
  10266. \begin{figure}[tp]
  10267. \centering
  10268. \begin{tcolorbox}[colback=white]
  10269. \small
  10270. {\if\edition\racketEd
  10271. \[
  10272. \begin{array}{l}
  10273. \gray{\LintOpAST} \\ \hline
  10274. \gray{\LvarASTRacket{}} \\ \hline
  10275. \gray{\LifASTRacket{}} \\ \hline
  10276. \LwhileASTRacket{} \\
  10277. \begin{array}{lcl}
  10278. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10279. \end{array}
  10280. \end{array}
  10281. \]
  10282. \fi}
  10283. {\if\edition\pythonEd\pythonColor
  10284. \[
  10285. \begin{array}{l}
  10286. \gray{\LintASTPython} \\ \hline
  10287. \gray{\LvarASTPython} \\ \hline
  10288. \gray{\LifASTPython} \\ \hline
  10289. \LwhileASTPython \\
  10290. \begin{array}{lcl}
  10291. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10292. \end{array}
  10293. \end{array}
  10294. \]
  10295. \fi}
  10296. \end{tcolorbox}
  10297. \python{
  10298. \index{subject}{While@\texttt{While}}
  10299. }
  10300. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10301. \label{fig:Lwhile-syntax}
  10302. \index{subject}{Lwhile@\LangLoop{} abstract syntax}
  10303. \end{figure}
  10304. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10305. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10306. shows the definition of its abstract syntax.
  10307. %
  10308. The definitional interpreter for \LangLoop{} is shown in
  10309. figure~\ref{fig:interp-Lwhile}.
  10310. %
  10311. {\if\edition\racketEd
  10312. %
  10313. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10314. and \code{Void}, and we make changes to the cases for \code{Var} and
  10315. \code{Let} regarding variables. To support assignment to variables and
  10316. to make their lifetimes indefinite (see the second example in
  10317. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10318. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10319. value.
  10320. %
  10321. Now we discuss the new cases. For \code{SetBang}, we find the
  10322. variable in the environment to obtain a boxed value, and then we change
  10323. it using \code{set-box!} to the result of evaluating the right-hand
  10324. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10325. %
  10326. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10327. if the result is true, (2) evaluate the body.
  10328. The result value of a \code{while} loop is also \code{\#<void>}.
  10329. %
  10330. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10331. subexpressions \itm{es} for their effects and then evaluates
  10332. and returns the result from \itm{body}.
  10333. %
  10334. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10335. %
  10336. \fi}
  10337. {\if\edition\pythonEd\pythonColor
  10338. %
  10339. We add a new case for \code{While} in the \code{interp\_stmts}
  10340. function, in which we repeatedly interpret the \code{body} so long as the
  10341. \code{test} expression remains true.
  10342. %
  10343. \fi}
  10344. \begin{figure}[tbp]
  10345. \begin{tcolorbox}[colback=white]
  10346. {\if\edition\racketEd
  10347. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10348. (define interp-Lwhile-class
  10349. (class interp-Lif-class
  10350. (super-new)
  10351. (define/override ((interp-exp env) e)
  10352. (define recur (interp-exp env))
  10353. (match e
  10354. [(Let x e body)
  10355. (define new-env (dict-set env x (box (recur e))))
  10356. ((interp-exp new-env) body)]
  10357. [(Var x) (unbox (dict-ref env x))]
  10358. [(SetBang x rhs)
  10359. (set-box! (dict-ref env x) (recur rhs))]
  10360. [(WhileLoop cnd body)
  10361. (define (loop)
  10362. (cond [(recur cnd) (recur body) (loop)]
  10363. [else (void)]))
  10364. (loop)]
  10365. [(Begin es body)
  10366. (for ([e es]) (recur e))
  10367. (recur body)]
  10368. [(Void) (void)]
  10369. [else ((super interp-exp env) e)]))
  10370. ))
  10371. (define (interp-Lwhile p)
  10372. (send (new interp-Lwhile-class) interp-program p))
  10373. \end{lstlisting}
  10374. \fi}
  10375. {\if\edition\pythonEd\pythonColor
  10376. \begin{lstlisting}
  10377. class InterpLwhile(InterpLif):
  10378. def interp_stmt(self, s, env, cont):
  10379. match s:
  10380. case While(test, body, []):
  10381. if self.interp_exp(test, env):
  10382. self.interp_stmts(body + [s] + cont, env)
  10383. else:
  10384. return self.interp_stmts(cont, env)
  10385. case _:
  10386. return super().interp_stmt(s, env, cont)
  10387. \end{lstlisting}
  10388. \fi}
  10389. \end{tcolorbox}
  10390. \caption{Interpreter for \LangLoop{}.}
  10391. \label{fig:interp-Lwhile}
  10392. \end{figure}
  10393. The definition of the type checker for \LangLoop{} is shown in
  10394. figure~\ref{fig:type-check-Lwhile}.
  10395. %
  10396. {\if\edition\racketEd
  10397. %
  10398. The type checking of the \code{SetBang} expression requires the type
  10399. of the variable and the right-hand side to agree. The result type is
  10400. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10401. and the result type is \code{Void}. For \code{Begin}, the result type
  10402. is the type of its last subexpression.
  10403. %
  10404. \fi}
  10405. %
  10406. {\if\edition\pythonEd\pythonColor
  10407. %
  10408. A \code{while} loop is well typed if the type of the \code{test}
  10409. expression is \code{bool} and the statements in the \code{body} are
  10410. well typed.
  10411. %
  10412. \fi}
  10413. \begin{figure}[tbp]
  10414. \begin{tcolorbox}[colback=white]
  10415. {\if\edition\racketEd
  10416. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10417. (define type-check-Lwhile-class
  10418. (class type-check-Lif-class
  10419. (super-new)
  10420. (inherit check-type-equal?)
  10421. (define/override (type-check-exp env)
  10422. (lambda (e)
  10423. (define recur (type-check-exp env))
  10424. (match e
  10425. [(SetBang x rhs)
  10426. (define-values (rhs^ rhsT) (recur rhs))
  10427. (define varT (dict-ref env x))
  10428. (check-type-equal? rhsT varT e)
  10429. (values (SetBang x rhs^) 'Void)]
  10430. [(WhileLoop cnd body)
  10431. (define-values (cnd^ Tc) (recur cnd))
  10432. (check-type-equal? Tc 'Boolean e)
  10433. (define-values (body^ Tbody) ((type-check-exp env) body))
  10434. (values (WhileLoop cnd^ body^) 'Void)]
  10435. [(Begin es body)
  10436. (define-values (es^ ts)
  10437. (for/lists (l1 l2) ([e es]) (recur e)))
  10438. (define-values (body^ Tbody) (recur body))
  10439. (values (Begin es^ body^) Tbody)]
  10440. [else ((super type-check-exp env) e)])))
  10441. ))
  10442. (define (type-check-Lwhile p)
  10443. (send (new type-check-Lwhile-class) type-check-program p))
  10444. \end{lstlisting}
  10445. \fi}
  10446. {\if\edition\pythonEd\pythonColor
  10447. \begin{lstlisting}
  10448. class TypeCheckLwhile(TypeCheckLif):
  10449. def type_check_stmts(self, ss, env):
  10450. if len(ss) == 0:
  10451. return
  10452. match ss[0]:
  10453. case While(test, body, []):
  10454. test_t = self.type_check_exp(test, env)
  10455. check_type_equal(bool, test_t, test)
  10456. body_t = self.type_check_stmts(body, env)
  10457. return self.type_check_stmts(ss[1:], env)
  10458. case _:
  10459. return super().type_check_stmts(ss, env)
  10460. \end{lstlisting}
  10461. \fi}
  10462. \end{tcolorbox}
  10463. \caption{Type checker for the \LangLoop{} language.}
  10464. \label{fig:type-check-Lwhile}
  10465. \end{figure}
  10466. {\if\edition\racketEd
  10467. %
  10468. At first glance, the translation of these language features to x86
  10469. seems straightforward because the \LangCIf{} intermediate language
  10470. already supports all the ingredients that we need: assignment,
  10471. \code{goto}, conditional branching, and sequencing. However,
  10472. complications arise, which we discuss in the next section. After
  10473. that we introduce the changes necessary to the existing passes.
  10474. %
  10475. \fi}
  10476. {\if\edition\pythonEd\pythonColor
  10477. %
  10478. At first glance, the translation of \code{while} loops to x86 seems
  10479. straightforward because the \LangCIf{} intermediate language already
  10480. supports \code{goto} and conditional branching. However, there are
  10481. complications that arise, which we discuss in the next section. After
  10482. that we introduce the changes necessary to the existing passes.
  10483. %
  10484. \fi}
  10485. \section{Cyclic Control Flow and Dataflow Analysis}
  10486. \label{sec:dataflow-analysis}
  10487. Up until this point, the programs generated in
  10488. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10489. \code{while} loop introduces a cycle. Does that matter?
  10490. %
  10491. Indeed, it does. Recall that for register allocation, the compiler
  10492. performs liveness analysis to determine which variables can share the
  10493. same register. To accomplish this, we analyzed the control-flow graph
  10494. in reverse topological order
  10495. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10496. well defined only for acyclic graphs.
  10497. Let us return to the example of computing the sum of the first five
  10498. positive integers. Here is the program after instruction
  10499. selection\index{subject}{instruction selection} but before register
  10500. allocation.
  10501. \begin{center}
  10502. {\if\edition\racketEd
  10503. \begin{minipage}{0.45\textwidth}
  10504. \begin{lstlisting}
  10505. (define (main) : Integer
  10506. mainstart:
  10507. movq $0, sum
  10508. movq $5, i
  10509. jmp block5
  10510. block5:
  10511. movq i, tmp3
  10512. cmpq tmp3, $0
  10513. jl block7
  10514. jmp block8
  10515. \end{lstlisting}
  10516. \end{minipage}
  10517. \begin{minipage}{0.45\textwidth}
  10518. \begin{lstlisting}
  10519. block7:
  10520. addq i, sum
  10521. movq $1, tmp4
  10522. negq tmp4
  10523. addq tmp4, i
  10524. jmp block5
  10525. block8:
  10526. movq $27, %rax
  10527. addq sum, %rax
  10528. jmp mainconclusion)
  10529. \end{lstlisting}
  10530. \end{minipage}
  10531. \fi}
  10532. {\if\edition\pythonEd\pythonColor
  10533. \begin{minipage}{0.45\textwidth}
  10534. \begin{lstlisting}
  10535. mainstart:
  10536. movq $0, sum
  10537. movq $5, i
  10538. jmp block5
  10539. block5:
  10540. cmpq $0, i
  10541. jg block7
  10542. jmp block8
  10543. \end{lstlisting}
  10544. \end{minipage}
  10545. \begin{minipage}{0.45\textwidth}
  10546. \begin{lstlisting}
  10547. block7:
  10548. addq i, sum
  10549. subq $1, i
  10550. jmp block5
  10551. block8:
  10552. movq sum, %rdi
  10553. callq print_int
  10554. movq $0, %rax
  10555. jmp mainconclusion
  10556. \end{lstlisting}
  10557. \end{minipage}
  10558. \fi}
  10559. \end{center}
  10560. Recall that liveness analysis works backward, starting at the end
  10561. of each function. For this example we could start with \code{block8}
  10562. because we know what is live at the beginning of the conclusion:
  10563. only \code{rax} and \code{rsp}. So the live-before set
  10564. for \code{block8} is \code{\{rsp,sum\}}.
  10565. %
  10566. Next we might try to analyze \code{block5} or \code{block7}, but
  10567. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10568. we are stuck.
  10569. The way out of this impasse is to realize that we can compute an
  10570. underapproximation of each live-before set by starting with empty
  10571. live-after sets. By \emph{underapproximation}, we mean that the set
  10572. contains only variables that are live for some execution of the
  10573. program, but the set may be missing some variables that are live.
  10574. Next, the underapproximations for each block can be improved by (1)
  10575. updating the live-after set for each block using the approximate
  10576. live-before sets from the other blocks, and (2) performing liveness
  10577. analysis again on each block. In fact, by iterating this process, the
  10578. underapproximations eventually become the correct solutions!
  10579. %
  10580. This approach of iteratively analyzing a control-flow graph is
  10581. applicable to many static analysis problems and goes by the name
  10582. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10583. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10584. Washington.
  10585. Let us apply this approach to the previously presented example. We use
  10586. the empty set for the initial live-before set for each block. Let
  10587. $m_0$ be the following mapping from label names to sets of locations
  10588. (variables and registers):
  10589. \begin{center}
  10590. \begin{lstlisting}
  10591. mainstart: {}, block5: {}, block7: {}, block8: {}
  10592. \end{lstlisting}
  10593. \end{center}
  10594. Using the above live-before approximations, we determine the
  10595. live-after for each block and then apply liveness analysis to each
  10596. block. This produces our next approximation $m_1$ of the live-before
  10597. sets.
  10598. \begin{center}
  10599. \begin{lstlisting}
  10600. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10601. \end{lstlisting}
  10602. \end{center}
  10603. For the second round, the live-after for \code{mainstart} is the
  10604. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10605. the liveness analysis for \code{mainstart} computes the empty set. The
  10606. live-after for \code{block5} is the union of the live-before sets for
  10607. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10608. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10609. sum\}}. The live-after for \code{block7} is the live-before for
  10610. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10611. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10612. Together these yield the following approximation $m_2$ of
  10613. the live-before sets:
  10614. \begin{center}
  10615. \begin{lstlisting}
  10616. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10617. \end{lstlisting}
  10618. \end{center}
  10619. In the preceding iteration, only \code{block5} changed, so we can
  10620. limit our attention to \code{mainstart} and \code{block7}, the two
  10621. blocks that jump to \code{block5}. As a result, the live-before sets
  10622. for \code{mainstart} and \code{block7} are updated to include
  10623. \code{rsp}, yielding the following approximation $m_3$:
  10624. \begin{center}
  10625. \begin{lstlisting}
  10626. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10627. \end{lstlisting}
  10628. \end{center}
  10629. Because \code{block7} changed, we analyze \code{block5} once more, but
  10630. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10631. our approximations have converged, so $m_3$ is the solution.
  10632. This iteration process is guaranteed to converge to a solution by the
  10633. Kleene fixed-point theorem, a general theorem about functions on
  10634. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10635. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10636. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10637. join operator
  10638. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10639. will be working with join semilattices.} When two elements are
  10640. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10641. as much information as $m_i$, so we can think of $m_j$ as a
  10642. better-than-or-equal-to approximation in relation to $m_i$. The
  10643. bottom element $\bot$ represents the complete lack of information,
  10644. that is, the worst approximation. The join operator takes two lattice
  10645. elements and combines their information; that is, it produces the
  10646. least upper bound of the two.\index{subject}{least upper bound}
  10647. A dataflow analysis typically involves two lattices: one lattice to
  10648. represent abstract states and another lattice that aggregates the
  10649. abstract states of all the blocks in the control-flow graph. For
  10650. liveness analysis, an abstract state is a set of locations. We form
  10651. the lattice $L$ by taking its elements to be sets of locations, the
  10652. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10653. set, and the join operator to be set union.
  10654. %
  10655. We form a second lattice $M$ by taking its elements to be mappings
  10656. from the block labels to sets of locations (elements of $L$). We
  10657. order the mappings point-wise, using the ordering of $L$. So, given any
  10658. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10659. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10660. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10661. to the empty set, $\bot_M(\ell) = \emptyset$.
  10662. We can think of one iteration of liveness analysis applied to the
  10663. whole program as being a function $f$ on the lattice $M$. It takes a
  10664. mapping as input and computes a new mapping.
  10665. \[
  10666. f(m_i) = m_{i+1}
  10667. \]
  10668. Next let us think for a moment about what a final solution $m_s$
  10669. should look like. If we perform liveness analysis using the solution
  10670. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10671. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10672. \[
  10673. f(m_s) = m_s
  10674. \]
  10675. Furthermore, the solution should include only locations that are
  10676. forced to be there by performing liveness analysis on the program, so
  10677. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10678. The Kleene fixed-point theorem states that if a function $f$ is
  10679. monotone (better inputs produce better outputs), then the least fixed
  10680. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10681. chain} that starts at $\bot$ and iterates $f$ as
  10682. follows:\index{subject}{Kleene fixed-point theorem}
  10683. \[
  10684. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10685. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10686. \]
  10687. When a lattice contains only finitely long ascending chains, then
  10688. every Kleene chain tops out at some fixed point after some number of
  10689. iterations of $f$.
  10690. \[
  10691. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10692. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10693. \]
  10694. The liveness analysis is indeed a monotone function and the lattice
  10695. $M$ has finitely long ascending chains because there are only a
  10696. finite number of variables and blocks in the program. Thus we are
  10697. guaranteed that iteratively applying liveness analysis to all blocks
  10698. in the program will eventually produce the least fixed point solution.
  10699. Next let us consider dataflow analysis in general and discuss the
  10700. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10701. %
  10702. The algorithm has four parameters: the control-flow graph \code{G}, a
  10703. function \code{transfer} that applies the analysis to one block, and the
  10704. \code{bottom} and \code{join} operators for the lattice of abstract
  10705. states. The \code{analyze\_dataflow} function is formulated as a
  10706. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10707. function come from the predecessor nodes in the control-flow
  10708. graph. However, liveness analysis is a \emph{backward} dataflow
  10709. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10710. function with the transpose of the control-flow graph.
  10711. The algorithm begins by creating the bottom mapping, represented by a
  10712. hash table. It then pushes all the nodes in the control-flow graph
  10713. onto the work list (a queue). The algorithm repeats the \code{while}
  10714. loop as long as there are items in the work list. In each iteration, a
  10715. node is popped from the work list and processed. The \code{input} for
  10716. the node is computed by taking the join of the abstract states of all
  10717. the predecessor nodes. The \code{transfer} function is then applied to
  10718. obtain the \code{output} abstract state. If the output differs from
  10719. the previous state for this block, the mapping for this block is
  10720. updated and its successor nodes are pushed onto the work list.
  10721. \begin{figure}[tb]
  10722. \begin{tcolorbox}[colback=white]
  10723. {\if\edition\racketEd
  10724. \begin{lstlisting}
  10725. (define (analyze_dataflow G transfer bottom join)
  10726. (define mapping (make-hash))
  10727. (for ([v (in-vertices G)])
  10728. (dict-set! mapping v bottom))
  10729. (define worklist (make-queue))
  10730. (for ([v (in-vertices G)])
  10731. (enqueue! worklist v))
  10732. (define trans-G (transpose G))
  10733. (while (not (queue-empty? worklist))
  10734. (define node (dequeue! worklist))
  10735. (define input (for/fold ([state bottom])
  10736. ([pred (in-neighbors trans-G node)])
  10737. (join state (dict-ref mapping pred))))
  10738. (define output (transfer node input))
  10739. (cond [(not (equal? output (dict-ref mapping node)))
  10740. (dict-set! mapping node output)
  10741. (for ([v (in-neighbors G node)])
  10742. (enqueue! worklist v))]))
  10743. mapping)
  10744. \end{lstlisting}
  10745. \fi}
  10746. {\if\edition\pythonEd\pythonColor
  10747. \begin{lstlisting}
  10748. def analyze_dataflow(G, transfer, bottom, join):
  10749. trans_G = transpose(G)
  10750. mapping = dict((v, bottom) for v in G.vertices())
  10751. worklist = deque(G.vertices)
  10752. while worklist:
  10753. node = worklist.pop()
  10754. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10755. input = reduce(join, inputs, bottom)
  10756. output = transfer(node, input)
  10757. if output != mapping[node]:
  10758. mapping[node] = output
  10759. worklist.extend(G.adjacent(node))
  10760. \end{lstlisting}
  10761. \fi}
  10762. \end{tcolorbox}
  10763. \caption{Generic work list algorithm for dataflow analysis.}
  10764. \label{fig:generic-dataflow}
  10765. \end{figure}
  10766. {\if\edition\racketEd
  10767. \section{Mutable Variables and Remove Complex Operands}
  10768. There is a subtle interaction between the
  10769. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10770. and the left-to-right order of evaluation of Racket. Consider the
  10771. following example:
  10772. \begin{lstlisting}
  10773. (let ([x 2])
  10774. (+ x (begin (set! x 40) x)))
  10775. \end{lstlisting}
  10776. The result of this program is \code{42} because the first read from
  10777. \code{x} produces \code{2} and the second produces \code{40}. However,
  10778. if we naively apply the \code{remove\_complex\_operands} pass to this
  10779. example we obtain the following program whose result is \code{80}!
  10780. \begin{lstlisting}
  10781. (let ([x 2])
  10782. (let ([tmp (begin (set! x 40) x)])
  10783. (+ x tmp)))
  10784. \end{lstlisting}
  10785. The problem is that with mutable variables, the ordering between
  10786. reads and writes is important, and the
  10787. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10788. before the first read of \code{x}.
  10789. We recommend solving this problem by giving special treatment to reads
  10790. from mutable variables, that is, variables that occur on the left-hand
  10791. side of a \code{set!}. We mark each read from a mutable variable with
  10792. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10793. that the read operation is effectful in that it can produce different
  10794. results at different points in time. Let's apply this idea to the
  10795. following variation that also involves a variable that is not mutated:
  10796. % loop_test_24.rkt
  10797. \begin{lstlisting}
  10798. (let ([x 2])
  10799. (let ([y 0])
  10800. (+ y (+ x (begin (set! x 40) x)))))
  10801. \end{lstlisting}
  10802. We first analyze this program to discover that variable \code{x}
  10803. is mutable but \code{y} is not. We then transform the program as
  10804. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10805. \begin{lstlisting}
  10806. (let ([x 2])
  10807. (let ([y 0])
  10808. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10809. \end{lstlisting}
  10810. Now that we have a clear distinction between reads from mutable and
  10811. immutable variables, we can apply the \code{remove\_complex\_operands}
  10812. pass, where reads from immutable variables are still classified as
  10813. atomic expressions but reads from mutable variables are classified as
  10814. complex. Thus, \code{remove\_complex\_operands} yields the following
  10815. program:\\
  10816. \begin{minipage}{\textwidth}
  10817. \begin{lstlisting}
  10818. (let ([x 2])
  10819. (let ([y 0])
  10820. (let ([t1 x])
  10821. (let ([t2 (begin (set! x 40) x)])
  10822. (let ([t3 (+ t1 t2)])
  10823. (+ y t3))))))
  10824. \end{lstlisting}
  10825. \end{minipage}
  10826. The temporary variable \code{t1} gets the value of \code{x} before the
  10827. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10828. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10829. do not generate a temporary variable for the occurrence of \code{y}
  10830. because it's an immutable variable. We want to avoid such unnecessary
  10831. extra temporaries because they would needlessly increase the number of
  10832. variables, making it more likely for some of them to be spilled. The
  10833. result of this program is \code{42}, the same as the result prior to
  10834. \code{remove\_complex\_operands}.
  10835. The approach that we've sketched requires only a small
  10836. modification to \code{remove\_complex\_operands} to handle
  10837. \code{get!}. However, it requires a new pass, called
  10838. \code{uncover-get!}, that we discuss in
  10839. section~\ref{sec:uncover-get-bang}.
  10840. As an aside, this problematic interaction between \code{set!} and the
  10841. pass \code{remove\_complex\_operands} is particular to Racket and not
  10842. its predecessor, the Scheme language. The key difference is that
  10843. Scheme does not specify an order of evaluation for the arguments of an
  10844. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10845. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10846. would be correct results for the example program. Interestingly,
  10847. Racket is implemented on top of the Chez Scheme
  10848. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10849. presented in this section (using extra \code{let} bindings to control
  10850. the order of evaluation) is used in the translation from Racket to
  10851. Scheme~\citep{Flatt:2019tb}.
  10852. \fi} % racket
  10853. Having discussed the complications that arise from adding support for
  10854. assignment and loops, we turn to discussing the individual compilation
  10855. passes.
  10856. {\if\edition\racketEd
  10857. \section{Uncover \texttt{get!}}
  10858. \label{sec:uncover-get-bang}
  10859. The goal of this pass is to mark uses of mutable variables so that
  10860. \code{remove\_complex\_operands} can treat them as complex expressions
  10861. and thereby preserve their ordering relative to the side effects in
  10862. other operands. So, the first step is to collect all the mutable
  10863. variables. We recommend creating an auxiliary function for this,
  10864. named \code{collect-set!}, that recursively traverses expressions,
  10865. returning the set of all variables that occur on the left-hand side of a
  10866. \code{set!}. Here's an excerpt of its implementation.
  10867. \begin{center}
  10868. \begin{minipage}{\textwidth}
  10869. \begin{lstlisting}
  10870. (define (collect-set! e)
  10871. (match e
  10872. [(Var x) (set)]
  10873. [(Int n) (set)]
  10874. [(Let x rhs body)
  10875. (set-union (collect-set! rhs) (collect-set! body))]
  10876. [(SetBang var rhs)
  10877. (set-union (set var) (collect-set! rhs))]
  10878. ...))
  10879. \end{lstlisting}
  10880. \end{minipage}
  10881. \end{center}
  10882. By placing this pass after \code{uniquify}, we need not worry about
  10883. variable shadowing, and our logic for \code{Let} can remain simple, as
  10884. in this excerpt.
  10885. The second step is to mark the occurrences of the mutable variables
  10886. with the new \code{GetBang} AST node (\code{get!} in concrete
  10887. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10888. function, which takes two parameters: the set of mutable variables
  10889. \code{set!-vars} and the expression \code{e} to be processed. The
  10890. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10891. mutable variable or leaves it alone if not.
  10892. \begin{center}
  10893. \begin{minipage}{\textwidth}
  10894. \begin{lstlisting}
  10895. (define ((uncover-get!-exp set!-vars) e)
  10896. (match e
  10897. [(Var x)
  10898. (if (set-member? set!-vars x)
  10899. (GetBang x)
  10900. (Var x))]
  10901. ...))
  10902. \end{lstlisting}
  10903. \end{minipage}
  10904. \end{center}
  10905. To wrap things up, define the \code{uncover-get!} function for
  10906. processing a whole program, using \code{collect-set!} to obtain the
  10907. set of mutable variables and then \code{uncover-get!-exp} to replace
  10908. their occurrences with \code{GetBang}.
  10909. \fi}
  10910. \section{Remove Complex Operands}
  10911. \label{sec:rco-loop}
  10912. {\if\edition\racketEd
  10913. %
  10914. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10915. \code{while} are all complex expressions. The subexpressions of
  10916. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10917. %
  10918. \fi}
  10919. {\if\edition\pythonEd\pythonColor
  10920. %
  10921. The change needed for this pass is to add a case for the \code{while}
  10922. statement. The condition of a loop is allowed to be a complex
  10923. expression, just like the condition of the \code{if} statement.
  10924. %
  10925. \fi}
  10926. %
  10927. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10928. \LangLoopANF{} of this pass.
  10929. \newcommand{\LwhileMonadASTRacket}{
  10930. \begin{array}{rcl}
  10931. \Atm &::=& \VOID{} \\
  10932. \Exp &::=& \GETBANG{\Var}
  10933. \MID \SETBANG{\Var}{\Exp}
  10934. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10935. &\MID& \WHILE{\Exp}{\Exp}
  10936. \end{array}
  10937. }
  10938. \newcommand{\LwhileMonadASTPython}{
  10939. \begin{array}{rcl}
  10940. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10941. \end{array}
  10942. }
  10943. \begin{figure}[tp]
  10944. \centering
  10945. \begin{tcolorbox}[colback=white]
  10946. \small
  10947. {\if\edition\racketEd
  10948. \[
  10949. \begin{array}{l}
  10950. \gray{\LvarMonadASTRacket} \\ \hline
  10951. \gray{\LifMonadASTRacket} \\ \hline
  10952. \LwhileMonadASTRacket \\
  10953. \begin{array}{rcl}
  10954. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10955. \end{array}
  10956. \end{array}
  10957. \]
  10958. \fi}
  10959. {\if\edition\pythonEd\pythonColor
  10960. \[
  10961. \begin{array}{l}
  10962. \gray{\LvarMonadASTPython} \\ \hline
  10963. \gray{\LifMonadASTPython} \\ \hline
  10964. \LwhileMonadASTPython \\
  10965. \begin{array}{rcl}
  10966. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10967. \end{array}
  10968. \end{array}
  10969. \]
  10970. \fi}
  10971. \end{tcolorbox}
  10972. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10973. \label{fig:Lwhile-anf-syntax}
  10974. \index{subject}{Lwhilemon@\LangLoopANF{} abstract syntax}
  10975. \end{figure}
  10976. {\if\edition\racketEd
  10977. %
  10978. As usual, when a complex expression appears in a grammar position that
  10979. needs to be atomic, such as the argument of a primitive operator, we
  10980. must introduce a temporary variable and bind it to the complex
  10981. expression. This approach applies, unchanged, to handle the new
  10982. language forms. For example, in the following code there are two
  10983. \code{begin} expressions appearing as arguments to the \code{+}
  10984. operator. The output of \code{rco\_exp} is then shown, in which the
  10985. \code{begin} expressions have been bound to temporary
  10986. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10987. allowed to have arbitrary expressions in their right-hand side
  10988. expression, so it is fine to place \code{begin} there.
  10989. %
  10990. \begin{center}
  10991. \begin{tabular}{lcl}
  10992. \begin{minipage}{0.4\textwidth}
  10993. \begin{lstlisting}
  10994. (let ([x2 10])
  10995. (let ([y3 0])
  10996. (+ (+ (begin
  10997. (set! y3 (read))
  10998. (get! x2))
  10999. (begin
  11000. (set! x2 (read))
  11001. (get! y3)))
  11002. (get! x2))))
  11003. \end{lstlisting}
  11004. \end{minipage}
  11005. &
  11006. $\Rightarrow$
  11007. &
  11008. \begin{minipage}{0.4\textwidth}
  11009. \begin{lstlisting}
  11010. (let ([x2 10])
  11011. (let ([y3 0])
  11012. (let ([tmp4 (begin
  11013. (set! y3 (read))
  11014. x2)])
  11015. (let ([tmp5 (begin
  11016. (set! x2 (read))
  11017. y3)])
  11018. (let ([tmp6 (+ tmp4 tmp5)])
  11019. (let ([tmp7 x2])
  11020. (+ tmp6 tmp7)))))))
  11021. \end{lstlisting}
  11022. \end{minipage}
  11023. \end{tabular}
  11024. \end{center}
  11025. \fi}
  11026. \section{Explicate Control \racket{and \LangCLoop{}}}
  11027. \label{sec:explicate-loop}
  11028. \newcommand{\CloopASTRacket}{
  11029. \begin{array}{lcl}
  11030. \Atm &::=& \VOID \\
  11031. \Stmt &::=& \READ{}
  11032. \end{array}
  11033. }
  11034. {\if\edition\racketEd
  11035. Recall that in the \code{explicate\_control} pass we define one helper
  11036. function for each kind of position in the program. For the \LangVarANF{}
  11037. language of integers and variables, we needed assignment and tail
  11038. positions. The \code{if} expressions of \LangIfANF{} introduced predicate
  11039. positions. For \LangLoopANF{}, the \code{begin} expression introduces yet
  11040. another kind of position: effect position. Except for the last
  11041. subexpression, the subexpressions inside a \code{begin} are evaluated
  11042. only for their effect. Their result values are discarded. We can
  11043. generate better code by taking this fact into account.
  11044. The output language of \code{explicate\_control} is \LangCLoop{}
  11045. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  11046. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  11047. and that \code{read} may appear as a statement. The most significant
  11048. difference between the programs generated by \code{explicate\_control}
  11049. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  11050. chapter is that the control-flow graphs of the latter may contain
  11051. cycles.
  11052. \begin{figure}[tp]
  11053. \begin{tcolorbox}[colback=white]
  11054. \small
  11055. \[
  11056. \begin{array}{l}
  11057. \gray{\CvarASTRacket} \\ \hline
  11058. \gray{\CifASTRacket} \\ \hline
  11059. \CloopASTRacket \\
  11060. \begin{array}{lcl}
  11061. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11062. \end{array}
  11063. \end{array}
  11064. \]
  11065. \end{tcolorbox}
  11066. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  11067. \label{fig:c7-syntax}
  11068. \index{subject}{Cwhile@\LangCLoop{} abstract syntax}
  11069. \end{figure}
  11070. The new auxiliary function \code{explicate\_effect} takes an
  11071. expression (in an effect position) and the code for its
  11072. continuation. The function returns a $\Tail$ that includes the
  11073. generated code for the input expression followed by the
  11074. continuation. If the expression is obviously pure, that is, never
  11075. causes side effects, then the expression can be removed, so the result
  11076. is just the continuation.
  11077. %
  11078. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  11079. interesting; the generated code is depicted in the following diagram:
  11080. \begin{center}
  11081. \begin{minipage}{0.3\textwidth}
  11082. \xymatrix{
  11083. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  11084. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  11085. & *+[F]{\txt{\itm{cont}}} \\
  11086. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  11087. }
  11088. \end{minipage}
  11089. \end{center}
  11090. We start by creating a fresh label $\itm{loop}$ for the top of the
  11091. loop. Next, recursively process the \itm{body} (in effect position)
  11092. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  11093. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11094. \itm{body'} as the \emph{then} branch and the continuation block as the
  11095. \emph{else} branch. The result should be added to the dictionary of
  11096. \code{basic-blocks} with the label \itm{loop}. The result for the
  11097. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11098. The auxiliary functions for tail, assignment, and predicate positions
  11099. need to be updated. The three new language forms, \code{while},
  11100. \code{set!}, and \code{begin}, can appear in assignment and tail
  11101. positions. Only \code{begin} may appear in predicate positions; the
  11102. other two have result type \code{Void}.
  11103. \fi}
  11104. %
  11105. {\if\edition\pythonEd\pythonColor
  11106. %
  11107. The output of this pass is the language \LangCIf{}. No new language
  11108. features are needed in the output, because a \code{while} loop can be
  11109. expressed in terms of \code{goto} and \code{if} statements, which are
  11110. already in \LangCIf{}.
  11111. %
  11112. Add a case for the \code{while} statement to the
  11113. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11114. the condition expression.
  11115. %
  11116. \fi}
  11117. {\if\edition\racketEd
  11118. \section{Select Instructions}
  11119. \label{sec:select-instructions-loop}
  11120. \index{subject}{select instructions}
  11121. Only two small additions are needed in the \code{select\_instructions}
  11122. pass to handle the changes to \LangCLoop{}. First, to handle the
  11123. addition of \VOID{} we simply translate it to \code{0}. Second,
  11124. \code{read} may appear as a stand-alone statement instead of
  11125. appearing only on the right-hand side of an assignment statement. The code
  11126. generation is nearly identical to the one for assignment; just leave
  11127. off the instruction for moving the result into the left-hand side.
  11128. \fi}
  11129. \section{Register Allocation}
  11130. \label{sec:register-allocation-loop}
  11131. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11132. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11133. which complicates the liveness analysis needed for register
  11134. allocation.
  11135. %
  11136. We recommend using the generic \code{analyze\_dataflow} function that
  11137. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11138. perform liveness analysis, replacing the code in
  11139. \code{uncover\_live} that processed the basic blocks in topological
  11140. order (section~\ref{sec:liveness-analysis-Lif}).
  11141. The \code{analyze\_dataflow} function has the following four parameters.
  11142. \begin{enumerate}
  11143. \item The first parameter \code{G} should be passed the transpose
  11144. of the control-flow graph.
  11145. \item The second parameter \code{transfer} should be passed a function
  11146. that applies liveness analysis to a basic block. It takes two
  11147. parameters: the label for the block to analyze and the live-after
  11148. set for that block. The transfer function should return the
  11149. live-before set for the block.
  11150. %
  11151. \racket{Also, as a side effect, it should update the block's
  11152. $\itm{info}$ with the liveness information for each instruction.}
  11153. %
  11154. \python{Also, as a side effect, it should update the live-before and
  11155. live-after sets for each instruction.}
  11156. %
  11157. To implement the \code{transfer} function, you should be able to
  11158. reuse the code you already have for analyzing basic blocks.
  11159. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11160. \code{bottom} and \code{join} for the lattice of abstract states,
  11161. that is, sets of locations. For liveness analysis, the bottom of the
  11162. lattice is the empty set, and the join operator is set union.
  11163. \end{enumerate}
  11164. \begin{figure}[tp]
  11165. \begin{tcolorbox}[colback=white]
  11166. {\if\edition\racketEd
  11167. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11168. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11169. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11170. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11171. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11172. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11173. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11174. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11175. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11176. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11177. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11178. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11179. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11180. \path[->,bend left=15] (Lfun) edge [above] node
  11181. {\ttfamily\footnotesize shrink} (Lfun-2);
  11182. \path[->,bend left=15] (Lfun-2) edge [above] node
  11183. {\ttfamily\footnotesize uniquify} (F1-4);
  11184. \path[->,bend left=15] (F1-4) edge [above] node
  11185. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11186. \path[->,bend left=15] (F1-5) edge [left] node
  11187. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11188. \path[->,bend left=10] (F1-6) edge [above] node
  11189. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11190. \path[->,bend left=15] (C3-2) edge [right] node
  11191. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11192. \path[->,bend right=15] (x86-2) edge [right] node
  11193. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11194. \path[->,bend right=15] (x86-2-1) edge [below] node
  11195. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11196. \path[->,bend right=15] (x86-2-2) edge [right] node
  11197. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11198. \path[->,bend left=15] (x86-3) edge [above] node
  11199. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11200. \path[->,bend left=15] (x86-4) edge [right] node
  11201. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11202. \end{tikzpicture}
  11203. \fi}
  11204. {\if\edition\pythonEd\pythonColor
  11205. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11206. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11207. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11208. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11209. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11210. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11211. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11212. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11213. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11214. \path[->,bend left=15] (Lfun) edge [above] node
  11215. {\ttfamily\footnotesize shrink} (Lfun-2);
  11216. \path[->,bend left=15] (Lfun-2) edge [above] node
  11217. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11218. \path[->,bend left=10] (F1-6) edge [right] node
  11219. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11220. \path[->,bend right=15] (C3-2) edge [right] node
  11221. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11222. \path[->,bend right=15] (x86-2) edge [below] node
  11223. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11224. \path[->,bend left=15] (x86-3) edge [above] node
  11225. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11226. \path[->,bend right=15] (x86-4) edge [below] node
  11227. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11228. \end{tikzpicture}
  11229. \fi}
  11230. \end{tcolorbox}
  11231. \caption{Diagram of the passes for \LangLoop{}.}
  11232. \label{fig:Lwhile-passes}
  11233. \end{figure}
  11234. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11235. for the compilation of \LangLoop{}.
  11236. % Further Reading: dataflow analysis
  11237. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11238. \chapter{Tuples and Garbage Collection}
  11239. \label{ch:Lvec}
  11240. \index{subject}{tuple}
  11241. \index{subject}{vector}
  11242. \setcounter{footnote}{0}
  11243. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11244. %% all the IR grammars are spelled out! \\ --Jeremy}
  11245. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11246. %% the root stack. \\ --Jeremy}
  11247. In this chapter we study the implementation of tuples\racket{, called
  11248. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11249. in which each element may have a different type.
  11250. %
  11251. This language feature is the first to use the computer's
  11252. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11253. indefinite; that is, a tuple lives forever from the programmer's
  11254. viewpoint. Of course, from an implementer's viewpoint, it is important
  11255. to reclaim the space associated with a tuple when it is no longer
  11256. needed, which is why we also study \emph{garbage collection}
  11257. \index{subject}{garbage collection} techniques in this chapter.
  11258. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11259. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11260. language (chapter~\ref{ch:Lwhile}) with tuples.
  11261. %
  11262. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11263. copying live tuples back and forth between two halves of the heap. The
  11264. garbage collector requires coordination with the compiler so that it
  11265. can find all the live tuples.
  11266. %
  11267. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11268. discuss the necessary changes and additions to the compiler passes,
  11269. including a new compiler pass named \code{expose\_allocation}.
  11270. \section{The \LangVec{} Language}
  11271. \label{sec:r3}
  11272. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11273. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11274. the definition of the abstract syntax.
  11275. %
  11276. \racket{The \LangVec{} language includes the forms \code{vector} for
  11277. creating a tuple, \code{vector-ref} for reading an element of a
  11278. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11279. \code{vector-length} for obtaining the number of elements of a
  11280. tuple.}
  11281. %
  11282. \python{The \LangVec{} language adds (1) tuple creation via a
  11283. comma-separated list of expressions; (2) accessing an element of a
  11284. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11285. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11286. comparison operator; and (4) obtaining the number of elements (the
  11287. length) of a tuple. In this chapter, we restrict access indices to
  11288. constant integers.}
  11289. %
  11290. The following program shows an example of the use of tuples. It creates a tuple
  11291. \code{t} containing the elements \code{40},
  11292. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11293. contains just \code{2}. The element at index $1$ of \code{t} is
  11294. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11295. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11296. to which we add \code{2}, the element at index $0$ of the tuple.
  11297. The result of the program is \code{42}.
  11298. %
  11299. {\if\edition\racketEd
  11300. \begin{lstlisting}
  11301. (let ([t (vector 40 #t (vector 2))])
  11302. (if (vector-ref t 1)
  11303. (+ (vector-ref t 0)
  11304. (vector-ref (vector-ref t 2) 0))
  11305. 44))
  11306. \end{lstlisting}
  11307. \fi}
  11308. {\if\edition\pythonEd\pythonColor
  11309. \begin{lstlisting}
  11310. t = 40, True, (2,)
  11311. print(t[0] + t[2][0] if t[1] else 44)
  11312. \end{lstlisting}
  11313. \fi}
  11314. \newcommand{\LtupGrammarRacket}{
  11315. \begin{array}{lcl}
  11316. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11317. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11318. \MID \LP\key{vector-length}\;\Exp\RP \\
  11319. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11320. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11321. \end{array}
  11322. }
  11323. \newcommand{\LtupASTRacket}{
  11324. \begin{array}{lcl}
  11325. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11326. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11327. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11328. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11329. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11330. \end{array}
  11331. }
  11332. \newcommand{\LtupGrammarPython}{
  11333. \begin{array}{rcl}
  11334. \itm{cmp} &::= & \key{is} \\
  11335. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11336. \end{array}
  11337. }
  11338. \newcommand{\LtupASTPython}{
  11339. \begin{array}{lcl}
  11340. \itm{cmp} &::= & \code{Is()} \\
  11341. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11342. &\MID& \LEN{\Exp}
  11343. \end{array}
  11344. }
  11345. \begin{figure}[tbp]
  11346. \centering
  11347. \begin{tcolorbox}[colback=white]
  11348. \small
  11349. {\if\edition\racketEd
  11350. \[
  11351. \begin{array}{l}
  11352. \gray{\LintGrammarRacket{}} \\ \hline
  11353. \gray{\LvarGrammarRacket{}} \\ \hline
  11354. \gray{\LifGrammarRacket{}} \\ \hline
  11355. \gray{\LwhileGrammarRacket} \\ \hline
  11356. \LtupGrammarRacket \\
  11357. \begin{array}{lcl}
  11358. \LangVecM{} &::=& \Exp
  11359. \end{array}
  11360. \end{array}
  11361. \]
  11362. \fi}
  11363. {\if\edition\pythonEd\pythonColor
  11364. \[
  11365. \begin{array}{l}
  11366. \gray{\LintGrammarPython{}} \\ \hline
  11367. \gray{\LvarGrammarPython{}} \\ \hline
  11368. \gray{\LifGrammarPython{}} \\ \hline
  11369. \gray{\LwhileGrammarPython} \\ \hline
  11370. \LtupGrammarPython \\
  11371. \begin{array}{rcl}
  11372. \LangVecM{} &::=& \Stmt^{*}
  11373. \end{array}
  11374. \end{array}
  11375. \]
  11376. \fi}
  11377. \end{tcolorbox}
  11378. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11379. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11380. \label{fig:Lvec-concrete-syntax}
  11381. \index{subject}{Ltup@\LangVec{} concrete syntax}
  11382. \end{figure}
  11383. \begin{figure}[tp]
  11384. \centering
  11385. \begin{tcolorbox}[colback=white]
  11386. \small
  11387. {\if\edition\racketEd
  11388. \[
  11389. \begin{array}{l}
  11390. \gray{\LintOpAST} \\ \hline
  11391. \gray{\LvarASTRacket{}} \\ \hline
  11392. \gray{\LifASTRacket{}} \\ \hline
  11393. \gray{\LwhileASTRacket{}} \\ \hline
  11394. \LtupASTRacket{} \\
  11395. \begin{array}{lcl}
  11396. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11397. \end{array}
  11398. \end{array}
  11399. \]
  11400. \fi}
  11401. {\if\edition\pythonEd\pythonColor
  11402. \[
  11403. \begin{array}{l}
  11404. \gray{\LintASTPython} \\ \hline
  11405. \gray{\LvarASTPython} \\ \hline
  11406. \gray{\LifASTPython} \\ \hline
  11407. \gray{\LwhileASTPython} \\ \hline
  11408. \LtupASTPython \\
  11409. \begin{array}{lcl}
  11410. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11411. \end{array}
  11412. \end{array}
  11413. \]
  11414. \fi}
  11415. \end{tcolorbox}
  11416. \caption{The abstract syntax of \LangVec{}.}
  11417. \label{fig:Lvec-syntax}
  11418. \index{subject}{Ltup@\LangVec{} abstract syntax}
  11419. \end{figure}
  11420. Tuples raise several interesting new issues. First, variable binding
  11421. performs a shallow copy in dealing with tuples, which means that
  11422. different variables can refer to the same tuple; that is, two
  11423. variables can be \emph{aliases}\index{subject}{alias} for the same
  11424. entity. Consider the following example, in which \code{t1} and
  11425. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11426. different tuple value with equal elements. The result of the
  11427. program is \code{42}.
  11428. \begin{center}
  11429. \begin{minipage}{0.96\textwidth}
  11430. {\if\edition\racketEd
  11431. \begin{lstlisting}
  11432. (let ([t1 (vector 3 7)])
  11433. (let ([t2 t1])
  11434. (let ([t3 (vector 3 7)])
  11435. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11436. 42
  11437. 0))))
  11438. \end{lstlisting}
  11439. \fi}
  11440. {\if\edition\pythonEd\pythonColor
  11441. \begin{lstlisting}
  11442. t1 = 3, 7
  11443. t2 = t1
  11444. t3 = 3, 7
  11445. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11446. \end{lstlisting}
  11447. \fi}
  11448. \end{minipage}
  11449. \end{center}
  11450. {\if\edition\racketEd
  11451. Whether two variables are aliased or not affects what happens
  11452. when the underlying tuple is mutated\index{subject}{mutation}.
  11453. Consider the following example in which \code{t1} and \code{t2}
  11454. again refer to the same tuple value.
  11455. \begin{center}
  11456. \begin{minipage}{0.96\textwidth}
  11457. \begin{lstlisting}
  11458. (let ([t1 (vector 3 7)])
  11459. (let ([t2 t1])
  11460. (let ([_ (vector-set! t2 0 42)])
  11461. (vector-ref t1 0))))
  11462. \end{lstlisting}
  11463. \end{minipage}
  11464. \end{center}
  11465. The mutation through \code{t2} is visible in referencing the tuple
  11466. from \code{t1}, so the result of this program is \code{42}.
  11467. \fi}
  11468. The next issue concerns the lifetime of tuples. When does a tuple's
  11469. lifetime end? Notice that \LangVec{} does not include an operation
  11470. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11471. to any notion of static scoping.
  11472. %
  11473. {\if\edition\racketEd
  11474. %
  11475. For example, the following program returns \code{42} even though the
  11476. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11477. that reads from the vector to which it was bound.
  11478. \begin{center}
  11479. \begin{minipage}{0.96\textwidth}
  11480. \begin{lstlisting}
  11481. (let ([v (vector (vector 44))])
  11482. (let ([x (let ([w (vector 42)])
  11483. (let ([_ (vector-set! v 0 w)])
  11484. 0))])
  11485. (+ x (vector-ref (vector-ref v 0) 0))))
  11486. \end{lstlisting}
  11487. \end{minipage}
  11488. \end{center}
  11489. \fi}
  11490. %
  11491. {\if\edition\pythonEd\pythonColor
  11492. %
  11493. For example, the following program returns \code{42} even though the
  11494. variable \code{x} goes out of scope when the function returns, prior
  11495. to reading the tuple element at index $0$. (We study the compilation
  11496. of functions in chapter~\ref{ch:Lfun}.)
  11497. %
  11498. \begin{center}
  11499. \begin{minipage}{0.96\textwidth}
  11500. \begin{lstlisting}
  11501. def f():
  11502. x = 42, 43
  11503. return x
  11504. t = f()
  11505. print(t[0])
  11506. \end{lstlisting}
  11507. \end{minipage}
  11508. \end{center}
  11509. \fi}
  11510. %
  11511. From the perspective of programmer-observable behavior, tuples live
  11512. forever. However, if they really lived forever then many long-running
  11513. programs would run out of memory. To solve this problem, the
  11514. language's runtime system performs automatic garbage collection.
  11515. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11516. \LangVec{} language.
  11517. %
  11518. \racket{We define the \code{vector}, \code{vector-ref},
  11519. \code{vector-set!}, and \code{vector-length} operations for
  11520. \LangVec{} in terms of the corresponding operations in Racket. One
  11521. subtle point is that the \code{vector-set!} operation returns the
  11522. \code{\#<void>} value.}
  11523. %
  11524. \python{We represent tuples with Python lists in the interpreter
  11525. because we need to write to them
  11526. (section~\ref{sec:expose-allocation}). (Python tuples are
  11527. immutable.) We define element access, the \code{is} operator, and
  11528. the \code{len} operator for \LangVec{} in terms of the corresponding
  11529. operations in Python.}
  11530. \begin{figure}[tbp]
  11531. \begin{tcolorbox}[colback=white]
  11532. {\if\edition\racketEd
  11533. \begin{lstlisting}
  11534. (define interp-Lvec-class
  11535. (class interp-Lwhile-class
  11536. (super-new)
  11537. (define/override (interp-op op)
  11538. (match op
  11539. ['eq? (lambda (v1 v2)
  11540. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11541. (and (boolean? v1) (boolean? v2))
  11542. (and (vector? v1) (vector? v2))
  11543. (and (void? v1) (void? v2)))
  11544. (eq? v1 v2)]))]
  11545. ['vector vector]
  11546. ['vector-length vector-length]
  11547. ['vector-ref vector-ref]
  11548. ['vector-set! vector-set!]
  11549. [else (super interp-op op)]
  11550. ))
  11551. (define/override ((interp-exp env) e)
  11552. (match e
  11553. [(HasType e t) ((interp-exp env) e)]
  11554. [else ((super interp-exp env) e)]
  11555. ))
  11556. ))
  11557. (define (interp-Lvec p)
  11558. (send (new interp-Lvec-class) interp-program p))
  11559. \end{lstlisting}
  11560. \fi}
  11561. %
  11562. {\if\edition\pythonEd\pythonColor
  11563. \begin{lstlisting}
  11564. class InterpLtup(InterpLwhile):
  11565. def interp_cmp(self, cmp):
  11566. match cmp:
  11567. case Is():
  11568. return lambda x, y: x is y
  11569. case _:
  11570. return super().interp_cmp(cmp)
  11571. def interp_exp(self, e, env):
  11572. match e:
  11573. case Tuple(es, Load()):
  11574. return tuple([self.interp_exp(e, env) for e in es])
  11575. case Subscript(tup, index, Load()):
  11576. t = self.interp_exp(tup, env)
  11577. n = self.interp_exp(index, env)
  11578. return t[n]
  11579. case _:
  11580. return super().interp_exp(e, env)
  11581. \end{lstlisting}
  11582. \fi}
  11583. \end{tcolorbox}
  11584. \caption{Interpreter for the \LangVec{} language.}
  11585. \label{fig:interp-Lvec}
  11586. \end{figure}
  11587. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11588. \LangVec{}.
  11589. %
  11590. The type of a tuple is a
  11591. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11592. type for each of its elements.
  11593. %
  11594. \racket{To create the s-expression for the \code{Vector} type, we use the
  11595. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11596. operator} \code{,@} to insert the list \code{t*} without its usual
  11597. start and end parentheses. \index{subject}{unquote-splicing}}
  11598. %
  11599. The type of accessing the ith element of a tuple is the ith element
  11600. type of the tuple's type, if there is one. If not, an error is
  11601. signaled. Note that the index \code{i} is required to be a constant
  11602. integer (and not, for example, a call to
  11603. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11604. can determine the element's type given the tuple type.
  11605. %
  11606. \racket{
  11607. Regarding writing an element to a tuple, the element's type must
  11608. be equal to the ith element type of the tuple's type.
  11609. The result type is \code{Void}.}
  11610. %% When allocating a tuple,
  11611. %% we need to know which elements of the tuple are themselves tuples for
  11612. %% the purposes of garbage collection. We can obtain this information
  11613. %% during type checking. The type checker shown in
  11614. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11615. %% expression; it also
  11616. %% %
  11617. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11618. %% where $T$ is the tuple's type.
  11619. %
  11620. %records the type of each tuple expression in a new field named \code{has\_type}.
  11621. \begin{figure}[tp]
  11622. \begin{tcolorbox}[colback=white]
  11623. {\if\edition\racketEd
  11624. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11625. (define type-check-Lvec-class
  11626. (class type-check-Lif-class
  11627. (super-new)
  11628. (inherit check-type-equal?)
  11629. (define/override (type-check-exp env)
  11630. (lambda (e)
  11631. (define recur (type-check-exp env))
  11632. (match e
  11633. [(Prim 'vector es)
  11634. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11635. (define t `(Vector ,@t*))
  11636. (values (Prim 'vector e*) t)]
  11637. [(Prim 'vector-ref (list e1 (Int i)))
  11638. (define-values (e1^ t) (recur e1))
  11639. (match t
  11640. [`(Vector ,ts ...)
  11641. (unless (and (0 . <= . i) (i . < . (length ts)))
  11642. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11643. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11644. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11645. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11646. (define-values (e-vec t-vec) (recur e1))
  11647. (define-values (e-elt^ t-elt) (recur elt))
  11648. (match t-vec
  11649. [`(Vector ,ts ...)
  11650. (unless (and (0 . <= . i) (i . < . (length ts)))
  11651. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11652. (check-type-equal? (list-ref ts i) t-elt e)
  11653. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11654. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11655. [(Prim 'vector-length (list e))
  11656. (define-values (e^ t) (recur e))
  11657. (match t
  11658. [`(Vector ,ts ...)
  11659. (values (Prim 'vector-length (list e^)) 'Integer)]
  11660. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11661. [(Prim 'eq? (list arg1 arg2))
  11662. (define-values (e1 t1) (recur arg1))
  11663. (define-values (e2 t2) (recur arg2))
  11664. (match* (t1 t2)
  11665. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11666. [(other wise) (check-type-equal? t1 t2 e)])
  11667. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11668. [else ((super type-check-exp env) e)]
  11669. )))
  11670. ))
  11671. (define (type-check-Lvec p)
  11672. (send (new type-check-Lvec-class) type-check-program p))
  11673. \end{lstlisting}
  11674. \fi}
  11675. {\if\edition\pythonEd\pythonColor
  11676. \begin{lstlisting}
  11677. class TypeCheckLtup(TypeCheckLwhile):
  11678. def type_check_exp(self, e, env):
  11679. match e:
  11680. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11681. l = self.type_check_exp(left, env)
  11682. r = self.type_check_exp(right, env)
  11683. check_type_equal(l, r, e)
  11684. return bool
  11685. case Tuple(es, Load()):
  11686. ts = [self.type_check_exp(e, env) for e in es]
  11687. e.has_type = TupleType(ts)
  11688. return e.has_type
  11689. case Subscript(tup, Constant(i), Load()):
  11690. tup_ty = self.type_check_exp(tup, env)
  11691. i_ty = self.type_check_exp(Constant(i), env)
  11692. check_type_equal(i_ty, int, i)
  11693. match tup_ty:
  11694. case TupleType(ts):
  11695. return ts[i]
  11696. case _:
  11697. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11698. case _:
  11699. return super().type_check_exp(e, env)
  11700. \end{lstlisting}
  11701. \fi}
  11702. \end{tcolorbox}
  11703. \caption{Type checker for the \LangVec{} language.}
  11704. \label{fig:type-check-Lvec}
  11705. \end{figure}
  11706. \section{Garbage Collection}
  11707. \label{sec:GC}
  11708. Garbage collection is a runtime technique for reclaiming space on the
  11709. heap that will not be used in the future of the running program. We
  11710. use the term \emph{object}\index{subject}{object} to refer to any
  11711. value that is stored in the heap, which for now includes only
  11712. tuples.%
  11713. %
  11714. \footnote{The term \emph{object} as it is used in the context of
  11715. object-oriented programming has a more specific meaning than the
  11716. way in which we use the term here.}
  11717. %
  11718. Unfortunately, it is impossible to know precisely which objects will
  11719. be accessed in the future and which will not. Instead, garbage
  11720. collectors overapproximate the set of objects that will be accessed by
  11721. identifying which objects can possibly be accessed. The running
  11722. program can directly access objects that are in registers and on the
  11723. procedure call stack. It can also transitively access the elements of
  11724. tuples, starting with a tuple whose address is in a register or on the
  11725. procedure call stack. We define the \emph{root
  11726. set}\index{subject}{root set} to be all the tuple addresses that are
  11727. in registers or on the procedure call stack. We define the \emph{live
  11728. objects}\index{subject}{live objects} to be the objects that are
  11729. reachable from the root set. Garbage collectors reclaim the space that
  11730. is allocated to objects that are no longer live. \index{subject}{allocate}
  11731. That means that some objects may not get reclaimed as soon as they could be,
  11732. but at least
  11733. garbage collectors do not reclaim the space dedicated to objects that
  11734. will be accessed in the future! The programmer can influence which
  11735. objects get reclaimed by causing them to become unreachable.
  11736. So the goal of the garbage collector is twofold:
  11737. \begin{enumerate}
  11738. \item to preserve all the live objects, and
  11739. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11740. \end{enumerate}
  11741. \subsection{Two-Space Copying Collector}
  11742. Here we study a relatively simple algorithm for garbage collection
  11743. that is the basis of many state-of-the-art garbage
  11744. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11745. particular, we describe a two-space copying
  11746. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11747. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11748. collector} \index{subject}{two-space copying collector}
  11749. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11750. what happens in a two-space collector, showing two time steps, prior
  11751. to garbage collection (on the top) and after garbage collection (on
  11752. the bottom). In a two-space collector, the heap is divided into two
  11753. parts named the FromSpace\index{subject}{FromSpace} and the
  11754. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11755. FromSpace until there is not enough room for the next allocation
  11756. request. At that point, the garbage collector goes to work to make
  11757. room for the next allocation.
  11758. A copying collector makes more room by copying all the live objects
  11759. from the FromSpace into the ToSpace and then performs a sleight of
  11760. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11761. as the new ToSpace. In the example shown in
  11762. figure~\ref{fig:copying-collector}, the root set consists of three
  11763. pointers, one in a register and two on the stack. All the live
  11764. objects have been copied to the ToSpace (the right-hand side of
  11765. figure~\ref{fig:copying-collector}) in a way that preserves the
  11766. pointer relationships. For example, the pointer in the register still
  11767. points to a tuple that in turn points to two other tuples. There are
  11768. four tuples that are not reachable from the root set and therefore do
  11769. not get copied into the ToSpace.
  11770. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11771. created by a well-typed program in \LangVec{} because it contains a
  11772. cycle. However, creating cycles will be possible once we get to
  11773. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11774. to deal with cycles to begin with, so we will not need to revisit this
  11775. issue.
  11776. \begin{figure}[tbp]
  11777. \centering
  11778. \begin{tcolorbox}[colback=white]
  11779. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11780. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11781. \\[5ex]
  11782. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11783. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11784. \end{tcolorbox}
  11785. \caption{A copying collector in action.}
  11786. \label{fig:copying-collector}
  11787. \end{figure}
  11788. \subsection{Graph Copying via Cheney's Algorithm}
  11789. \label{sec:cheney}
  11790. \index{subject}{Cheney's algorithm}
  11791. Let us take a closer look at the copying of the live objects. The
  11792. allocated\index{subject}{allocate} objects and pointers can be viewed
  11793. as a graph, and we need to copy the part of the graph that is
  11794. reachable from the root set. To make sure that we copy all the
  11795. reachable vertices in the graph, we need an exhaustive graph traversal
  11796. algorithm, such as depth-first search or breadth-first
  11797. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11798. take into account the possibility of cycles by marking which vertices
  11799. have already been visited, so to ensure termination of the
  11800. algorithm. These search algorithms also use a data structure such as a
  11801. stack or queue as a to-do list to keep track of the vertices that need
  11802. to be visited. We use breadth-first search and a trick due to
  11803. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11804. copying tuples into the ToSpace.
  11805. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11806. copy progresses. The queue is represented by a chunk of contiguous
  11807. memory at the beginning of the ToSpace, using two pointers to track
  11808. the front and the back of the queue, called the \emph{free pointer}
  11809. and the \emph{scan pointer}, respectively. The algorithm starts by
  11810. copying all tuples that are immediately reachable from the root set
  11811. into the ToSpace to form the initial queue. When we copy a tuple, we
  11812. mark the old tuple to indicate that it has been visited. We discuss
  11813. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11814. that any pointers inside the copied tuples in the queue still point
  11815. back to the FromSpace. Once the initial queue has been created, the
  11816. algorithm enters a loop in which it repeatedly processes the tuple at
  11817. the front of the queue and pops it off the queue. To process a tuple,
  11818. the algorithm copies all the objects that are directly reachable from it
  11819. to the ToSpace, placing them at the back of the queue. The algorithm
  11820. then updates the pointers in the popped tuple so that they point to the
  11821. newly copied objects.
  11822. \begin{figure}[tbp]
  11823. \centering
  11824. \begin{tcolorbox}[colback=white]
  11825. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11826. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11827. \end{tcolorbox}
  11828. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11829. \label{fig:cheney}
  11830. \end{figure}
  11831. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11832. tuple whose second element is $42$ to the back of the queue. The other
  11833. pointer goes to a tuple that has already been copied, so we do not
  11834. need to copy it again, but we do need to update the pointer to the new
  11835. location. This can be accomplished by storing a \emph{forwarding
  11836. pointer}\index{subject}{forwarding pointer} to the new location in the
  11837. old tuple, when we initially copied the tuple into the
  11838. ToSpace. This completes one step of the algorithm. The algorithm
  11839. continues in this way until the queue is empty; that is, when the scan
  11840. pointer catches up with the free pointer.
  11841. \subsection{Data Representation}
  11842. \label{sec:data-rep-gc}
  11843. The garbage collector places some requirements on the data
  11844. representations used by our compiler. First, the garbage collector
  11845. needs to distinguish between pointers and other kinds of data such as
  11846. integers. The following are three ways to accomplish this:
  11847. \begin{enumerate}
  11848. \item Attach a tag to each object that identifies what type of
  11849. object it is~\citep{McCarthy:1960dz}.
  11850. \item Store different types of objects in different
  11851. regions~\citep{Steele:1977ab}.
  11852. \item Use type information from the program to either (a) generate
  11853. type-specific code for collecting, or (b) generate tables that
  11854. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11855. \end{enumerate}
  11856. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11857. need to tag objects in any case, so option 1 is a natural choice for those
  11858. languages. However, \LangVec{} is a statically typed language, so it
  11859. would be unfortunate to require tags on every object, especially small
  11860. and pervasive objects like integers and Booleans. Option 3 is the
  11861. best-performing choice for statically typed languages, but it comes with
  11862. a relatively high implementation complexity. To keep this chapter
  11863. within a reasonable scope of complexity, we recommend a combination of options
  11864. 1 and 2, using separate strategies for the stack and the heap.
  11865. Regarding the stack, we recommend using a separate stack for pointers,
  11866. which we call the \emph{root stack}\index{subject}{root stack}
  11867. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11868. That is, when a local variable needs to be spilled and is of type
  11869. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11870. root stack instead of putting it on the procedure call
  11871. stack. Furthermore, we always spill tuple-typed variables if they are
  11872. live during a call to the collector, thereby ensuring that no pointers
  11873. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11874. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11875. contrasts it with the data layout using a root stack. The root stack
  11876. contains the two pointers from the regular stack and also the pointer
  11877. in the second register.
  11878. \begin{figure}[tbp]
  11879. \centering
  11880. \begin{tcolorbox}[colback=white]
  11881. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11882. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11883. \end{tcolorbox}
  11884. \caption{Maintaining a root stack to facilitate garbage collection.}
  11885. \label{fig:shadow-stack}
  11886. \end{figure}
  11887. The problem of distinguishing between pointers and other kinds of data
  11888. also arises inside each tuple on the heap. We solve this problem by
  11889. attaching a tag, an extra 64 bits, to each
  11890. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11891. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11892. Note that we have drawn the bits in a big-endian way, from right to left,
  11893. with bit location 0 (the least significant bit) on the far right,
  11894. which corresponds to the direction of the x86 shifting instructions
  11895. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11896. is dedicated to specifying which elements of the tuple are pointers,
  11897. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11898. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11899. data. The pointer mask starts at bit location 7. We limit tuples to a
  11900. maximum size of fifty elements, so we need 50 bits for the pointer
  11901. mask.%
  11902. %
  11903. \footnote{A production-quality compiler would handle
  11904. arbitrarily sized tuples and use a more complex approach.}
  11905. %
  11906. The tag also contains two other pieces of information. The length of
  11907. the tuple (number of elements) is stored in bits at locations 1 through
  11908. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11909. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11910. has not yet been copied. If the bit has value 0, then the entire tag
  11911. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11912. zero in any case, because our tuples are 8-byte aligned.)
  11913. \begin{figure}[tbp]
  11914. \centering
  11915. \begin{tcolorbox}[colback=white]
  11916. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11917. \end{tcolorbox}
  11918. \caption{Representation of tuples in the heap.}
  11919. \label{fig:tuple-rep}
  11920. \end{figure}
  11921. \subsection{Implementation of the Garbage Collector}
  11922. \label{sec:organize-gz}
  11923. \index{subject}{prelude}
  11924. An implementation of the copying collector is provided in the
  11925. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11926. interface to the garbage collector that is used by the compiler. The
  11927. \code{initialize} function creates the FromSpace, ToSpace, and root
  11928. stack and should be called in the prelude of the \code{main}
  11929. function. The arguments of \code{initialize} are the root stack size
  11930. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11931. good choice for both. The \code{initialize} function puts the address
  11932. of the beginning of the FromSpace into the global variable
  11933. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11934. the address that is one past the last element of the FromSpace. We use
  11935. half-open intervals to represent chunks of
  11936. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11937. points to the first element of the root stack.
  11938. As long as there is room left in the FromSpace, your generated code
  11939. can allocate\index{subject}{allocate} tuples simply by moving the
  11940. \code{free\_ptr} forward.
  11941. %
  11942. The amount of room left in the FromSpace is the difference between the
  11943. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11944. function should be called when there is not enough room left in the
  11945. FromSpace for the next allocation. The \code{collect} function takes
  11946. a pointer to the current top of the root stack (one past the last item
  11947. that was pushed) and the number of bytes that need to be
  11948. allocated. The \code{collect} function performs the copying collection
  11949. and leaves the heap in a state such that there is enough room for the
  11950. next allocation.
  11951. \begin{figure}[tbp]
  11952. \begin{tcolorbox}[colback=white]
  11953. \begin{lstlisting}
  11954. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11955. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11956. int64_t* free_ptr;
  11957. int64_t* fromspace_begin;
  11958. int64_t* fromspace_end;
  11959. int64_t** rootstack_begin;
  11960. \end{lstlisting}
  11961. \end{tcolorbox}
  11962. \caption{The compiler's interface to the garbage collector.}
  11963. \label{fig:gc-header}
  11964. \end{figure}
  11965. %% \begin{exercise}
  11966. %% In the file \code{runtime.c} you will find the implementation of
  11967. %% \code{initialize} and a partial implementation of \code{collect}.
  11968. %% The \code{collect} function calls another function, \code{cheney},
  11969. %% to perform the actual copy, and that function is left to the reader
  11970. %% to implement. The following is the prototype for \code{cheney}.
  11971. %% \begin{lstlisting}
  11972. %% static void cheney(int64_t** rootstack_ptr);
  11973. %% \end{lstlisting}
  11974. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11975. %% rootstack (which is an array of pointers). The \code{cheney} function
  11976. %% also communicates with \code{collect} through the global
  11977. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11978. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11979. %% the ToSpace:
  11980. %% \begin{lstlisting}
  11981. %% static int64_t* tospace_begin;
  11982. %% static int64_t* tospace_end;
  11983. %% \end{lstlisting}
  11984. %% The job of the \code{cheney} function is to copy all the live
  11985. %% objects (reachable from the root stack) into the ToSpace, update
  11986. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11987. %% update the root stack so that it points to the objects in the
  11988. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11989. %% and ToSpace.
  11990. %% \end{exercise}
  11991. The introduction of garbage collection has a nontrivial impact on our
  11992. compiler passes. We introduce a new compiler pass named
  11993. \code{expose\_allocation} that elaborates the code for allocating
  11994. tuples. We also make significant changes to
  11995. \code{select\_instructions}, \code{build\_interference},
  11996. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11997. make minor changes in several more passes.
  11998. The following program serves as our running example. It creates
  11999. two tuples, one nested inside the other. Both tuples have length
  12000. one. The program accesses the element in the inner tuple.
  12001. % tests/vectors_test_17.rkt
  12002. {\if\edition\racketEd
  12003. \begin{lstlisting}
  12004. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  12005. \end{lstlisting}
  12006. \fi}
  12007. % tests/tuple/get_get.py
  12008. {\if\edition\pythonEd\pythonColor
  12009. \begin{lstlisting}
  12010. v1 = (42,)
  12011. v2 = (v1,)
  12012. print(v2[0][0])
  12013. \end{lstlisting}
  12014. \fi}
  12015. %% {\if\edition\racketEd
  12016. %% \section{Shrink}
  12017. %% \label{sec:shrink-Lvec}
  12018. %% Recall that the \code{shrink} pass translates the primitives operators
  12019. %% into a smaller set of primitives.
  12020. %% %
  12021. %% This pass comes after type checking, and the type checker adds a
  12022. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  12023. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  12024. %% \fi}
  12025. \section{Expose Allocation}
  12026. \label{sec:expose-allocation}
  12027. The pass \code{expose\_allocation} lowers tuple creation into making a
  12028. conditional call to the collector followed by allocating the
  12029. appropriate amount of memory and initializing it. We choose to place
  12030. the \code{expose\_allocation} pass before
  12031. \code{remove\_complex\_operands} because it generates code that
  12032. contains complex operands. However, with some care it can also be
  12033. placed after \code{remove\_complex\_operands}, which would simplify
  12034. tuple creation by removing the need to assign the initializing
  12035. expressions to temporary variables (see below).
  12036. The output of \code{expose\_allocation} is a language \LangAlloc{}
  12037. that replaces tuple creation with new lower-level forms that we use in the
  12038. translation of tuple creation\index{subject}{Lalloc@\LangAlloc{}}.
  12039. %
  12040. {\if\edition\racketEd
  12041. \[
  12042. \begin{array}{lcl}
  12043. \Exp &::=& (\key{collect} \,\itm{int})
  12044. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  12045. \MID (\key{global-value} \,\itm{name})
  12046. \end{array}
  12047. \]
  12048. \fi}
  12049. {\if\edition\pythonEd\pythonColor
  12050. \[
  12051. \begin{array}{lcl}
  12052. \Exp &::=& \key{collect}(\itm{int})
  12053. \MID \key{allocate}(\itm{int},\itm{type})
  12054. \MID \key{global\_value}(\itm{name}) \\
  12055. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  12056. \end{array}
  12057. \]
  12058. \fi}
  12059. %
  12060. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  12061. there be $n$ bytes ready to be allocated. During instruction
  12062. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  12063. form will become a call to the \code{collect} function in
  12064. \code{runtime.c}.
  12065. %
  12066. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  12067. space at the front for the 64-bit tag), but the elements are not
  12068. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  12069. of the tuple:
  12070. %
  12071. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  12072. %
  12073. where $\Type_i$ is the type of the $i$th element.
  12074. %
  12075. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  12076. variable, such as \code{free\_ptr}.
  12077. \racket{
  12078. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  12079. can be obtained by running the
  12080. \code{type-check-Lvec-has-type} type checker immediately before the
  12081. \code{expose\_allocation} pass. This version of the type checker
  12082. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  12083. around each tuple creation. The concrete syntax
  12084. for \code{HasType} is \code{has-type}.}
  12085. The following shows the transformation of tuple creation into (1) a
  12086. sequence of temporary variable bindings for the initializing
  12087. expressions, (2) a conditional call to \code{collect}, (3) a call to
  12088. \code{allocate}, and (4) the initialization of the tuple. The
  12089. \itm{len} placeholder refers to the length of the tuple, and
  12090. \itm{bytes} is the total number of bytes that need to be allocated for
  12091. the tuple, which is 8 for the tag plus \itm{len} times 8.
  12092. %
  12093. \python{The \itm{type} needed for the second argument of the
  12094. \code{allocate} form can be obtained from the \code{has\_type} field
  12095. of the tuple AST node, which is stored there by running the type
  12096. checker for \LangVec{} immediately before this pass.}
  12097. %
  12098. \begin{center}
  12099. \begin{minipage}{\textwidth}
  12100. {\if\edition\racketEd
  12101. \begin{lstlisting}
  12102. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12103. |$\Longrightarrow$|
  12104. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12105. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12106. (global-value fromspace_end))
  12107. (void)
  12108. (collect |\itm{bytes}|))])
  12109. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12110. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12111. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12112. |$v$|) ... )))) ...)
  12113. \end{lstlisting}
  12114. \fi}
  12115. {\if\edition\pythonEd\pythonColor
  12116. \begin{lstlisting}
  12117. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12118. |$\Longrightarrow$|
  12119. begin:
  12120. |$x_0$| = |$e_0$|
  12121. |$\vdots$|
  12122. |$x_{n-1}$| = |$e_{n-1}$|
  12123. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12124. 0
  12125. else:
  12126. collect(|\itm{bytes}|)
  12127. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12128. |$v$|[0] = |$x_0$|
  12129. |$\vdots$|
  12130. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12131. |$v$|
  12132. \end{lstlisting}
  12133. \fi}
  12134. \end{minipage}
  12135. \end{center}
  12136. %
  12137. \noindent The sequencing of the initializing expressions
  12138. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12139. they may trigger garbage collection and we cannot have an allocated
  12140. but uninitialized tuple on the heap during a collection.
  12141. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12142. \code{expose\_allocation} pass on our running example.
  12143. \begin{figure}[tbp]
  12144. \begin{tcolorbox}[colback=white]
  12145. % tests/s2_17.rkt
  12146. {\if\edition\racketEd
  12147. \begin{lstlisting}
  12148. (vector-ref
  12149. (vector-ref
  12150. (let ([vecinit6
  12151. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12152. (global-value fromspace_end))
  12153. (void)
  12154. (collect 16))])
  12155. (let ([alloc2 (allocate 1 (Vector Integer))])
  12156. (let ([_3 (vector-set! alloc2 0 42)])
  12157. alloc2)))])
  12158. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12159. (global-value fromspace_end))
  12160. (void)
  12161. (collect 16))])
  12162. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12163. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12164. alloc5))))
  12165. 0)
  12166. 0)
  12167. \end{lstlisting}
  12168. \fi}
  12169. {\if\edition\pythonEd\pythonColor
  12170. \begin{lstlisting}
  12171. v1 = begin:
  12172. init.514 = 42
  12173. if (free_ptr + 16) < fromspace_end:
  12174. else:
  12175. collect(16)
  12176. alloc.513 = allocate(1,tuple[int])
  12177. alloc.513[0] = init.514
  12178. alloc.513
  12179. v2 = begin:
  12180. init.516 = v1
  12181. if (free_ptr + 16) < fromspace_end:
  12182. else:
  12183. collect(16)
  12184. alloc.515 = allocate(1,tuple[tuple[int]])
  12185. alloc.515[0] = init.516
  12186. alloc.515
  12187. print(v2[0][0])
  12188. \end{lstlisting}
  12189. \fi}
  12190. \end{tcolorbox}
  12191. \caption{Output of the \code{expose\_allocation} pass.}
  12192. \label{fig:expose-alloc-output}
  12193. \end{figure}
  12194. \section{Remove Complex Operands}
  12195. \label{sec:remove-complex-opera-Lvec}
  12196. {\if\edition\racketEd
  12197. %
  12198. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12199. should be treated as complex operands.
  12200. %
  12201. \fi}
  12202. %
  12203. {\if\edition\pythonEd\pythonColor
  12204. %
  12205. The expressions \code{allocate}, \code{begin},
  12206. and tuple access should be treated as complex operands. The
  12207. subexpressions of tuple access must be atomic.
  12208. The \code{global\_value} AST node is atomic.
  12209. %
  12210. \fi}
  12211. %% A new case for
  12212. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12213. %% handled carefully to prevent the \code{Prim} node from being separated
  12214. %% from its enclosing \code{HasType}.
  12215. Figure~\ref{fig:Lvec-anf-syntax}
  12216. shows the grammar for the output language \LangAllocANF{} of this
  12217. pass, which is \LangAlloc{} in monadic normal form.
  12218. \newcommand{\LtupMonadASTRacket}{
  12219. \begin{array}{rcl}
  12220. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12221. \MID \GLOBALVALUE{\Var}
  12222. \end{array}
  12223. }
  12224. \newcommand{\LtupMonadASTPython}{
  12225. \begin{array}{rcl}
  12226. \Atm &::=& \GLOBALVALUE{\Var} \\
  12227. \Exp &::=& \GET{\Atm}{\Atm}
  12228. \MID \LEN{\Atm}\\
  12229. &\MID& \ALLOCATE{\Int}{\Type}\\
  12230. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12231. &\MID& \COLLECT{\Int}
  12232. \end{array}
  12233. }
  12234. \begin{figure}[tp]
  12235. \centering
  12236. \begin{tcolorbox}[colback=white]
  12237. \small
  12238. {\if\edition\racketEd
  12239. \[
  12240. \begin{array}{l}
  12241. \gray{\LvarMonadASTRacket} \\ \hline
  12242. \gray{\LifMonadASTRacket} \\ \hline
  12243. \gray{\LwhileMonadASTRacket} \\ \hline
  12244. \LtupMonadASTRacket \\
  12245. \begin{array}{rcl}
  12246. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12247. \end{array}
  12248. \end{array}
  12249. \]
  12250. \fi}
  12251. {\if\edition\pythonEd\pythonColor
  12252. \[
  12253. \begin{array}{l}
  12254. \gray{\LvarMonadASTPython} \\ \hline
  12255. \gray{\LifMonadASTPython} \\ \hline
  12256. \gray{\LwhileMonadASTPython} \\ \hline
  12257. \LtupMonadASTPython \\
  12258. \begin{array}{rcl}
  12259. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12260. \end{array}
  12261. \end{array}
  12262. \]
  12263. \fi}
  12264. \end{tcolorbox}
  12265. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12266. \label{fig:Lvec-anf-syntax}
  12267. \index{subject}{Ltupmon@\LangAllocANF{} abstract syntax}
  12268. \end{figure}
  12269. \section{Explicate Control and the \LangCVec{} Language}
  12270. \label{sec:explicate-control-r3}
  12271. \newcommand{\CtupASTRacket}{
  12272. \begin{array}{lcl}
  12273. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12274. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12275. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12276. &\MID& \VECLEN{\Atm} \\
  12277. &\MID& \GLOBALVALUE{\Var} \\
  12278. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12279. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12280. \end{array}
  12281. }
  12282. \newcommand{\CtupASTPython}{
  12283. \begin{array}{lcl}
  12284. \Atm &::=& \GLOBALVALUE{\Var} \\
  12285. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12286. &\MID& \LEN{\Atm} \\
  12287. \Stmt &::=& \COLLECT{\Int}
  12288. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12289. \end{array}
  12290. }
  12291. \begin{figure}[tp]
  12292. \begin{tcolorbox}[colback=white]
  12293. \small
  12294. {\if\edition\racketEd
  12295. \[
  12296. \begin{array}{l}
  12297. \gray{\CvarASTRacket} \\ \hline
  12298. \gray{\CifASTRacket} \\ \hline
  12299. \gray{\CloopASTRacket} \\ \hline
  12300. \CtupASTRacket \\
  12301. \begin{array}{lcl}
  12302. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12303. \end{array}
  12304. \end{array}
  12305. \]
  12306. \fi}
  12307. {\if\edition\pythonEd\pythonColor
  12308. \[
  12309. \begin{array}{l}
  12310. \gray{\CifASTPython} \\ \hline
  12311. \CtupASTPython \\
  12312. \begin{array}{lcl}
  12313. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12314. \end{array}
  12315. \end{array}
  12316. \]
  12317. \fi}
  12318. \end{tcolorbox}
  12319. \caption{The abstract syntax of \LangCVec{}, extending
  12320. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12321. (figure~\ref{fig:c1-syntax})}.}
  12322. \label{fig:c2-syntax}
  12323. \index{subject}{Cvec@\LangCVec{} abstract syntax}
  12324. \end{figure}
  12325. The output of \code{explicate\_control} is a program in the
  12326. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12327. shows the definition of the abstract syntax.
  12328. %
  12329. %% \racket{(The concrete syntax is defined in
  12330. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12331. %
  12332. The new expressions of \LangCVec{} include \key{allocate},
  12333. %
  12334. \racket{\key{vector-ref}, and \key{vector-set!},}
  12335. %
  12336. \python{accessing tuple elements,}
  12337. %
  12338. and \key{global\_value}.
  12339. %
  12340. \python{\LangCVec{} also includes the \code{collect} statement and
  12341. assignment to a tuple element.}
  12342. %
  12343. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12344. %
  12345. The \code{explicate\_control} pass can treat these new forms much like
  12346. the other forms that we've already encountered. The output of the
  12347. \code{explicate\_control} pass on the running example is shown on the
  12348. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12349. section.
  12350. \section{Select Instructions and the \LangXGlobal{} Language}
  12351. \label{sec:select-instructions-gc}
  12352. \index{subject}{select instructions}
  12353. %% void (rep as zero)
  12354. %% allocate
  12355. %% collect (callq collect)
  12356. %% vector-ref
  12357. %% vector-set!
  12358. %% vector-length
  12359. %% global (postpone)
  12360. In this pass we generate x86 code for most of the new operations that
  12361. are needed to compile tuples, including \code{Allocate},
  12362. \code{Collect}, accessing tuple elements, and the \code{Is}
  12363. comparison.
  12364. %
  12365. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12366. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12367. \ref{fig:x86-2}). \index{subject}{x86}
  12368. The tuple read and write forms translate into \code{movq}
  12369. instructions. (The $+1$ in the offset serves to move past the tag at the
  12370. beginning of the tuple representation.)
  12371. %
  12372. \begin{center}
  12373. \begin{minipage}{\textwidth}
  12374. {\if\edition\racketEd
  12375. \begin{lstlisting}
  12376. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12377. |$\Longrightarrow$|
  12378. movq |$\itm{tup}'$|, %r11
  12379. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12380. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12381. |$\Longrightarrow$|
  12382. movq |$\itm{tup}'$|, %r11
  12383. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12384. movq $0, |$\itm{lhs'}$|
  12385. \end{lstlisting}
  12386. \fi}
  12387. {\if\edition\pythonEd\pythonColor
  12388. \begin{lstlisting}
  12389. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12390. |$\Longrightarrow$|
  12391. movq |$\itm{tup}'$|, %r11
  12392. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12393. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12394. |$\Longrightarrow$|
  12395. movq |$\itm{tup}'$|, %r11
  12396. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12397. \end{lstlisting}
  12398. \fi}
  12399. \end{minipage}
  12400. \end{center}
  12401. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12402. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12403. are obtained by translating from \LangCVec{} to x86.
  12404. %
  12405. The move of $\itm{tup}'$ to
  12406. register \code{r11} ensures that the offset expression
  12407. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12408. removing \code{r11} from consideration by the register allocator.
  12409. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12410. \code{rax}. Then the generated code for tuple assignment would be
  12411. \begin{lstlisting}
  12412. movq |$\itm{tup}'$|, %rax
  12413. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12414. \end{lstlisting}
  12415. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12416. \code{patch\_instructions} would insert a move through \code{rax}
  12417. as follows:
  12418. \begin{lstlisting}
  12419. movq |$\itm{tup}'$|, %rax
  12420. movq |$\itm{rhs}'$|, %rax
  12421. movq %rax, |$8(n+1)$|(%rax)
  12422. \end{lstlisting}
  12423. However, this sequence of instructions does not work because we're
  12424. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12425. $\itm{rhs}'$) at the same time!
  12426. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12427. be translated into a sequence of instructions that read the tag of the
  12428. tuple and extract the 6 bits that represent the tuple length, which
  12429. are the bits starting at index 1 and going up to and including bit 6.
  12430. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12431. (shift right) can be used to accomplish this.
  12432. We compile the \code{allocate} form to operations on the
  12433. \code{free\_ptr}, as shown next. This approach is called
  12434. \emph{inline allocation} because it implements allocation without a
  12435. function call by simply incrementing the allocation pointer. It is much
  12436. more efficient than calling a function for each allocation. The
  12437. address in the \code{free\_ptr} is the next free address in the
  12438. FromSpace, so we copy it into \code{r11} and then move it forward by
  12439. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12440. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12441. the tag. We then initialize the \itm{tag} and finally copy the
  12442. address in \code{r11} to the left-hand side. Refer to
  12443. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12444. %
  12445. \racket{We recommend using the Racket operations
  12446. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12447. during compilation.}
  12448. %
  12449. \python{We recommend using the bitwise-or operator \code{|} and the
  12450. shift-left operator \code{<<} to compute the tag during
  12451. compilation.}
  12452. %
  12453. The type annotation in the \code{allocate} form is used to determine
  12454. the pointer mask region of the tag.
  12455. %
  12456. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12457. address of the \code{free\_ptr} global variable using a special
  12458. instruction-pointer-relative addressing mode of the x86-64 processor.
  12459. In particular, the assembler computes the distance $d$ between the
  12460. address of \code{free\_ptr} and where the \code{rip} would be at that
  12461. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12462. \code{$d$(\%rip)}, which at runtime will compute the address of
  12463. \code{free\_ptr}.
  12464. %
  12465. {\if\edition\racketEd
  12466. \begin{lstlisting}
  12467. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12468. |$\Longrightarrow$|
  12469. movq free_ptr(%rip), %r11
  12470. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12471. movq $|$\itm{tag}$|, 0(%r11)
  12472. movq %r11, |$\itm{lhs}'$|
  12473. \end{lstlisting}
  12474. \fi}
  12475. {\if\edition\pythonEd\pythonColor
  12476. \begin{lstlisting}
  12477. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12478. |$\Longrightarrow$|
  12479. movq free_ptr(%rip), %r11
  12480. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12481. movq $|$\itm{tag}$|, 0(%r11)
  12482. movq %r11, |$\itm{lhs}'$|
  12483. \end{lstlisting}
  12484. \fi}
  12485. %
  12486. The \code{collect} form is compiled to a call to the \code{collect}
  12487. function in the runtime. The arguments to \code{collect} are (1) the
  12488. top of the root stack, and (2) the number of bytes that need to be
  12489. allocated. We use another dedicated register, \code{r15}, to store
  12490. the pointer to the top of the root stack. Therefore \code{r15} is not
  12491. available for use by the register allocator.
  12492. %
  12493. {\if\edition\racketEd
  12494. \begin{lstlisting}
  12495. (collect |$\itm{bytes}$|)
  12496. |$\Longrightarrow$|
  12497. movq %r15, %rdi
  12498. movq $|\itm{bytes}|, %rsi
  12499. callq collect
  12500. \end{lstlisting}
  12501. \fi}
  12502. {\if\edition\pythonEd\pythonColor
  12503. \begin{lstlisting}
  12504. collect(|$\itm{bytes}$|)
  12505. |$\Longrightarrow$|
  12506. movq %r15, %rdi
  12507. movq $|\itm{bytes}|, %rsi
  12508. callq collect
  12509. \end{lstlisting}
  12510. \fi}
  12511. {\if\edition\pythonEd\pythonColor
  12512. The \code{is} comparison is compiled similarly to the other comparison
  12513. operators, using the \code{cmpq} instruction. Because the value of a
  12514. tuple is its address, we can translate \code{is} into a simple check
  12515. for equality using the \code{e} condition code. \\
  12516. \begin{tabular}{lll}
  12517. \begin{minipage}{0.4\textwidth}
  12518. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12519. \end{minipage}
  12520. &
  12521. $\Rightarrow$
  12522. &
  12523. \begin{minipage}{0.4\textwidth}
  12524. \begin{lstlisting}
  12525. cmpq |$\Arg_2$|, |$\Arg_1$|
  12526. sete %al
  12527. movzbq %al, |$\Var$|
  12528. \end{lstlisting}
  12529. \end{minipage}
  12530. \end{tabular}
  12531. \fi}
  12532. \newcommand{\GrammarXGlobal}{
  12533. \begin{array}{lcl}
  12534. \Arg &::=& \itm{label} \key{(\%rip)}
  12535. \end{array}
  12536. }
  12537. \newcommand{\ASTXGlobalRacket}{
  12538. \begin{array}{lcl}
  12539. \Arg &::=& \GLOBAL{\itm{label}}
  12540. \end{array}
  12541. }
  12542. \begin{figure}[tp]
  12543. \begin{tcolorbox}[colback=white]
  12544. {\if\edition\racketEd
  12545. \[
  12546. \begin{array}{l}
  12547. \gray{\GrammarXIntRacket} \\ \hline
  12548. \gray{\GrammarXIfRacket} \\ \hline
  12549. \GrammarXGlobal \\
  12550. \begin{array}{lcl}
  12551. \LangXGlobalM{} &::= & \key{.globl main} \\
  12552. & & \key{main:} \; \Instr^{*}
  12553. \end{array}
  12554. \end{array}
  12555. \]
  12556. \fi}
  12557. {\if\edition\pythonEd\pythonColor
  12558. \[
  12559. \begin{array}{l}
  12560. \gray{\GrammarXIntPython} \\ \hline
  12561. \gray{\GrammarXIfPython} \\ \hline
  12562. \GrammarXGlobal \\
  12563. \begin{array}{lcl}
  12564. \LangXGlobalM{} &::= & \key{.globl main} \\
  12565. & & \key{main:} \; \Instr^{*}
  12566. \end{array}
  12567. \end{array}
  12568. \]
  12569. \fi}
  12570. \end{tcolorbox}
  12571. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12572. \label{fig:x86-2-concrete}
  12573. \end{figure}
  12574. \begin{figure}[tp]
  12575. \begin{tcolorbox}[colback=white]
  12576. \small
  12577. {\if\edition\racketEd
  12578. \[
  12579. \begin{array}{l}
  12580. \gray{\ASTXIntRacket} \\ \hline
  12581. \gray{\ASTXIfRacket} \\ \hline
  12582. \ASTXGlobalRacket \\
  12583. \begin{array}{lcl}
  12584. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12585. \end{array}
  12586. \end{array}
  12587. \]
  12588. \fi}
  12589. {\if\edition\pythonEd\pythonColor
  12590. \[
  12591. \begin{array}{l}
  12592. \gray{\ASTXIntPython} \\ \hline
  12593. \gray{\ASTXIfPython} \\ \hline
  12594. \ASTXGlobalRacket \\
  12595. \begin{array}{lcl}
  12596. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12597. \end{array}
  12598. \end{array}
  12599. \]
  12600. \fi}
  12601. \end{tcolorbox}
  12602. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12603. \label{fig:x86-2}
  12604. \end{figure}
  12605. The definitions of the concrete and abstract syntax of the
  12606. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12607. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12608. of global variables.
  12609. %
  12610. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12611. \code{select\_instructions} pass on the running example.
  12612. \begin{figure}[tbp]
  12613. \centering
  12614. \begin{tcolorbox}[colback=white]
  12615. {\if\edition\racketEd
  12616. % tests/s2_17.rkt
  12617. \begin{tabular}{lll}
  12618. \begin{minipage}{0.5\textwidth}
  12619. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12620. start:
  12621. tmp9 = (global-value free_ptr);
  12622. tmp0 = (+ tmp9 16);
  12623. tmp1 = (global-value fromspace_end);
  12624. if (< tmp0 tmp1)
  12625. goto block0;
  12626. else
  12627. goto block1;
  12628. block0:
  12629. _4 = (void);
  12630. goto block9;
  12631. block1:
  12632. (collect 16)
  12633. goto block9;
  12634. block9:
  12635. alloc2 = (allocate 1 (Vector Integer));
  12636. _3 = (vector-set! alloc2 0 42);
  12637. vecinit6 = alloc2;
  12638. tmp2 = (global-value free_ptr);
  12639. tmp3 = (+ tmp2 16);
  12640. tmp4 = (global-value fromspace_end);
  12641. if (< tmp3 tmp4)
  12642. goto block7;
  12643. else
  12644. goto block8;
  12645. block7:
  12646. _8 = (void);
  12647. goto block6;
  12648. block8:
  12649. (collect 16)
  12650. goto block6;
  12651. block6:
  12652. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12653. _7 = (vector-set! alloc5 0 vecinit6);
  12654. tmp5 = (vector-ref alloc5 0);
  12655. return (vector-ref tmp5 0);
  12656. \end{lstlisting}
  12657. \end{minipage}
  12658. &$\Rightarrow$&
  12659. \begin{minipage}{0.4\textwidth}
  12660. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12661. start:
  12662. movq free_ptr(%rip), tmp9
  12663. movq tmp9, tmp0
  12664. addq $16, tmp0
  12665. movq fromspace_end(%rip), tmp1
  12666. cmpq tmp1, tmp0
  12667. jl block0
  12668. jmp block1
  12669. block0:
  12670. movq $0, _4
  12671. jmp block9
  12672. block1:
  12673. movq %r15, %rdi
  12674. movq $16, %rsi
  12675. callq collect
  12676. jmp block9
  12677. block9:
  12678. movq free_ptr(%rip), %r11
  12679. addq $16, free_ptr(%rip)
  12680. movq $3, 0(%r11)
  12681. movq %r11, alloc2
  12682. movq alloc2, %r11
  12683. movq $42, 8(%r11)
  12684. movq $0, _3
  12685. movq alloc2, vecinit6
  12686. movq free_ptr(%rip), tmp2
  12687. movq tmp2, tmp3
  12688. addq $16, tmp3
  12689. movq fromspace_end(%rip), tmp4
  12690. cmpq tmp4, tmp3
  12691. jl block7
  12692. jmp block8
  12693. block7:
  12694. movq $0, _8
  12695. jmp block6
  12696. block8:
  12697. movq %r15, %rdi
  12698. movq $16, %rsi
  12699. callq collect
  12700. jmp block6
  12701. block6:
  12702. movq free_ptr(%rip), %r11
  12703. addq $16, free_ptr(%rip)
  12704. movq $131, 0(%r11)
  12705. movq %r11, alloc5
  12706. movq alloc5, %r11
  12707. movq vecinit6, 8(%r11)
  12708. movq $0, _7
  12709. movq alloc5, %r11
  12710. movq 8(%r11), tmp5
  12711. movq tmp5, %r11
  12712. movq 8(%r11), %rax
  12713. jmp conclusion
  12714. \end{lstlisting}
  12715. \end{minipage}
  12716. \end{tabular}
  12717. \fi}
  12718. {\if\edition\pythonEd
  12719. % tests/tuple/get_get.py
  12720. \begin{tabular}{lll}
  12721. \begin{minipage}{0.5\textwidth}
  12722. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12723. start:
  12724. init.514 = 42
  12725. tmp.517 = free_ptr
  12726. tmp.518 = (tmp.517 + 16)
  12727. tmp.519 = fromspace_end
  12728. if tmp.518 < tmp.519:
  12729. goto block.529
  12730. else:
  12731. goto block.530
  12732. block.529:
  12733. goto block.528
  12734. block.530:
  12735. collect(16)
  12736. goto block.528
  12737. block.528:
  12738. alloc.513 = allocate(1,tuple[int])
  12739. alloc.513:tuple[int][0] = init.514
  12740. v1 = alloc.513
  12741. init.516 = v1
  12742. tmp.520 = free_ptr
  12743. tmp.521 = (tmp.520 + 16)
  12744. tmp.522 = fromspace_end
  12745. if tmp.521 < tmp.522:
  12746. goto block.526
  12747. else:
  12748. goto block.527
  12749. block.526:
  12750. goto block.525
  12751. block.527:
  12752. collect(16)
  12753. goto block.525
  12754. block.525:
  12755. alloc.515 = allocate(1,tuple[tuple[int]])
  12756. alloc.515:tuple[tuple[int]][0] = init.516
  12757. v2 = alloc.515
  12758. tmp.523 = v2[0]
  12759. tmp.524 = tmp.523[0]
  12760. print(tmp.524)
  12761. return 0
  12762. \end{lstlisting}
  12763. \end{minipage}
  12764. &$\Rightarrow$&
  12765. \begin{minipage}{0.4\textwidth}
  12766. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12767. start:
  12768. movq $42, init.514
  12769. movq free_ptr(%rip), tmp.517
  12770. movq tmp.517, tmp.518
  12771. addq $16, tmp.518
  12772. movq fromspace_end(%rip), tmp.519
  12773. cmpq tmp.519, tmp.518
  12774. jl block.529
  12775. jmp block.530
  12776. block.529:
  12777. jmp block.528
  12778. block.530:
  12779. movq %r15, %rdi
  12780. movq $16, %rsi
  12781. callq collect
  12782. jmp block.528
  12783. block.528:
  12784. movq free_ptr(%rip), %r11
  12785. addq $16, free_ptr(%rip)
  12786. movq $3, 0(%r11)
  12787. movq %r11, alloc.513
  12788. movq alloc.513, %r11
  12789. movq init.514, 8(%r11)
  12790. movq alloc.513, v1
  12791. movq v1, init.516
  12792. movq free_ptr(%rip), tmp.520
  12793. movq tmp.520, tmp.521
  12794. addq $16, tmp.521
  12795. movq fromspace_end(%rip), tmp.522
  12796. cmpq tmp.522, tmp.521
  12797. jl block.526
  12798. jmp block.527
  12799. block.526:
  12800. jmp block.525
  12801. block.527:
  12802. movq %r15, %rdi
  12803. movq $16, %rsi
  12804. callq collect
  12805. jmp block.525
  12806. block.525:
  12807. movq free_ptr(%rip), %r11
  12808. addq $16, free_ptr(%rip)
  12809. movq $131, 0(%r11)
  12810. movq %r11, alloc.515
  12811. movq alloc.515, %r11
  12812. movq init.516, 8(%r11)
  12813. movq alloc.515, v2
  12814. movq v2, %r11
  12815. movq 8(%r11), %r11
  12816. movq %r11, tmp.523
  12817. movq tmp.523, %r11
  12818. movq 8(%r11), %r11
  12819. movq %r11, tmp.524
  12820. movq tmp.524, %rdi
  12821. callq print_int
  12822. movq $0, %rax
  12823. jmp conclusion
  12824. \end{lstlisting}
  12825. \end{minipage}
  12826. \end{tabular}
  12827. \fi}
  12828. \end{tcolorbox}
  12829. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12830. \code{select\_instructions} (\emph{right}) on the running example.}
  12831. \label{fig:select-instr-output-gc}
  12832. \end{figure}
  12833. \clearpage
  12834. \section{Register Allocation}
  12835. \label{sec:reg-alloc-gc}
  12836. \index{subject}{register allocation}
  12837. As discussed previously in this chapter, the garbage collector needs to
  12838. access all the pointers in the root set, that is, all variables that
  12839. are tuples. It will be the responsibility of the register allocator
  12840. to make sure that
  12841. \begin{enumerate}
  12842. \item the root stack is used for spilling tuple-typed variables, and
  12843. \item if a tuple-typed variable is live during a call to the
  12844. collector, it must be spilled to ensure that it is visible to the
  12845. collector.
  12846. \end{enumerate}
  12847. The latter responsibility can be handled during construction of the
  12848. interference graph, by adding interference edges between the call-live
  12849. tuple-typed variables and all the callee-saved registers. (They
  12850. already interfere with the caller-saved registers.)
  12851. %
  12852. \racket{The type information for variables is in the \code{Program}
  12853. form, so we recommend adding another parameter to the
  12854. \code{build\_interference} function to communicate this alist.}
  12855. %
  12856. \python{The type information for variables is generated by the type
  12857. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12858. the \code{CProgram} AST mode. You'll need to propagate that
  12859. information so that it is available in this pass.}
  12860. The spilling of tuple-typed variables to the root stack can be handled
  12861. after graph coloring, in choosing how to assign the colors
  12862. (integers) to registers and stack locations. The
  12863. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12864. changes to also record the number of spills to the root stack.
  12865. % build-interference
  12866. %
  12867. % callq
  12868. % extra parameter for var->type assoc. list
  12869. % update 'program' and 'if'
  12870. % allocate-registers
  12871. % allocate spilled vectors to the rootstack
  12872. % don't change color-graph
  12873. % TODO:
  12874. %\section{Patch Instructions}
  12875. %[mention that global variables are memory references]
  12876. \section{Generate Prelude and Conclusion}
  12877. \label{sec:print-x86-gc}
  12878. \label{sec:prelude-conclusion-x86-gc}
  12879. \index{subject}{prelude}\index{subject}{conclusion}
  12880. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12881. \code{prelude\_and\_conclusion} pass on the running example. In the
  12882. prelude of the \code{main} function, we allocate space
  12883. on the root stack to make room for the spills of tuple-typed
  12884. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12885. taking care that the root stack grows up instead of down. For the
  12886. running example, there was just one spill, so we increment \code{r15}
  12887. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12888. One issue that deserves special care is that there may be a call to
  12889. \code{collect} prior to the initializing assignments for all the
  12890. variables in the root stack. We do not want the garbage collector to
  12891. mistakenly determine that some uninitialized variable is a pointer that
  12892. needs to be followed. Thus, we zero out all locations on the root
  12893. stack in the prelude of \code{main}. In
  12894. figure~\ref{fig:print-x86-output-gc}, the instruction
  12895. %
  12896. \lstinline{movq $0, 0(%r15)}
  12897. %
  12898. is sufficient to accomplish this task because there is only one spill.
  12899. In general, we have to clear as many words as there are spills of
  12900. tuple-typed variables. The garbage collector tests each root to see
  12901. if it is null prior to dereferencing it.
  12902. \begin{figure}[htbp]
  12903. \begin{tcolorbox}[colback=white]
  12904. {\if\edition\racketEd
  12905. \begin{minipage}[t]{0.5\textwidth}
  12906. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12907. .globl main
  12908. main:
  12909. pushq %rbp
  12910. movq %rsp, %rbp
  12911. subq $0, %rsp
  12912. movq $65536, %rdi
  12913. movq $65536, %rsi
  12914. callq initialize
  12915. movq rootstack_begin(%rip), %r15
  12916. movq $0, 0(%r15)
  12917. addq $8, %r15
  12918. jmp start
  12919. conclusion:
  12920. subq $8, %r15
  12921. addq $0, %rsp
  12922. popq %rbp
  12923. retq
  12924. \end{lstlisting}
  12925. \end{minipage}
  12926. \fi}
  12927. {\if\edition\pythonEd
  12928. \begin{minipage}[t]{0.5\textwidth}
  12929. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12930. .globl main
  12931. main:
  12932. pushq %rbp
  12933. movq %rsp, %rbp
  12934. pushq %rbx
  12935. subq $8, %rsp
  12936. movq $65536, %rdi
  12937. movq $16, %rsi
  12938. callq initialize
  12939. movq rootstack_begin(%rip), %r15
  12940. movq $0, 0(%r15)
  12941. addq $8, %r15
  12942. jmp start
  12943. conclusion:
  12944. subq $8, %r15
  12945. addq $8, %rsp
  12946. popq %rbx
  12947. popq %rbp
  12948. retq
  12949. \end{lstlisting}
  12950. \end{minipage}
  12951. \fi}
  12952. \end{tcolorbox}
  12953. \caption{The prelude and conclusion for the running example.}
  12954. \label{fig:print-x86-output-gc}
  12955. \end{figure}
  12956. \begin{figure}[tbp]
  12957. \begin{tcolorbox}[colback=white]
  12958. {\if\edition\racketEd
  12959. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12960. \node (Lvec) at (0,2) {\large \LangVec{}};
  12961. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12962. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12963. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12964. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12965. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12966. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12967. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12968. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12969. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12970. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12971. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12972. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12973. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12974. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12975. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12976. \path[->,bend left=15] (Lvec-4) edge [right] node
  12977. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12978. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12979. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12980. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12981. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12982. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12983. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12984. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12985. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12986. \end{tikzpicture}
  12987. \fi}
  12988. {\if\edition\pythonEd\pythonColor
  12989. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12990. \node (Lvec) at (0,2) {\large \LangVec{}};
  12991. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12992. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12993. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12994. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12995. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12996. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12997. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12998. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12999. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  13000. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  13001. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  13002. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  13003. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  13004. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  13005. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  13006. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  13007. \end{tikzpicture}
  13008. \fi}
  13009. \end{tcolorbox}
  13010. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  13011. \label{fig:Lvec-passes}
  13012. \end{figure}
  13013. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  13014. for the compilation of \LangVec{}.
  13015. \clearpage
  13016. {\if\edition\racketEd
  13017. \section{Challenge: Simple Structures}
  13018. \label{sec:simple-structures}
  13019. \index{subject}{struct}
  13020. \index{subject}{structure}
  13021. The language \LangStruct{} extends \LangVec{} with support for simple
  13022. structures. The definition of its concrete syntax is shown in
  13023. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  13024. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  13025. in Typed Racket is a user-defined data type that contains named fields
  13026. and that is heap allocated\index{subject}{heap allocated},
  13027. similarly to a vector. The following is an
  13028. example of a structure definition, in this case the definition of a
  13029. \code{point} type:
  13030. \begin{lstlisting}
  13031. (struct point ([x : Integer] [y : Integer]) #:mutable)
  13032. \end{lstlisting}
  13033. \newcommand{\LstructGrammarRacket}{
  13034. \begin{array}{lcl}
  13035. \Type &::=& \Var \\
  13036. \Exp &::=& (\Var\;\Exp \ldots)\\
  13037. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  13038. \end{array}
  13039. }
  13040. \newcommand{\LstructASTRacket}{
  13041. \begin{array}{lcl}
  13042. \Type &::=& \VAR{\Var} \\
  13043. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  13044. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  13045. \end{array}
  13046. }
  13047. \begin{figure}[tbp]
  13048. \centering
  13049. \begin{tcolorbox}[colback=white]
  13050. \[
  13051. \begin{array}{l}
  13052. \gray{\LintGrammarRacket{}} \\ \hline
  13053. \gray{\LvarGrammarRacket{}} \\ \hline
  13054. \gray{\LifGrammarRacket{}} \\ \hline
  13055. \gray{\LwhileGrammarRacket} \\ \hline
  13056. \gray{\LtupGrammarRacket} \\ \hline
  13057. \LstructGrammarRacket \\
  13058. \begin{array}{lcl}
  13059. \LangStruct{} &::=& \Def \ldots \; \Exp
  13060. \end{array}
  13061. \end{array}
  13062. \]
  13063. \end{tcolorbox}
  13064. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  13065. (figure~\ref{fig:Lvec-concrete-syntax}).}
  13066. \label{fig:Lstruct-concrete-syntax}
  13067. \index{subject}{Lstruct@\LangStruct{} concrete syntax}
  13068. \end{figure}
  13069. \begin{figure}[tbp]
  13070. \centering
  13071. \begin{tcolorbox}[colback=white]
  13072. \small
  13073. \[
  13074. \begin{array}{l}
  13075. \gray{\LintASTRacket{}} \\ \hline
  13076. \gray{\LvarASTRacket{}} \\ \hline
  13077. \gray{\LifASTRacket{}} \\ \hline
  13078. \gray{\LwhileASTRacket} \\ \hline
  13079. \gray{\LtupASTRacket} \\ \hline
  13080. \LstructASTRacket \\
  13081. \begin{array}{lcl}
  13082. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13083. \end{array}
  13084. \end{array}
  13085. \]
  13086. \end{tcolorbox}
  13087. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  13088. (figure~\ref{fig:Lvec-syntax}).}
  13089. \label{fig:Lstruct-syntax}
  13090. \index{subject}{Lstruct@\LangStruct{} abstract syntax}
  13091. \end{figure}
  13092. An instance of a structure is created using function-call syntax, with
  13093. the name of the structure in the function position, as follows:
  13094. \begin{lstlisting}
  13095. (point 7 12)
  13096. \end{lstlisting}
  13097. Function-call syntax is also used to read a field of a structure. The
  13098. function name is formed by the structure name, a dash, and the field
  13099. name. The following example uses \code{point-x} and \code{point-y} to
  13100. access the \code{x} and \code{y} fields of two point instances:
  13101. \begin{center}
  13102. \begin{lstlisting}
  13103. (let ([pt1 (point 7 12)])
  13104. (let ([pt2 (point 4 3)])
  13105. (+ (- (point-x pt1) (point-x pt2))
  13106. (- (point-y pt1) (point-y pt2)))))
  13107. \end{lstlisting}
  13108. \end{center}
  13109. Similarly, to write to a field of a structure, use its set function,
  13110. whose name starts with \code{set-}, followed by the structure name,
  13111. then a dash, then the field name, and finally with an exclamation
  13112. mark. The following example uses \code{set-point-x!} to change the
  13113. \code{x} field from \code{7} to \code{42}:
  13114. \begin{center}
  13115. \begin{lstlisting}
  13116. (let ([pt (point 7 12)])
  13117. (let ([_ (set-point-x! pt 42)])
  13118. (point-x pt)))
  13119. \end{lstlisting}
  13120. \end{center}
  13121. \begin{exercise}\normalfont\normalsize
  13122. Create a type checker for \LangStruct{} by extending the type
  13123. checker for \LangVec{}. Extend your compiler with support for simple
  13124. structures, compiling \LangStruct{} to x86 assembly code. Create
  13125. five new test cases that use structures, and test your compiler.
  13126. \end{exercise}
  13127. % TODO: create an interpreter for L_struct
  13128. \clearpage
  13129. \fi}
  13130. \section{Challenge: Arrays}
  13131. \label{sec:arrays}
  13132. % TODO mention trapped-error
  13133. In this chapter we have studied tuples, that is, heterogeneous
  13134. sequences of elements whose length is determined at compile time. This
  13135. challenge is also about sequences, but this time the length is
  13136. determined at runtime and all the elements have the same type (they
  13137. are homogeneous). We use the traditional term \emph{array} for this
  13138. latter kind of sequence.
  13139. %
  13140. \racket{
  13141. The Racket language does not distinguish between tuples and arrays;
  13142. they are both represented by vectors. However, Typed Racket
  13143. distinguishes between tuples and arrays: the \code{Vector} type is for
  13144. tuples, and the \code{Vectorof} type is for arrays.}%
  13145. \python{Arrays correspond to the \code{list} type in the Python language.}
  13146. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13147. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13148. presents the definition of the abstract syntax, extending \LangVec{}
  13149. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13150. \racket{\code{make-vector} primitive operator for creating an array,
  13151. whose arguments are the length of the array and an initial value for
  13152. all the elements in the array.}%
  13153. \python{bracket notation for creating an array literal.}
  13154. \racket{The \code{vector-length},
  13155. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13156. for tuples become overloaded for use with arrays.}
  13157. \python{
  13158. The subscript operator becomes overloaded for use with arrays and tuples
  13159. and now may appear on the left-hand side of an assignment.
  13160. Note that the index of the subscript, when applied to an array, may be an
  13161. arbitrary expression and not exclusively a constant integer.
  13162. The \code{len} function is also applicable to arrays.
  13163. }
  13164. %
  13165. We include integer multiplication in \LangArray{} because it is
  13166. useful in many examples involving arrays such as computing the
  13167. inner product of two arrays (figure~\ref{fig:inner_product}).
  13168. \newcommand{\LarrayGrammarRacket}{
  13169. \begin{array}{lcl}
  13170. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13171. \Exp &::=& \CMUL{\Exp}{\Exp}
  13172. \MID \CMAKEVEC{\Exp}{\Exp}
  13173. \end{array}
  13174. }
  13175. \newcommand{\LarrayASTRacket}{
  13176. \begin{array}{lcl}
  13177. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13178. \Exp &::=& \MUL{\Exp}{\Exp}
  13179. \MID \MAKEVEC{\Exp}{\Exp}
  13180. \end{array}
  13181. }
  13182. \newcommand{\LarrayGrammarPython}{
  13183. \begin{array}{lcl}
  13184. \Type &::=& \key{list}\LS\Type\RS \\
  13185. \Exp &::=& \CMUL{\Exp}{\Exp}
  13186. \MID \CGET{\Exp}{\Exp}
  13187. \MID \LS \Exp \code{,} \ldots \RS \\
  13188. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13189. \end{array}
  13190. }
  13191. \newcommand{\LarrayASTPython}{
  13192. \begin{array}{lcl}
  13193. \Type &::=& \key{ListType}\LP\Type\RP \\
  13194. \Exp &::=& \MUL{\Exp}{\Exp}
  13195. \MID \GET{\Exp}{\Exp} \\
  13196. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13197. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13198. \end{array}
  13199. }
  13200. \begin{figure}[tp]
  13201. \centering
  13202. \begin{tcolorbox}[colback=white]
  13203. \small
  13204. {\if\edition\racketEd
  13205. \[
  13206. \begin{array}{l}
  13207. \gray{\LintGrammarRacket{}} \\ \hline
  13208. \gray{\LvarGrammarRacket{}} \\ \hline
  13209. \gray{\LifGrammarRacket{}} \\ \hline
  13210. \gray{\LwhileGrammarRacket} \\ \hline
  13211. \gray{\LtupGrammarRacket} \\ \hline
  13212. \LarrayGrammarRacket \\
  13213. \begin{array}{lcl}
  13214. \LangArray{} &::=& \Exp
  13215. \end{array}
  13216. \end{array}
  13217. \]
  13218. \fi}
  13219. {\if\edition\pythonEd\pythonColor
  13220. \[
  13221. \begin{array}{l}
  13222. \gray{\LintGrammarPython{}} \\ \hline
  13223. \gray{\LvarGrammarPython{}} \\ \hline
  13224. \gray{\LifGrammarPython{}} \\ \hline
  13225. \gray{\LwhileGrammarPython} \\ \hline
  13226. \gray{\LtupGrammarPython} \\ \hline
  13227. \LarrayGrammarPython \\
  13228. \begin{array}{rcl}
  13229. \LangArrayM{} &::=& \Stmt^{*}
  13230. \end{array}
  13231. \end{array}
  13232. \]
  13233. \fi}
  13234. \end{tcolorbox}
  13235. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13236. \label{fig:Lvecof-concrete-syntax}
  13237. \index{subject}{Larray@\LangArray{} concrete syntax}
  13238. \end{figure}
  13239. \begin{figure}[tp]
  13240. \centering
  13241. \begin{tcolorbox}[colback=white]
  13242. \small
  13243. {\if\edition\racketEd
  13244. \[
  13245. \begin{array}{l}
  13246. \gray{\LintASTRacket{}} \\ \hline
  13247. \gray{\LvarASTRacket{}} \\ \hline
  13248. \gray{\LifASTRacket{}} \\ \hline
  13249. \gray{\LwhileASTRacket} \\ \hline
  13250. \gray{\LtupASTRacket} \\ \hline
  13251. \LarrayASTRacket \\
  13252. \begin{array}{lcl}
  13253. \LangArray{} &::=& \Exp
  13254. \end{array}
  13255. \end{array}
  13256. \]
  13257. \fi}
  13258. {\if\edition\pythonEd\pythonColor
  13259. \[
  13260. \begin{array}{l}
  13261. \gray{\LintASTPython{}} \\ \hline
  13262. \gray{\LvarASTPython{}} \\ \hline
  13263. \gray{\LifASTPython{}} \\ \hline
  13264. \gray{\LwhileASTPython} \\ \hline
  13265. \gray{\LtupASTPython} \\ \hline
  13266. \LarrayASTPython \\
  13267. \begin{array}{rcl}
  13268. \LangArrayM{} &::=& \Stmt^{*}
  13269. \end{array}
  13270. \end{array}
  13271. \]
  13272. \fi}
  13273. \end{tcolorbox}
  13274. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13275. \label{fig:Lvecof-syntax}
  13276. \index{subject}{Larray@\LangArray{} abstract syntax}
  13277. \end{figure}
  13278. \begin{figure}[tp]
  13279. \begin{tcolorbox}[colback=white]
  13280. {\if\edition\racketEd
  13281. \begin{lstlisting}
  13282. (let ([A (make-vector 2 2)])
  13283. (let ([B (make-vector 2 3)])
  13284. (let ([i 0])
  13285. (let ([prod 0])
  13286. (begin
  13287. (while (< i (vector-length A))
  13288. (begin
  13289. (set! prod (+ prod (* (vector-ref A i)
  13290. (vector-ref B i))))
  13291. (set! i (+ i 1))))
  13292. prod)))))
  13293. \end{lstlisting}
  13294. \fi}
  13295. {\if\edition\pythonEd\pythonColor
  13296. \begin{lstlisting}
  13297. A = [2, 2]
  13298. B = [3, 3]
  13299. i = 0
  13300. prod = 0
  13301. while i != len(A):
  13302. prod = prod + A[i] * B[i]
  13303. i = i + 1
  13304. print(prod)
  13305. \end{lstlisting}
  13306. \fi}
  13307. \end{tcolorbox}
  13308. \caption{Example program that computes the inner product.}
  13309. \label{fig:inner_product}
  13310. \end{figure}
  13311. {\if\edition\racketEd
  13312. %
  13313. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13314. checker for \LangArray{}. The result type of
  13315. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13316. of the initializing expression. The length expression is required to
  13317. have type \code{Integer}. The type checking of the operators
  13318. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13319. updated to handle the situation in which the vector has type
  13320. \code{Vectorof}. In these cases we translate the operators to their
  13321. \code{vectorof} form so that later passes can easily distinguish
  13322. between operations on tuples versus arrays. We override the
  13323. \code{operator-types} method to provide the type signature for
  13324. multiplication: it takes two integers and returns an integer.
  13325. \fi}
  13326. %
  13327. {\if\edition\pythonEd\pythonColor
  13328. %
  13329. The type checker for \LangArray{} is defined in
  13330. figures~\ref{fig:type-check-Lvecof} and
  13331. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13332. is \code{list[T]}, where \code{T} is the type of the initializing
  13333. expressions. The type checking of the \code{len} function and the
  13334. subscript operator are updated to handle lists. The type checker now
  13335. also handles a subscript on the left-hand side of an assignment.
  13336. Regarding multiplication, it takes two integers and returns an
  13337. integer.
  13338. %
  13339. \fi}
  13340. \begin{figure}[tbp]
  13341. \begin{tcolorbox}[colback=white]
  13342. {\if\edition\racketEd
  13343. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13344. (define type-check-Lvecof-class
  13345. (class type-check-Lvec-class
  13346. (super-new)
  13347. (inherit check-type-equal?)
  13348. (define/override (operator-types)
  13349. (append '((* . ((Integer Integer) . Integer)))
  13350. (super operator-types)))
  13351. (define/override (type-check-exp env)
  13352. (lambda (e)
  13353. (define recur (type-check-exp env))
  13354. (match e
  13355. [(Prim 'make-vector (list e1 e2))
  13356. (define-values (e1^ t1) (recur e1))
  13357. (define-values (e2^ elt-type) (recur e2))
  13358. (define vec-type `(Vectorof ,elt-type))
  13359. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13360. [(Prim 'vector-ref (list e1 e2))
  13361. (define-values (e1^ t1) (recur e1))
  13362. (define-values (e2^ t2) (recur e2))
  13363. (match* (t1 t2)
  13364. [(`(Vectorof ,elt-type) 'Integer)
  13365. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13366. [(other wise) ((super type-check-exp env) e)])]
  13367. [(Prim 'vector-set! (list e1 e2 e3) )
  13368. (define-values (e-vec t-vec) (recur e1))
  13369. (define-values (e2^ t2) (recur e2))
  13370. (define-values (e-arg^ t-arg) (recur e3))
  13371. (match t-vec
  13372. [`(Vectorof ,elt-type)
  13373. (check-type-equal? elt-type t-arg e)
  13374. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13375. [else ((super type-check-exp env) e)])]
  13376. [(Prim 'vector-length (list e1))
  13377. (define-values (e1^ t1) (recur e1))
  13378. (match t1
  13379. [`(Vectorof ,t)
  13380. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13381. [else ((super type-check-exp env) e)])]
  13382. [else ((super type-check-exp env) e)])))
  13383. ))
  13384. (define (type-check-Lvecof p)
  13385. (send (new type-check-Lvecof-class) type-check-program p))
  13386. \end{lstlisting}
  13387. \fi}
  13388. {\if\edition\pythonEd\pythonColor
  13389. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13390. class TypeCheckLarray(TypeCheckLtup):
  13391. def type_check_exp(self, e, env):
  13392. match e:
  13393. case ast.List(es, Load()):
  13394. ts = [self.type_check_exp(e, env) for e in es]
  13395. elt_ty = ts[0]
  13396. for (ty, elt) in zip(ts, es):
  13397. self.check_type_equal(elt_ty, ty, elt)
  13398. e.has_type = ListType(elt_ty)
  13399. return e.has_type
  13400. case Call(Name('len'), [tup]):
  13401. tup_t = self.type_check_exp(tup, env)
  13402. tup.has_type = tup_t
  13403. match tup_t:
  13404. case TupleType(ts):
  13405. return IntType()
  13406. case ListType(ty):
  13407. return IntType()
  13408. case _:
  13409. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13410. case Subscript(tup, index, Load()):
  13411. tup_ty = self.type_check_exp(tup, env)
  13412. tup.has_type = tup_ty
  13413. index_ty = self.type_check_exp(index, env)
  13414. self.check_type_equal(index_ty, IntType(), index)
  13415. match tup_ty:
  13416. case TupleType(ts):
  13417. match index:
  13418. case Constant(i):
  13419. return ts[i]
  13420. case _:
  13421. raise Exception('subscript required constant integer index')
  13422. case ListType(ty):
  13423. return ty
  13424. case _:
  13425. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13426. case BinOp(left, Mult(), right):
  13427. l = self.type_check_exp(left, env)
  13428. self.check_type_equal(l, IntType(), left)
  13429. r = self.type_check_exp(right, env)
  13430. self.check_type_equal(r, IntType(), right)
  13431. return IntType()
  13432. case _:
  13433. return super().type_check_exp(e, env)
  13434. \end{lstlisting}
  13435. \fi}
  13436. \end{tcolorbox}
  13437. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13438. \label{fig:type-check-Lvecof}
  13439. \end{figure}
  13440. {\if\edition\pythonEd
  13441. \begin{figure}[tbp]
  13442. \begin{tcolorbox}[colback=white]
  13443. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13444. def type_check_stmts(self, ss, env):
  13445. if len(ss) == 0:
  13446. return VoidType()
  13447. match ss[0]:
  13448. case Assign([Subscript(tup, index, Store())], value):
  13449. tup_t = self.type_check_exp(tup, env)
  13450. tup.has_type = tup_t
  13451. value_t = self.type_check_exp(value, env)
  13452. index_ty = self.type_check_exp(index, env)
  13453. self.check_type_equal(index_ty, IntType(), index)
  13454. match tup_t:
  13455. case ListType(ty):
  13456. self.check_type_equal(ty, value_t, ss[0])
  13457. case TupleType(ts):
  13458. return self.type_check_stmts(ss, env)
  13459. case _:
  13460. raise Exception('type_check_stmts: '
  13461. 'expected tuple or list, not ' + repr(tup_t))
  13462. return self.type_check_stmts(ss[1:], env)
  13463. case _:
  13464. return super().type_check_stmts(ss, env)
  13465. \end{lstlisting}
  13466. \end{tcolorbox}
  13467. \caption{Type checker for the \LangArray{} language, part 2.}
  13468. \label{fig:type-check-Lvecof-part2}
  13469. \end{figure}
  13470. \fi}
  13471. The definition of the interpreter for \LangArray{} is shown in
  13472. \racket{figure~\ref{fig:interp-Lvecof}}
  13473. \python{figure~\ref{fig:interp-Lvecof}}.
  13474. \racket{The \code{make-vector} operator is
  13475. interpreted using Racket's \code{make-vector} function,
  13476. and multiplication is interpreted using \code{fx*},
  13477. which is multiplication for \code{fixnum} integers.
  13478. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13479. we translate array access operations
  13480. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13481. which we interpret using \code{vector} operations with additional
  13482. bounds checks that signal a \code{trapped-error}.
  13483. }
  13484. %
  13485. \python{We implement array creation with a Python list comprehension,
  13486. and multiplication is implemented with 64-bit multiplication. We
  13487. add a case for a subscript on the left-hand side of
  13488. assignment. Other uses of subscript can be handled by the existing
  13489. code for tuples.}
  13490. \begin{figure}[tbp]
  13491. \begin{tcolorbox}[colback=white]
  13492. {\if\edition\racketEd
  13493. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13494. (define interp-Lvecof-class
  13495. (class interp-Lvec-class
  13496. (super-new)
  13497. (define/override (interp-op op)
  13498. (match op
  13499. ['make-vector make-vector]
  13500. ['vectorof-length vector-length]
  13501. ['vectorof-ref
  13502. (lambda (v i)
  13503. (if (< i (vector-length v))
  13504. (vector-ref v i)
  13505. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13506. ['vectorof-set!
  13507. (lambda (v i e)
  13508. (if (< i (vector-length v))
  13509. (vector-set! v i e)
  13510. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13511. [else (super interp-op op)]))
  13512. ))
  13513. (define (interp-Lvecof p)
  13514. (send (new interp-Lvecof-class) interp-program p))
  13515. \end{lstlisting}
  13516. \fi}
  13517. {\if\edition\pythonEd\pythonColor
  13518. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13519. class InterpLarray(InterpLtup):
  13520. def interp_exp(self, e, env):
  13521. match e:
  13522. case ast.List(es, Load()):
  13523. return [self.interp_exp(e, env) for e in es]
  13524. case BinOp(left, Mult(), right):
  13525. l = self.interp_exp(left, env)
  13526. r = self.interp_exp(right, env)
  13527. return mul64(l, r)
  13528. case Subscript(tup, index, Load()):
  13529. t = self.interp_exp(tup, env)
  13530. n = self.interp_exp(index, env)
  13531. if n < len(t):
  13532. return t[n]
  13533. else:
  13534. raise TrappedError('array index out of bounds')
  13535. case _:
  13536. return super().interp_exp(e, env)
  13537. def interp_stmt(self, s, env, cont):
  13538. match s:
  13539. case Assign([Subscript(tup, index)], value):
  13540. t = self.interp_exp(tup, env)
  13541. n = self.interp_exp(index, env)
  13542. if n < len(t):
  13543. t[n] = self.interp_exp(value, env)
  13544. else:
  13545. raise TrappedError('array index out of bounds')
  13546. return self.interp_stmts(cont, env)
  13547. case _:
  13548. return super().interp_stmt(s, env, cont)
  13549. \end{lstlisting}
  13550. \fi}
  13551. \end{tcolorbox}
  13552. \caption{Interpreter for \LangArray{}.}
  13553. \label{fig:interp-Lvecof}
  13554. \end{figure}
  13555. \subsection{Data Representation}
  13556. \label{sec:array-rep}
  13557. Just as with tuples, we store arrays on the heap, which means that the
  13558. garbage collector will need to inspect arrays. An immediate thought is
  13559. to use the same representation for arrays that we use for tuples.
  13560. However, we limit tuples to a length of fifty so that their length and
  13561. pointer mask can fit into the 64-bit tag at the beginning of each
  13562. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13563. millions of elements, so we need more bits to store the length.
  13564. However, because arrays are homogeneous, we need only 1 bit for the
  13565. pointer mask instead of 1 bit per array element. Finally, the
  13566. garbage collector must be able to distinguish between tuples
  13567. and arrays, so we need to reserve one bit for that purpose. We
  13568. arrive at the following layout for the 64-bit tag at the beginning of
  13569. an array:
  13570. \begin{itemize}
  13571. \item The right-most bit is the forwarding bit, just as in a tuple.
  13572. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13573. that it is not.
  13574. \item The next bit to the left is the pointer mask. A $0$ indicates
  13575. that none of the elements are pointers, and a $1$ indicates that all
  13576. the elements are pointers.
  13577. \item The next $60$ bits store the length of the array.
  13578. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13579. and an array ($1$).
  13580. \item The left-most bit is reserved as explained in
  13581. chapter~\ref{ch:Lgrad}.
  13582. \end{itemize}
  13583. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13584. %% differentiate the kinds of values that have been injected into the
  13585. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13586. %% to indicate that the value is an array.
  13587. In the following subsections we provide hints regarding how to update
  13588. the passes to handle arrays.
  13589. \subsection{Overload Resolution}
  13590. \label{sec:array-resolution}
  13591. As noted previously, with the addition of arrays, several operators
  13592. have become \emph{overloaded}; that is, they can be applied to values
  13593. of more than one type. In this case, the element access and length
  13594. operators can be applied to both tuples and arrays. This kind of
  13595. overloading is quite common in programming languages, so many
  13596. compilers perform \emph{overload resolution}\index{subject}{overload
  13597. resolution} to handle it. The idea is to translate each overloaded
  13598. operator into different operators for the different types.
  13599. Implement a new pass named \code{resolve}.
  13600. Translate the reading of an array element to
  13601. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13602. and the writing of an array element to
  13603. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13604. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13605. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13606. When these operators are applied to tuples, leave them as is.
  13607. %
  13608. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13609. field, which can be inspected to determine whether the operator
  13610. is applied to a tuple or an array.}
  13611. \subsection{Bounds Checking}
  13612. Recall that the interpreter for \LangArray{} signals a
  13613. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13614. when there is an array access that is out of
  13615. bounds. Therefore your compiler is obliged to also catch these errors
  13616. during execution and halt, signaling an error. We recommend inserting
  13617. a new pass named \code{check\_bounds} that inserts code around each
  13618. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13619. \python{subscript} operation to ensure that the index is greater than
  13620. or equal to zero and less than the array's length. If not, the program
  13621. should halt, for which we recommend using a new primitive operation
  13622. named \code{exit}.
  13623. %% \subsection{Reveal Casts}
  13624. %% The array-access operators \code{vectorof-ref} and
  13625. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13626. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13627. %% that the type checker cannot tell whether the index will be in bounds,
  13628. %% so the bounds check must be performed at run time. Recall that the
  13629. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13630. %% an \code{If} around a vector reference for update to check whether
  13631. %% the index is less than the length. You should do the same for
  13632. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13633. %% In addition, the handling of the \code{any-vector} operators in
  13634. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13635. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13636. %% generated code should test whether the tag is for tuples (\code{010})
  13637. %% or arrays (\code{110}) and then dispatch to either
  13638. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13639. %% we add a case in \code{select\_instructions} to generate the
  13640. %% appropriate instructions for accessing the array length from the
  13641. %% header of an array.
  13642. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13643. %% the generated code needs to check that the index is less than the
  13644. %% vector length, so like the code for \code{any-vector-length}, check
  13645. %% the tag to determine whether to use \code{any-vector-length} or
  13646. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13647. %% is complete, the generated code can use \code{any-vector-ref} and
  13648. %% \code{any-vector-set!} for both tuples and arrays because the
  13649. %% instructions used for those operators do not look at the tag at the
  13650. %% front of the tuple or array.
  13651. \subsection{Expose Allocation}
  13652. % TODO: add figure for C_array
  13653. This pass should translate array creation into lower-level
  13654. operations. In particular, the new AST node \ALLOCARRAY{\Int}{\Type}
  13655. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13656. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13657. array. The \code{AllocateArray} AST node allocates an array of the
  13658. length specified by the $\Exp$ (of type \INTTY), but does not
  13659. initialize the elements of the array. Generate code in this pass to
  13660. initialize the elements analogous to the case for tuples.
  13661. {\if\edition\racketEd
  13662. \subsection{Uncover \texttt{get!}}
  13663. \label{sec:uncover-get-bang-vecof}
  13664. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13665. \code{uncover-get!-exp}.
  13666. \fi}
  13667. \subsection{Remove Complex Operands}
  13668. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13669. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13670. complex, and its subexpression must be atomic.
  13671. \subsection{Explicate Control}
  13672. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13673. \code{explicate\_assign}.
  13674. \subsection{Select Instructions}
  13675. \index{subject}{select instructions}
  13676. Generate instructions for \code{AllocateArray} similar to those for
  13677. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13678. except that the tag at the front of the array should instead use the
  13679. representation discussed in section~\ref{sec:array-rep}.
  13680. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13681. extract the length from the tag.
  13682. The instructions generated for accessing an element of an array differ
  13683. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13684. that the index is not a constant so you need to generate instructions
  13685. that compute the offset at runtime.
  13686. Compile the \code{exit} primitive into a call to the \code{exit}
  13687. function of the C standard library, with an argument of $255$.
  13688. %% Also, note that assignment to an array element may appear in
  13689. %% as a stand-alone statement, so make sure to handle that situation in
  13690. %% this pass.
  13691. %% Finally, the instructions for \code{any-vectorof-length} should be
  13692. %% similar to those for \code{vectorof-length}, except that one must
  13693. %% first project the array by writing zeroes into the $3$-bit tag
  13694. \begin{exercise}\normalfont\normalsize
  13695. Implement a compiler for the \LangArray{} language by extending your
  13696. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13697. programs, including the one shown in figure~\ref{fig:inner_product}
  13698. and also a program that multiplies two matrices. Note that although
  13699. matrices are two-dimensional arrays, they can be encoded into
  13700. one-dimensional arrays by laying out each row in the array, one after
  13701. the next.
  13702. \end{exercise}
  13703. {\if\edition\racketEd
  13704. \section{Challenge: Generational Collection}
  13705. The copying collector described in section~\ref{sec:GC} can incur
  13706. significant runtime overhead because the call to \code{collect} takes
  13707. time proportional to all the live data. One way to reduce this
  13708. overhead is to reduce how much data is inspected in each call to
  13709. \code{collect}. In particular, researchers have observed that recently
  13710. allocated data is more likely to become garbage than data that has
  13711. survived one or more previous calls to \code{collect}. This insight
  13712. motivated the creation of \emph{generational garbage collectors}
  13713. \index{subject}{generational garbage collector} that
  13714. (1) segregate data according to its age into two or more generations;
  13715. (2) allocate less space for younger generations, so collecting them is
  13716. faster, and more space for the older generations; and (3) perform
  13717. collection on the younger generations more frequently than on older
  13718. generations~\citep{Wilson:1992fk}.
  13719. For this challenge assignment, the goal is to adapt the copying
  13720. collector implemented in \code{runtime.c} to use two generations, one
  13721. for young data and one for old data. Each generation consists of a
  13722. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13723. \code{collect} function to use the two generations:
  13724. \begin{enumerate}
  13725. \item Copy the young generation's FromSpace to its ToSpace and then
  13726. switch the role of the ToSpace and FromSpace.
  13727. \item If there is enough space for the requested number of bytes in
  13728. the young FromSpace, then return from \code{collect}.
  13729. \item If there is not enough space in the young FromSpace for the
  13730. requested bytes, then move the data from the young generation to the
  13731. old one with the following steps:
  13732. \begin{enumerate}
  13733. \item[a.] If there is enough room in the old FromSpace, copy the young
  13734. FromSpace to the old FromSpace and then return.
  13735. \item[b.] If there is not enough room in the old FromSpace, then collect
  13736. the old generation by copying the old FromSpace to the old ToSpace
  13737. and swap the roles of the old FromSpace and ToSpace.
  13738. \item[c.] If there is enough room now, copy the young FromSpace to the
  13739. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13740. and ToSpace for the old generation. Copy the young FromSpace and
  13741. the old FromSpace into the larger FromSpace for the old
  13742. generation and then return.
  13743. \end{enumerate}
  13744. \end{enumerate}
  13745. We recommend that you generalize the \code{cheney} function so that it
  13746. can be used for all the copies mentioned: between the young FromSpace
  13747. and ToSpace, between the old FromSpace and ToSpace, and between the
  13748. young FromSpace and old FromSpace. This can be accomplished by adding
  13749. parameters to \code{cheney} that replace its use of the global
  13750. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13751. \code{tospace\_begin}, and \code{tospace\_end}.
  13752. Note that the collection of the young generation does not traverse the
  13753. old generation. This introduces a potential problem: there may be
  13754. young data that is reachable only through pointers in the old
  13755. generation. If these pointers are not taken into account, the
  13756. collector could throw away young data that is live! One solution,
  13757. called \emph{pointer recording}, is to maintain a set of all the
  13758. pointers from the old generation into the new generation and consider
  13759. this set as part of the root set. To maintain this set, the compiler
  13760. must insert extra instructions around every \code{vector-set!}. If the
  13761. vector being modified is in the old generation, and if the value being
  13762. written is a pointer into the new generation, then that pointer must
  13763. be added to the set. Also, if the value being overwritten was a
  13764. pointer into the new generation, then that pointer should be removed
  13765. from the set.
  13766. \begin{exercise}\normalfont\normalsize
  13767. Adapt the \code{collect} function in \code{runtime.c} to implement
  13768. generational garbage collection, as outlined in this section.
  13769. Update the code generation for \code{vector-set!} to implement
  13770. pointer recording. Make sure that your new compiler and runtime
  13771. execute without error on your test suite.
  13772. \end{exercise}
  13773. \fi}
  13774. \section{Further Reading}
  13775. \citet{Appel90} describes many data representation approaches
  13776. including the ones used in the compilation of Standard ML.
  13777. There are many alternatives to copying collectors (and their bigger
  13778. siblings, the generational collectors) with regard to garbage
  13779. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13780. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13781. collectors are that allocation is fast (just a comparison and pointer
  13782. increment), there is no fragmentation, cyclic garbage is collected,
  13783. and the time complexity of collection depends only on the amount of
  13784. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13785. main disadvantages of a two-space copying collector is that it uses a
  13786. lot of extra space and takes a long time to perform the copy, though
  13787. these problems are ameliorated in generational collectors.
  13788. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13789. small objects and generate a lot of garbage, so copying and
  13790. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13791. Garbage collection is an active research topic, especially concurrent
  13792. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13793. developing new techniques and revisiting old
  13794. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13795. meet every year at the International Symposium on Memory Management to
  13796. present these findings.
  13797. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13798. \chapter{Functions}
  13799. \label{ch:Lfun}
  13800. \index{subject}{function}
  13801. \setcounter{footnote}{0}
  13802. This chapter studies the compilation of a subset of \racket{Typed
  13803. Racket}\python{Python} in which only top-level function definitions
  13804. are allowed. This kind of function appears in the C programming
  13805. language, and it serves as an important stepping-stone to implementing
  13806. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13807. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13808. \section{The \LangFun{} Language}
  13809. The concrete syntax and abstract syntax for function definitions and
  13810. function application are shown in
  13811. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13812. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13813. with zero or more function definitions. The function names from these
  13814. definitions are in scope for the entire program, including all the
  13815. function definitions, and therefore the ordering of function
  13816. definitions does not matter.
  13817. %
  13818. \python{The abstract syntax for function parameters in
  13819. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13820. consists of a parameter name and its type. This design differs from
  13821. Python's \code{ast} module, which has a more complex structure for
  13822. function parameters to handle keyword parameters,
  13823. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13824. complex Python abstract syntax into the simpler syntax shown in
  13825. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13826. \code{FunctionDef} constructor are for decorators and a type
  13827. comment, neither of which are used by our compiler. We recommend
  13828. replacing them with \code{None} in the \code{shrink} pass.
  13829. }
  13830. %
  13831. The concrete syntax for function application
  13832. \index{subject}{function application}
  13833. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13834. where the first expression
  13835. must evaluate to a function and the remaining expressions are the arguments. The
  13836. abstract syntax for function application is
  13837. $\APPLY{\Exp}{\Exp^*}$.
  13838. %% The syntax for function application does not include an explicit
  13839. %% keyword, which is error prone when using \code{match}. To alleviate
  13840. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13841. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13842. Functions are first-class in the sense that a function pointer
  13843. \index{subject}{function pointer} is data and can be stored in memory or passed
  13844. as a parameter to another function. Thus, there is a function
  13845. type, written
  13846. {\if\edition\racketEd
  13847. \begin{lstlisting}
  13848. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13849. \end{lstlisting}
  13850. \fi}
  13851. {\if\edition\pythonEd\pythonColor
  13852. \begin{lstlisting}
  13853. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13854. \end{lstlisting}
  13855. \fi}
  13856. %
  13857. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13858. through $\Type_n$ and whose return type is $\Type_R$. The main
  13859. limitation of these functions (with respect to
  13860. \racket{Racket}\python{Python} functions) is that they are not
  13861. lexically scoped. That is, the only external entities that can be
  13862. referenced from inside a function body are other globally defined
  13863. functions. The syntax of \LangFun{} prevents function definitions from
  13864. being nested inside each other.
  13865. \newcommand{\LfunGrammarRacket}{
  13866. \begin{array}{lcl}
  13867. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13868. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13869. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13870. \end{array}
  13871. }
  13872. \newcommand{\LfunASTRacket}{
  13873. \begin{array}{lcl}
  13874. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13875. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13876. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13877. \end{array}
  13878. }
  13879. \newcommand{\LfunGrammarPython}{
  13880. \begin{array}{lcl}
  13881. \Type &::=& \key{int}
  13882. \MID \key{bool} \MID \key{void}
  13883. \MID \key{tuple}\LS \Type^+ \RS
  13884. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13885. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13886. \Stmt &::=& \CRETURN{\Exp} \\
  13887. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13888. \end{array}
  13889. }
  13890. \newcommand{\LfunASTPython}{
  13891. \begin{array}{lcl}
  13892. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13893. \MID \key{TupleType}\LS\Type^+\RS\\
  13894. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13895. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13896. \Stmt &::=& \RETURN{\Exp} \\
  13897. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13898. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13899. \end{array}
  13900. }
  13901. \begin{figure}[tp]
  13902. \centering
  13903. \begin{tcolorbox}[colback=white]
  13904. \small
  13905. {\if\edition\racketEd
  13906. \[
  13907. \begin{array}{l}
  13908. \gray{\LintGrammarRacket{}} \\ \hline
  13909. \gray{\LvarGrammarRacket{}} \\ \hline
  13910. \gray{\LifGrammarRacket{}} \\ \hline
  13911. \gray{\LwhileGrammarRacket} \\ \hline
  13912. \gray{\LtupGrammarRacket} \\ \hline
  13913. \LfunGrammarRacket \\
  13914. \begin{array}{lcl}
  13915. \LangFunM{} &::=& \Def \ldots \; \Exp
  13916. \end{array}
  13917. \end{array}
  13918. \]
  13919. \fi}
  13920. {\if\edition\pythonEd\pythonColor
  13921. \[
  13922. \begin{array}{l}
  13923. \gray{\LintGrammarPython{}} \\ \hline
  13924. \gray{\LvarGrammarPython{}} \\ \hline
  13925. \gray{\LifGrammarPython{}} \\ \hline
  13926. \gray{\LwhileGrammarPython} \\ \hline
  13927. \gray{\LtupGrammarPython} \\ \hline
  13928. \LfunGrammarPython \\
  13929. \begin{array}{rcl}
  13930. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13931. \end{array}
  13932. \end{array}
  13933. \]
  13934. \fi}
  13935. \end{tcolorbox}
  13936. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13937. \label{fig:Lfun-concrete-syntax}
  13938. \index{subject}{Lfun@\LangFun{} concrete syntax}
  13939. \end{figure}
  13940. \begin{figure}[tp]
  13941. \centering
  13942. \begin{tcolorbox}[colback=white]
  13943. \small
  13944. {\if\edition\racketEd
  13945. \[
  13946. \begin{array}{l}
  13947. \gray{\LintOpAST} \\ \hline
  13948. \gray{\LvarASTRacket{}} \\ \hline
  13949. \gray{\LifASTRacket{}} \\ \hline
  13950. \gray{\LwhileASTRacket{}} \\ \hline
  13951. \gray{\LtupASTRacket{}} \\ \hline
  13952. \LfunASTRacket \\
  13953. \begin{array}{lcl}
  13954. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13955. \end{array}
  13956. \end{array}
  13957. \]
  13958. \fi}
  13959. {\if\edition\pythonEd\pythonColor
  13960. \[
  13961. \begin{array}{l}
  13962. \gray{\LintASTPython{}} \\ \hline
  13963. \gray{\LvarASTPython{}} \\ \hline
  13964. \gray{\LifASTPython{}} \\ \hline
  13965. \gray{\LwhileASTPython} \\ \hline
  13966. \gray{\LtupASTPython} \\ \hline
  13967. \LfunASTPython \\
  13968. \begin{array}{rcl}
  13969. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13970. \end{array}
  13971. \end{array}
  13972. \]
  13973. \fi}
  13974. \end{tcolorbox}
  13975. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13976. \label{fig:Lfun-syntax}
  13977. \index{subject}{Lfun@\LangFun{} abstract syntax}
  13978. \end{figure}
  13979. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13980. representative example of defining and using functions in \LangFun{}.
  13981. We define a function \code{map} that applies some other function
  13982. \code{f} to both elements of a tuple and returns a new tuple
  13983. containing the results. We also define a function \code{inc}. The
  13984. program applies \code{map} to \code{inc} and
  13985. %
  13986. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13987. %
  13988. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13989. %
  13990. from which we return \code{42}.
  13991. \begin{figure}[tbp]
  13992. \begin{tcolorbox}[colback=white]
  13993. {\if\edition\racketEd
  13994. \begin{lstlisting}
  13995. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13996. : (Vector Integer Integer)
  13997. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13998. (define (inc [x : Integer]) : Integer
  13999. (+ x 1))
  14000. (vector-ref (map inc (vector 0 41)) 1)
  14001. \end{lstlisting}
  14002. \fi}
  14003. {\if\edition\pythonEd\pythonColor
  14004. \begin{lstlisting}
  14005. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  14006. return f(v[0]), f(v[1])
  14007. def inc(x : int) -> int:
  14008. return x + 1
  14009. print(map(inc, (0, 41))[1])
  14010. \end{lstlisting}
  14011. \fi}
  14012. \end{tcolorbox}
  14013. \caption{Example of using functions in \LangFun{}.}
  14014. \label{fig:Lfun-function-example}
  14015. \end{figure}
  14016. The definitional interpreter for \LangFun{} is shown in
  14017. figure~\ref{fig:interp-Lfun}. The case for the
  14018. %
  14019. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14020. %
  14021. AST is responsible for setting up the mutual recursion between the
  14022. top-level function definitions.
  14023. %
  14024. \racket{We use the classic back-patching
  14025. \index{subject}{back-patching} approach that uses mutable variables
  14026. and makes two passes over the function
  14027. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  14028. top-level environment using a mutable cons cell for each function
  14029. definition. Note that the \code{lambda}\index{subject}{lambda} value
  14030. for each function is incomplete; it does not yet include the environment.
  14031. Once the top-level environment has been constructed, we iterate over it and
  14032. update the \code{lambda} values to use the top-level environment.}
  14033. %
  14034. \python{We create a dictionary named \code{env} and fill it in
  14035. by mapping each function name to a new \code{Function} value,
  14036. each of which stores a reference to the \code{env}.
  14037. (We define the class \code{Function} for this purpose.)}
  14038. %
  14039. To interpret a function \racket{application}\python{call}, we match
  14040. the result of the function expression to obtain a function value. We
  14041. then extend the function's environment with the mapping of parameters to
  14042. argument values. Finally, we interpret the body of the function in
  14043. this extended environment.
  14044. \begin{figure}[tp]
  14045. \begin{tcolorbox}[colback=white]
  14046. {\if\edition\racketEd
  14047. \begin{lstlisting}
  14048. (define interp-Lfun-class
  14049. (class interp-Lvec-class
  14050. (super-new)
  14051. (define/override ((interp-exp env) e)
  14052. (define recur (interp-exp env))
  14053. (match e
  14054. [(Apply fun args)
  14055. (define fun-val (recur fun))
  14056. (define arg-vals (for/list ([e args]) (recur e)))
  14057. (match fun-val
  14058. [`(function (,xs ...) ,body ,fun-env)
  14059. (define params-args (for/list ([x xs] [arg arg-vals])
  14060. (cons x (box arg))))
  14061. (define new-env (append params-args fun-env))
  14062. ((interp-exp new-env) body)]
  14063. [else
  14064. (error 'interp-exp "expected function, not ~a" fun-val)])]
  14065. [else ((super interp-exp env) e)]
  14066. ))
  14067. (define/public (interp-def d)
  14068. (match d
  14069. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  14070. (cons f (box `(function ,xs ,body ())))]))
  14071. (define/override (interp-program p)
  14072. (match p
  14073. [(ProgramDefsExp info ds body)
  14074. (let ([top-level (for/list ([d ds]) (interp-def d))])
  14075. (for/list ([f (in-dict-values top-level)])
  14076. (set-box! f (match (unbox f)
  14077. [`(function ,xs ,body ())
  14078. `(function ,xs ,body ,top-level)])))
  14079. ((interp-exp top-level) body))]))
  14080. ))
  14081. (define (interp-Lfun p)
  14082. (send (new interp-Lfun-class) interp-program p))
  14083. \end{lstlisting}
  14084. \fi}
  14085. {\if\edition\pythonEd\pythonColor
  14086. \begin{lstlisting}
  14087. class InterpLfun(InterpLtup):
  14088. def apply_fun(self, fun, args, e):
  14089. match fun:
  14090. case Function(name, xs, body, env):
  14091. new_env = env.copy().update(zip(xs, args))
  14092. return self.interp_stmts(body, new_env)
  14093. case _:
  14094. raise Exception('apply_fun: unexpected: ' + repr(fun))
  14095. def interp_exp(self, e, env):
  14096. match e:
  14097. case Call(Name('input_int'), []):
  14098. return super().interp_exp(e, env)
  14099. case Call(func, args):
  14100. f = self.interp_exp(func, env)
  14101. vs = [self.interp_exp(arg, env) for arg in args]
  14102. return self.apply_fun(f, vs, e)
  14103. case _:
  14104. return super().interp_exp(e, env)
  14105. def interp_stmt(self, s, env, cont):
  14106. match s:
  14107. case Return(value):
  14108. return self.interp_exp(value, env)
  14109. case FunctionDef(name, params, bod, dl, returns, comment):
  14110. if isinstance(params, ast.arguments):
  14111. ps = [p.arg for p in params.args]
  14112. else:
  14113. ps = [x for (x,t) in params]
  14114. env[name] = Function(name, ps, bod, env)
  14115. return self.interp_stmts(cont, env)
  14116. case _:
  14117. return super().interp_stmt(s, env, cont)
  14118. def interp(self, p):
  14119. match p:
  14120. case Module(ss):
  14121. env = {}
  14122. self.interp_stmts(ss, env)
  14123. if 'main' in env.keys():
  14124. self.apply_fun(env['main'], [], None)
  14125. case _:
  14126. raise Exception('interp: unexpected ' + repr(p))
  14127. \end{lstlisting}
  14128. \fi}
  14129. \end{tcolorbox}
  14130. \caption{Interpreter for the \LangFun{} language.}
  14131. \label{fig:interp-Lfun}
  14132. \end{figure}
  14133. %\margincomment{TODO: explain type checker}
  14134. The type checker for \LangFun{} is shown in
  14135. figure~\ref{fig:type-check-Lfun}.
  14136. %
  14137. \python{(We omit the code that parses function parameters into the
  14138. simpler abstract syntax.)}
  14139. %
  14140. Similarly to the interpreter, the case for the
  14141. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14142. %
  14143. AST is responsible for setting up the mutual recursion between the
  14144. top-level function definitions. We begin by creating a mapping
  14145. \code{env} from every function name to its type. We then type check
  14146. the program using this mapping.
  14147. %
  14148. \python{To check a function definition, we copy and extend the
  14149. \code{env} with the parameters of the function. We then type check
  14150. the body of the function and obtain the actual return type
  14151. \code{rt}, which is either the type of the expression in a
  14152. \code{return} statement or the \code{VoidType} if control reaches
  14153. the end of the function without a \code{return} statement. (If
  14154. there are multiple \code{return} statements, the types of their
  14155. expressions must agree.) Finally, we check that the actual return
  14156. type \code{rt} is equal to the declared return type \code{returns}.}
  14157. %
  14158. To check a function \racket{application}\python{call}, we match
  14159. the type of the function expression to a function type and check that
  14160. the types of the argument expressions are equal to the function's
  14161. parameter types. The type of the \racket{application}\python{call} as
  14162. a whole is the return type from the function type.
  14163. \begin{figure}[tp]
  14164. \begin{tcolorbox}[colback=white]
  14165. {\if\edition\racketEd
  14166. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14167. (define type-check-Lfun-class
  14168. (class type-check-Lvec-class
  14169. (super-new)
  14170. (inherit check-type-equal?)
  14171. (define/public (type-check-apply env e es)
  14172. (define-values (e^ ty) ((type-check-exp env) e))
  14173. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14174. ((type-check-exp env) e)))
  14175. (match ty
  14176. [`(,ty^* ... -> ,rt)
  14177. (for ([arg-ty ty*] [param-ty ty^*])
  14178. (check-type-equal? arg-ty param-ty (Apply e es)))
  14179. (values e^ e* rt)]))
  14180. (define/override (type-check-exp env)
  14181. (lambda (e)
  14182. (match e
  14183. [(FunRef f n)
  14184. (values (FunRef f n) (dict-ref env f))]
  14185. [(Apply e es)
  14186. (define-values (e^ es^ rt) (type-check-apply env e es))
  14187. (values (Apply e^ es^) rt)]
  14188. [(Call e es)
  14189. (define-values (e^ es^ rt) (type-check-apply env e es))
  14190. (values (Call e^ es^) rt)]
  14191. [else ((super type-check-exp env) e)])))
  14192. (define/public (type-check-def env)
  14193. (lambda (e)
  14194. (match e
  14195. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14196. (define new-env (append (map cons xs ps) env))
  14197. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14198. (check-type-equal? ty^ rt body)
  14199. (Def f p:t* rt info body^)])))
  14200. (define/public (fun-def-type d)
  14201. (match d
  14202. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14203. (define/override (type-check-program e)
  14204. (match e
  14205. [(ProgramDefsExp info ds body)
  14206. (define env (for/list ([d ds])
  14207. (cons (Def-name d) (fun-def-type d))))
  14208. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14209. (define-values (body^ ty) ((type-check-exp env) body))
  14210. (check-type-equal? ty 'Integer body)
  14211. (ProgramDefsExp info ds^ body^)]))))
  14212. (define (type-check-Lfun p)
  14213. (send (new type-check-Lfun-class) type-check-program p))
  14214. \end{lstlisting}
  14215. \fi}
  14216. {\if\edition\pythonEd\pythonColor
  14217. \begin{lstlisting}
  14218. class TypeCheckLfun(TypeCheckLtup):
  14219. def type_check_exp(self, e, env):
  14220. match e:
  14221. case Call(Name('input_int'), []):
  14222. return super().type_check_exp(e, env)
  14223. case Call(func, args):
  14224. func_t = self.type_check_exp(func, env)
  14225. args_t = [self.type_check_exp(arg, env) for arg in args]
  14226. match func_t:
  14227. case FunctionType(params_t, return_t):
  14228. for (arg_t, param_t) in zip(args_t, params_t):
  14229. check_type_equal(param_t, arg_t, e)
  14230. return return_t
  14231. case _:
  14232. raise Exception('type_check_exp: in call, unexpected ' +
  14233. repr(func_t))
  14234. case _:
  14235. return super().type_check_exp(e, env)
  14236. def type_check_stmts(self, ss, env):
  14237. if len(ss) == 0:
  14238. return VoidType()
  14239. match ss[0]:
  14240. case FunctionDef(name, params, body, dl, returns, comment):
  14241. new_env = env.copy().update(params)
  14242. rt = self.type_check_stmts(body, new_env)
  14243. check_type_equal(returns, rt, ss[0])
  14244. return self.type_check_stmts(ss[1:], env)
  14245. case Return(value):
  14246. return self.type_check_exp(value, env)
  14247. case _:
  14248. return super().type_check_stmts(ss, env)
  14249. def type_check(self, p):
  14250. match p:
  14251. case Module(body):
  14252. env = {}
  14253. for s in body:
  14254. match s:
  14255. case FunctionDef(name, params, bod, dl, returns, comment):
  14256. if name in env:
  14257. raise Exception('type_check: function ' +
  14258. repr(name) + ' defined twice')
  14259. params_t = [t for (x,t) in params]
  14260. env[name] = FunctionType(params_t, returns)
  14261. self.type_check_stmts(body, env)
  14262. case _:
  14263. raise Exception('type_check: unexpected ' + repr(p))
  14264. \end{lstlisting}
  14265. \fi}
  14266. \end{tcolorbox}
  14267. \caption{Type checker for the \LangFun{} language.}
  14268. \label{fig:type-check-Lfun}
  14269. \end{figure}
  14270. \clearpage
  14271. \section{Functions in x86}
  14272. \label{sec:fun-x86}
  14273. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14274. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14275. %% \margincomment{\tiny Talk about the return address on the
  14276. %% stack and what callq and retq does.\\ --Jeremy }
  14277. The x86 architecture provides a few features to support the
  14278. implementation of functions. We have already seen that there are
  14279. labels in x86 so that one can refer to the location of an instruction,
  14280. as is needed for jump instructions. Labels can also be used to mark
  14281. the beginning of the instructions for a function. Going further, we
  14282. can obtain the address of a label by using the \key{leaq}
  14283. instruction. For example, the following puts the address of the
  14284. \code{inc} label into the \code{rbx} register:
  14285. \begin{lstlisting}
  14286. leaq inc(%rip), %rbx
  14287. \end{lstlisting}
  14288. Recall from section~\ref{sec:select-instructions-gc} that
  14289. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14290. addressing.
  14291. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14292. to functions whose locations were given by a label, such as
  14293. \code{read\_int}. To support function calls in this chapter we instead
  14294. jump to functions whose location are given by an address in
  14295. a register; that is, we use \emph{indirect function calls}. The
  14296. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14297. before the register name.\index{subject}{indirect function call}
  14298. \begin{lstlisting}
  14299. callq *%rbx
  14300. \end{lstlisting}
  14301. \subsection{Calling Conventions}
  14302. \label{sec:calling-conventions-fun}
  14303. \index{subject}{calling conventions}
  14304. The \code{callq} instruction provides partial support for implementing
  14305. functions: it pushes the return address on the stack and it jumps to
  14306. the target. However, \code{callq} does not handle
  14307. \begin{enumerate}
  14308. \item parameter passing,
  14309. \item pushing frames on the procedure call stack and popping them off,
  14310. or
  14311. \item determining how registers are shared by different functions.
  14312. \end{enumerate}
  14313. Regarding parameter passing, recall that the x86-64 calling
  14314. convention for Unix-based systems uses the following six registers to
  14315. pass arguments to a function, in the given order:
  14316. \begin{lstlisting}
  14317. rdi rsi rdx rcx r8 r9
  14318. \end{lstlisting}
  14319. If there are more than six arguments, then the calling convention
  14320. mandates using space on the frame of the caller for the rest of the
  14321. arguments. However, to ease the implementation of efficient tail calls
  14322. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14323. arguments.
  14324. %
  14325. The return value of the function is stored in register \code{rax}.
  14326. Regarding frames \index{subject}{frame} and the procedure call stack,
  14327. \index{subject}{procedure call stack} recall from
  14328. section~\ref{sec:x86} that the stack grows down and each function call
  14329. uses a chunk of space on the stack called a frame. The caller sets the
  14330. stack pointer, register \code{rsp}, to the last data item in its
  14331. frame. The callee must not change anything in the caller's frame, that
  14332. is, anything that is at or above the stack pointer. The callee is free
  14333. to use locations that are below the stack pointer.
  14334. Recall that we store variables of tuple type on the root stack. So,
  14335. the prelude\index{subject}{prelude} of a function needs to move the
  14336. root stack pointer \code{r15} up according to the number of variables
  14337. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14338. move the root stack pointer back down. Also, the prelude must
  14339. initialize to \code{0} this frame's slots in the root stack to signal
  14340. to the garbage collector that those slots do not yet contain a valid
  14341. pointer. Otherwise the garbage collector will interpret the garbage
  14342. bits in those slots as memory addresses and try to traverse them,
  14343. causing serious mayhem!
  14344. Regarding the sharing of registers between different functions, recall
  14345. from section~\ref{sec:calling-conventions} that the registers are
  14346. divided into two groups, the caller-saved registers and the
  14347. callee-saved registers. The caller should assume that all the
  14348. caller-saved registers are overwritten with arbitrary values by the
  14349. callee. For that reason we recommend in
  14350. section~\ref{sec:calling-conventions} that variables that are live
  14351. during a function call should not be assigned to caller-saved
  14352. registers.
  14353. On the flip side, if the callee wants to use a callee-saved register,
  14354. the callee must save the contents of those registers on their stack
  14355. frame and then put them back prior to returning to the caller. For
  14356. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14357. the register allocator assigns a variable to a callee-saved register,
  14358. then the prelude of the \code{main} function must save that register
  14359. to the stack and the conclusion of \code{main} must restore it. This
  14360. recommendation now generalizes to all functions.
  14361. Recall that the base pointer, register \code{rbp}, is used as a
  14362. point of reference within a frame, so that each local variable can be
  14363. accessed at a fixed offset from the base pointer
  14364. (section~\ref{sec:x86}).
  14365. %
  14366. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14367. frames.
  14368. \begin{figure}[tbp]
  14369. \centering
  14370. \begin{tcolorbox}[colback=white]
  14371. \begin{tabular}{r|r|l|l} \hline
  14372. Caller View & Callee View & Contents & Frame \\ \hline
  14373. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14374. 0(\key{\%rbp}) & & old \key{rbp} \\
  14375. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14376. \ldots & & \ldots \\
  14377. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14378. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14379. \ldots & & \ldots \\
  14380. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14381. %% & & \\
  14382. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14383. %% & \ldots & \ldots \\
  14384. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14385. \hline
  14386. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14387. & 0(\key{\%rbp}) & old \key{rbp} \\
  14388. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14389. & \ldots & \ldots \\
  14390. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14391. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14392. & \ldots & \ldots \\
  14393. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14394. \end{tabular}
  14395. \end{tcolorbox}
  14396. \caption{Memory layout of caller and callee frames.}
  14397. \label{fig:call-frames}
  14398. \end{figure}
  14399. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14400. %% local variables and for storing the values of callee-saved registers
  14401. %% (we shall refer to all of these collectively as ``locals''), and that
  14402. %% at the beginning of a function we move the stack pointer \code{rsp}
  14403. %% down to make room for them.
  14404. %% We recommend storing the local variables
  14405. %% first and then the callee-saved registers, so that the local variables
  14406. %% can be accessed using \code{rbp} the same as before the addition of
  14407. %% functions.
  14408. %% To make additional room for passing arguments, we shall
  14409. %% move the stack pointer even further down. We count how many stack
  14410. %% arguments are needed for each function call that occurs inside the
  14411. %% body of the function and find their maximum. Adding this number to the
  14412. %% number of locals gives us how much the \code{rsp} should be moved at
  14413. %% the beginning of the function. In preparation for a function call, we
  14414. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14415. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14416. %% so on.
  14417. %% Upon calling the function, the stack arguments are retrieved by the
  14418. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14419. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14420. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14421. %% the layout of the caller and callee frames. Notice how important it is
  14422. %% that we correctly compute the maximum number of arguments needed for
  14423. %% function calls; if that number is too small then the arguments and
  14424. %% local variables will smash into each other!
  14425. \subsection{Efficient Tail Calls}
  14426. \label{sec:tail-call}
  14427. In general, the amount of stack space used by a program is determined
  14428. by the longest chain of nested function calls. That is, if function
  14429. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14430. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14431. large if functions are recursive. However, in some cases we can
  14432. arrange to use only a constant amount of space for a long chain of
  14433. nested function calls.
  14434. A \emph{tail call}\index{subject}{tail call} is a function call that
  14435. happens as the last action in a function body. For example, in the
  14436. following program, the recursive call to \code{tail\_sum} is a tail
  14437. call:
  14438. \begin{center}
  14439. {\if\edition\racketEd
  14440. \begin{lstlisting}
  14441. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14442. (if (eq? n 0)
  14443. r
  14444. (tail_sum (- n 1) (+ n r))))
  14445. (+ (tail_sum 3 0) 36)
  14446. \end{lstlisting}
  14447. \fi}
  14448. {\if\edition\pythonEd\pythonColor
  14449. \begin{lstlisting}
  14450. def tail_sum(n : int, r : int) -> int:
  14451. if n == 0:
  14452. return r
  14453. else:
  14454. return tail_sum(n - 1, n + r)
  14455. print(tail_sum(3, 0) + 36)
  14456. \end{lstlisting}
  14457. \fi}
  14458. \end{center}
  14459. At a tail call, the frame of the caller is no longer needed, so we can
  14460. pop the caller's frame before making the tail
  14461. call. \index{subject}{frame} With this approach, a recursive function
  14462. that makes only tail calls ends up using a constant amount of stack
  14463. space. \racket{Functional languages like Racket rely heavily on
  14464. recursive functions, so the definition of Racket \emph{requires}
  14465. that all tail calls be optimized in this way.}
  14466. Some care is needed with regard to argument passing in tail calls. As
  14467. mentioned, for arguments beyond the sixth, the convention is to use
  14468. space in the caller's frame for passing arguments. However, for a
  14469. tail call we pop the caller's frame and can no longer use it. An
  14470. alternative is to use space in the callee's frame for passing
  14471. arguments. However, this option is also problematic because the caller
  14472. and callee's frames overlap in memory. As we begin to copy the
  14473. arguments from their sources in the caller's frame, the target
  14474. locations in the callee's frame might collide with the sources for
  14475. later arguments! We solve this problem by using the heap instead of
  14476. the stack for passing more than six arguments
  14477. (section~\ref{sec:limit-functions-r4}).
  14478. As mentioned, for a tail call we pop the caller's frame prior to
  14479. making the tail call. The instructions for popping a frame are the
  14480. instructions that we usually place in the conclusion of a
  14481. function. Thus, we also need to place such code immediately before
  14482. each tail call. These instructions include restoring the callee-saved
  14483. registers, so it is fortunate that the argument passing registers are
  14484. all caller-saved registers.
  14485. One note remains regarding which instruction to use to make the tail
  14486. call. When the callee is finished, it should not return to the current
  14487. function but instead return to the function that called the current
  14488. one. Thus, the return address that is already on the stack is the
  14489. right one, and we should not use \key{callq} to make the tail call
  14490. because that would overwrite the return address. Instead we simply use
  14491. the \key{jmp} instruction. As with the indirect function call, we write
  14492. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14493. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14494. jump target because the conclusion can overwrite just about everything
  14495. else.
  14496. \begin{lstlisting}
  14497. jmp *%rax
  14498. \end{lstlisting}
  14499. \section{Shrink \LangFun{}}
  14500. \label{sec:shrink-r4}
  14501. The \code{shrink} pass performs a minor modification to ease the
  14502. later passes. This pass introduces an explicit \code{main} function
  14503. that gobbles up all the top-level statements of the module.
  14504. %
  14505. \racket{It also changes the top \code{ProgramDefsExp} form to
  14506. \code{ProgramDefs}.}
  14507. {\if\edition\racketEd
  14508. \begin{lstlisting}
  14509. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14510. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14511. \end{lstlisting}
  14512. where $\itm{mainDef}$ is
  14513. \begin{lstlisting}
  14514. (Def 'main '() 'Integer '() |$\Exp'$|)
  14515. \end{lstlisting}
  14516. \fi}
  14517. {\if\edition\pythonEd\pythonColor
  14518. \begin{lstlisting}
  14519. Module(|$\Def\ldots\Stmt\ldots$|)
  14520. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14521. \end{lstlisting}
  14522. where $\itm{mainDef}$ is
  14523. \begin{lstlisting}
  14524. FunctionDef('main', [], |$\Stmt\ldots$|Return(Constant(0)), None, IntType(), None)
  14525. \end{lstlisting}
  14526. \fi}
  14527. \section{Reveal Functions and the \LangFunRef{} Language}
  14528. \label{sec:reveal-functions-r4}
  14529. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14530. in that it conflates the use of function names and local
  14531. variables. This is a problem because we need to compile the use of a
  14532. function name differently from the use of a local variable. In
  14533. particular, we use \code{leaq} to convert the function name (a label
  14534. in x86) to an address in a register. Thus, we create a new pass that
  14535. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14536. $n$ is the arity of the function.\python{\footnote{The arity is not
  14537. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14538. This pass is named \code{reveal\_functions} and the output language
  14539. is \LangFunRef{}\index{subject}{Lfunref@\LangFunRef{}}.
  14540. %is defined in figure~\ref{fig:f1-syntax}.
  14541. %% The concrete syntax for a
  14542. %% function reference is $\CFUNREF{f}$.
  14543. %% \begin{figure}[tp]
  14544. %% \centering
  14545. %% \fbox{
  14546. %% \begin{minipage}{0.96\textwidth}
  14547. %% {\if\edition\racketEd
  14548. %% \[
  14549. %% \begin{array}{lcl}
  14550. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14551. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14552. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14553. %% \end{array}
  14554. %% \]
  14555. %% \fi}
  14556. %% {\if\edition\pythonEd\pythonColor
  14557. %% \[
  14558. %% \begin{array}{lcl}
  14559. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14560. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14561. %% \end{array}
  14562. %% \]
  14563. %% \fi}
  14564. %% \end{minipage}
  14565. %% }
  14566. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14567. %% (figure~\ref{fig:Lfun-syntax}).}
  14568. %% \label{fig:f1-syntax}
  14569. %% \end{figure}
  14570. %% Distinguishing between calls in tail position and non-tail position
  14571. %% requires the pass to have some notion of context. We recommend using
  14572. %% two mutually recursive functions, one for processing expressions in
  14573. %% tail position and another for the rest.
  14574. \racket{Placing this pass after \code{uniquify} will make sure that
  14575. there are no local variables and functions that share the same
  14576. name.}
  14577. %
  14578. The \code{reveal\_functions} pass should come before the
  14579. \code{remove\_complex\_operands} pass because function references
  14580. should be categorized as complex expressions.
  14581. \section{Limit Functions}
  14582. \label{sec:limit-functions-r4}
  14583. Recall that we wish to limit the number of function parameters to six
  14584. so that we do not need to use the stack for argument passing, which
  14585. makes it easier to implement efficient tail calls. However, because
  14586. the input language \LangFun{} supports arbitrary numbers of function
  14587. arguments, we have some work to do! The \code{limit\_functions} pass
  14588. transforms functions and function calls that involve more than six
  14589. arguments to pass the first five arguments as usual, but it packs the
  14590. rest of the arguments into a tuple and passes it as the sixth
  14591. argument.\footnote{The implementation this pass can be postponed to
  14592. last because you can test the rest of the passes on functions with
  14593. six or fewer parameters.}
  14594. Each function definition with seven or more parameters is transformed as
  14595. follows:
  14596. {\if\edition\racketEd
  14597. \begin{lstlisting}
  14598. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14599. |$\Rightarrow$|
  14600. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14601. \end{lstlisting}
  14602. \fi}
  14603. {\if\edition\pythonEd\pythonColor
  14604. \begin{lstlisting}
  14605. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14606. |$\Rightarrow$|
  14607. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14608. |$T_r$|, None, |$\itm{body}'$|, None)
  14609. \end{lstlisting}
  14610. \fi}
  14611. %
  14612. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14613. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14614. the $k$th element of the tuple, where $k = i - 6$.
  14615. %
  14616. {\if\edition\racketEd
  14617. \begin{lstlisting}
  14618. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14619. \end{lstlisting}
  14620. \fi}
  14621. {\if\edition\pythonEd\pythonColor
  14622. \begin{lstlisting}
  14623. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14624. \end{lstlisting}
  14625. \fi}
  14626. For function calls with too many arguments, the \code{limit\_functions}
  14627. pass transforms them in the following way:
  14628. \begin{tabular}{lll}
  14629. \begin{minipage}{0.3\textwidth}
  14630. {\if\edition\racketEd
  14631. \begin{lstlisting}
  14632. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14633. \end{lstlisting}
  14634. \fi}
  14635. {\if\edition\pythonEd\pythonColor
  14636. \begin{lstlisting}
  14637. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14638. \end{lstlisting}
  14639. \fi}
  14640. \end{minipage}
  14641. &
  14642. $\Rightarrow$
  14643. &
  14644. \begin{minipage}{0.5\textwidth}
  14645. {\if\edition\racketEd
  14646. \begin{lstlisting}
  14647. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14648. \end{lstlisting}
  14649. \fi}
  14650. {\if\edition\pythonEd\pythonColor
  14651. \begin{lstlisting}
  14652. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14653. \end{lstlisting}
  14654. \fi}
  14655. \end{minipage}
  14656. \end{tabular}
  14657. \section{Remove Complex Operands}
  14658. \label{sec:rco-r4}
  14659. The primary decisions to make for this pass are whether to classify
  14660. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14661. atomic or complex expressions. Recall that an atomic expression
  14662. ends up as an immediate argument of an x86 instruction. Function
  14663. application translates to a sequence of instructions, so
  14664. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14665. a complex expression. On the other hand, the arguments of
  14666. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14667. expressions.
  14668. %
  14669. Regarding \code{FunRef}, as discussed previously, the function label
  14670. needs to be converted to an address using the \code{leaq}
  14671. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14672. needs to be classified as a complex expression so that we generate an
  14673. assignment statement with a left-hand side that can serve as the
  14674. target of the \code{leaq}.
  14675. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14676. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14677. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14678. and augments programs to include a list of function definitions.
  14679. %
  14680. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14681. \newcommand{\LfunMonadASTRacket}{
  14682. \begin{array}{lcl}
  14683. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14684. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14685. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14686. \end{array}
  14687. }
  14688. \newcommand{\LfunMonadASTPython}{
  14689. \begin{array}{lcl}
  14690. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14691. \MID \key{TupleType}\LS\Type^+\RS\\
  14692. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14693. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14694. \Stmt &::=& \RETURN{\Exp} \\
  14695. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14696. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14697. \end{array}
  14698. }
  14699. \begin{figure}[tp]
  14700. \centering
  14701. \begin{tcolorbox}[colback=white]
  14702. \footnotesize
  14703. {\if\edition\racketEd
  14704. \[
  14705. \begin{array}{l}
  14706. \gray{\LvarMonadASTRacket} \\ \hline
  14707. \gray{\LifMonadASTRacket} \\ \hline
  14708. \gray{\LwhileMonadASTRacket} \\ \hline
  14709. \gray{\LtupMonadASTRacket} \\ \hline
  14710. \LfunMonadASTRacket \\
  14711. \begin{array}{rcl}
  14712. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14713. \end{array}
  14714. \end{array}
  14715. \]
  14716. \fi}
  14717. {\if\edition\pythonEd\pythonColor
  14718. \[
  14719. \begin{array}{l}
  14720. \gray{\LvarMonadASTPython} \\ \hline
  14721. \gray{\LifMonadASTPython} \\ \hline
  14722. \gray{\LwhileMonadASTPython} \\ \hline
  14723. \gray{\LtupMonadASTPython} \\ \hline
  14724. \LfunMonadASTPython \\
  14725. \begin{array}{rcl}
  14726. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14727. \end{array}
  14728. \end{array}
  14729. \]
  14730. \fi}
  14731. \end{tcolorbox}
  14732. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14733. \label{fig:Lfun-anf-syntax}
  14734. \index{subject}{Lfunmon@\LangFunANF{} abstract syntax}
  14735. \end{figure}
  14736. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14737. %% \LangFunANF{} of this pass.
  14738. %% \begin{figure}[tp]
  14739. %% \centering
  14740. %% \fbox{
  14741. %% \begin{minipage}{0.96\textwidth}
  14742. %% \small
  14743. %% \[
  14744. %% \begin{array}{rcl}
  14745. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14746. %% \MID \VOID{} } \\
  14747. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14748. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14749. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14750. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14751. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14752. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14753. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14754. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14755. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14756. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14757. %% \end{array}
  14758. %% \]
  14759. %% \end{minipage}
  14760. %% }
  14761. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14762. %% \label{fig:Lfun-anf-syntax}
  14763. %% \end{figure}
  14764. \section{Explicate Control and the \LangCFun{} Language}
  14765. \label{sec:explicate-control-r4}
  14766. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14767. output of \code{explicate\_control}.
  14768. %
  14769. %% \racket{(The concrete syntax is given in
  14770. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14771. %
  14772. \racket{The auxiliary functions for assignment and tail contexts should
  14773. be updated with cases for \code{Apply} and \code{FunRef}.}
  14774. The auxiliary function for predicate context should be updated for
  14775. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14776. \code{FunRef} cannot be a Boolean.)
  14777. %
  14778. \racket{In assignment and predicate contexts,
  14779. \code{Apply} becomes \code{Call}, whereas
  14780. in tail position \code{Apply} becomes \code{TailCall}.}
  14781. %
  14782. We recommend defining a new auxiliary function for processing function
  14783. definitions. This code is similar to the case for \code{Program} in
  14784. \LangVecANF{}. The top-level \code{explicate\_control} function that
  14785. handles the \code{ProgramDefs} form of \LangFunANF{} can apply this
  14786. new function to all function definitions.
  14787. {\if\edition\pythonEd\pythonColor
  14788. The translation of \code{Return} statements requires a new auxiliary
  14789. function to handle expressions in tail context, called
  14790. \code{explicate\_tail}. The function should take an expression and the
  14791. dictionary of basic blocks and produce a list of statements in the
  14792. \LangCFun{} language. The \code{explicate\_tail} function should
  14793. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14794. and a default case for other kinds of expressions. The default case
  14795. should produce a \code{Return} statement. The case for \code{Call}
  14796. should change it into \code{TailCall}. The other cases should
  14797. recursively process their subexpressions and statements, choosing the
  14798. appropriate explicate functions for the various contexts.
  14799. \fi}
  14800. \newcommand{\CfunASTRacket}{
  14801. \begin{array}{lcl}
  14802. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14803. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14804. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14805. \end{array}
  14806. }
  14807. \newcommand{\CfunASTPython}{
  14808. \begin{array}{lcl}
  14809. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14810. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14811. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14812. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14813. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14814. \end{array}
  14815. }
  14816. \begin{figure}[tp]
  14817. \begin{tcolorbox}[colback=white]
  14818. \footnotesize
  14819. {\if\edition\racketEd
  14820. \[
  14821. \begin{array}{l}
  14822. \gray{\CvarASTRacket} \\ \hline
  14823. \gray{\CifASTRacket} \\ \hline
  14824. \gray{\CloopASTRacket} \\ \hline
  14825. \gray{\CtupASTRacket} \\ \hline
  14826. \CfunASTRacket \\
  14827. \begin{array}{lcl}
  14828. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14829. \end{array}
  14830. \end{array}
  14831. \]
  14832. \fi}
  14833. {\if\edition\pythonEd\pythonColor
  14834. \[
  14835. \begin{array}{l}
  14836. \gray{\CifASTPython} \\ \hline
  14837. \gray{\CtupASTPython} \\ \hline
  14838. \CfunASTPython \\
  14839. \begin{array}{lcl}
  14840. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14841. \end{array}
  14842. \end{array}
  14843. \]
  14844. \fi}
  14845. \end{tcolorbox}
  14846. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14847. \label{fig:c3-syntax}
  14848. \index{subject}{Cfun@\LangCFun{} abstract syntax}
  14849. \end{figure}
  14850. \clearpage
  14851. \section{Select Instructions and the \LangXIndCall{} Language}
  14852. \label{sec:select-r4}
  14853. \index{subject}{select instructions}
  14854. The output of select instructions is a program in the \LangXIndCall{}
  14855. language; the definition of its concrete syntax is shown in
  14856. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14857. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14858. directive on the labels of function definitions to make sure the
  14859. bottom three bits are zero, which we put to use in
  14860. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14861. this section. \index{subject}{x86}
  14862. \newcommand{\GrammarXIndCall}{
  14863. \begin{array}{lcl}
  14864. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14865. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14866. \Block &::= & \Instr^{+} \\
  14867. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14868. \end{array}
  14869. }
  14870. \newcommand{\ASTXIndCallRacket}{
  14871. \begin{array}{lcl}
  14872. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14873. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14874. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14875. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14876. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14877. \end{array}
  14878. }
  14879. \begin{figure}[tp]
  14880. \begin{tcolorbox}[colback=white]
  14881. \small
  14882. {\if\edition\racketEd
  14883. \[
  14884. \begin{array}{l}
  14885. \gray{\GrammarXIntRacket} \\ \hline
  14886. \gray{\GrammarXIfRacket} \\ \hline
  14887. \gray{\GrammarXGlobal} \\ \hline
  14888. \GrammarXIndCall \\
  14889. \begin{array}{lcl}
  14890. \LangXIndCallM{} &::= & \Def^{*}
  14891. \end{array}
  14892. \end{array}
  14893. \]
  14894. \fi}
  14895. {\if\edition\pythonEd
  14896. \[
  14897. \begin{array}{l}
  14898. \gray{\GrammarXIntPython} \\ \hline
  14899. \gray{\GrammarXIfPython} \\ \hline
  14900. \gray{\GrammarXGlobal} \\ \hline
  14901. \GrammarXIndCall \\
  14902. \begin{array}{lcl}
  14903. \LangXIndCallM{} &::= & \Def^{*}
  14904. \end{array}
  14905. \end{array}
  14906. \]
  14907. \fi}
  14908. \end{tcolorbox}
  14909. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14910. \label{fig:x86-3-concrete}
  14911. \end{figure}
  14912. \begin{figure}[tp]
  14913. \begin{tcolorbox}[colback=white]
  14914. \small
  14915. {\if\edition\racketEd
  14916. \[\arraycolsep=3pt
  14917. \begin{array}{l}
  14918. \gray{\ASTXIntRacket} \\ \hline
  14919. \gray{\ASTXIfRacket} \\ \hline
  14920. \gray{\ASTXGlobalRacket} \\ \hline
  14921. \ASTXIndCallRacket \\
  14922. \begin{array}{lcl}
  14923. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14924. \end{array}
  14925. \end{array}
  14926. \]
  14927. \fi}
  14928. {\if\edition\pythonEd\pythonColor
  14929. \[
  14930. \begin{array}{lcl}
  14931. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14932. \MID \BYTEREG{\Reg} } \\
  14933. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14934. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14935. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14936. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14937. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14938. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14939. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14940. \end{array}
  14941. \]
  14942. \fi}
  14943. \end{tcolorbox}
  14944. \caption{The abstract syntax of \LangXIndCall{} (extends
  14945. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14946. \label{fig:x86-3}
  14947. \end{figure}
  14948. An assignment of a function reference to a variable becomes a
  14949. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14950. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14951. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14952. node, whose concrete syntax is instruction-pointer-relative
  14953. addressing.
  14954. \begin{center}
  14955. \begin{tabular}{lcl}
  14956. \begin{minipage}{0.35\textwidth}
  14957. {\if\edition\racketEd
  14958. \begin{lstlisting}
  14959. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14960. \end{lstlisting}
  14961. \fi}
  14962. {\if\edition\pythonEd\pythonColor
  14963. \begin{lstlisting}
  14964. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14965. \end{lstlisting}
  14966. \fi}
  14967. \end{minipage}
  14968. &
  14969. $\Rightarrow$\qquad\qquad
  14970. &
  14971. \begin{minipage}{0.3\textwidth}
  14972. \begin{lstlisting}
  14973. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14974. \end{lstlisting}
  14975. \end{minipage}
  14976. \end{tabular}
  14977. \end{center}
  14978. Regarding function definitions, we need to remove the parameters and
  14979. instead perform parameter passing using the conventions discussed in
  14980. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14981. registers. We recommend turning the parameters into local variables
  14982. and generating instructions at the beginning of the function to move
  14983. from the argument-passing registers
  14984. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14985. {\if\edition\racketEd
  14986. \begin{lstlisting}
  14987. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14988. |$\Rightarrow$|
  14989. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14990. \end{lstlisting}
  14991. \fi}
  14992. {\if\edition\pythonEd\pythonColor
  14993. \begin{lstlisting}
  14994. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14995. |$\Rightarrow$|
  14996. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14997. \end{lstlisting}
  14998. \fi}
  14999. The basic blocks $B'$ are the same as $B$ except that the
  15000. \code{start} block is modified to add the instructions for moving from
  15001. the argument registers to the parameter variables. So the \code{start}
  15002. block of $B$ shown on the left of the following is changed to the code
  15003. on the right:
  15004. \begin{center}
  15005. \begin{minipage}{0.3\textwidth}
  15006. \begin{lstlisting}
  15007. start:
  15008. |$\itm{instr}_1$|
  15009. |$\cdots$|
  15010. |$\itm{instr}_n$|
  15011. \end{lstlisting}
  15012. \end{minipage}
  15013. $\Rightarrow$
  15014. \begin{minipage}{0.3\textwidth}
  15015. \begin{lstlisting}
  15016. |$f$|start:
  15017. movq %rdi, |$x_1$|
  15018. movq %rsi, |$x_2$|
  15019. |$\cdots$|
  15020. |$\itm{instr}_1$|
  15021. |$\cdots$|
  15022. |$\itm{instr}_n$|
  15023. \end{lstlisting}
  15024. \end{minipage}
  15025. \end{center}
  15026. Recall that we use the label \code{start} for the initial block of a
  15027. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  15028. the conclusion of the program with \code{conclusion}, so that
  15029. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  15030. by a jump to \code{conclusion}. With the addition of function
  15031. definitions, there is a start block and conclusion for each function,
  15032. but their labels need to be unique. We recommend prepending the
  15033. function's name to \code{start} and \code{conclusion}, respectively,
  15034. to obtain unique labels.
  15035. \racket{The interpreter for \LangXIndCall{} needs to be given the
  15036. number of parameters the function expects, but the parameters are no
  15037. longer in the syntax of function definitions. Instead, add an entry
  15038. to $\itm{info}$ that maps \code{num-params} to the number of
  15039. parameters to construct $\itm{info}'$.}
  15040. By changing the parameters to local variables, we are giving the
  15041. register allocator control over which registers or stack locations to
  15042. use for them. If you implement the move-biasing challenge
  15043. (section~\ref{sec:move-biasing}), the register allocator will try to
  15044. assign the parameter variables to the corresponding argument register,
  15045. in which case the \code{patch\_instructions} pass will remove the
  15046. \code{movq} instruction. This happens in the example translation given
  15047. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  15048. the \code{add} function.
  15049. %
  15050. Also, note that the register allocator will perform liveness analysis
  15051. on this sequence of move instructions and build the interference
  15052. graph. So, for example, $x_1$ will be marked as interfering with
  15053. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  15054. which is good because otherwise the first \code{movq} would overwrite
  15055. the argument in \code{rsi} that is needed for $x_2$.
  15056. Next, consider the compilation of function calls. In the mirror image
  15057. of the handling of parameters in function definitions, the arguments
  15058. are moved to the argument-passing registers. Note that the function
  15059. is not given as a label, but its address is produced by the argument
  15060. $\itm{arg}_0$. So, we translate the call into an indirect function
  15061. call. The return value from the function is stored in \code{rax}, so
  15062. it needs to be moved into the \itm{lhs}.
  15063. \begin{lstlisting}
  15064. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  15065. |$\Rightarrow$|
  15066. movq |$\itm{arg}_1$|, %rdi
  15067. movq |$\itm{arg}_2$|, %rsi
  15068. |$\vdots$|
  15069. callq *|$\itm{arg}_0$|
  15070. movq %rax, |$\itm{lhs}$|
  15071. \end{lstlisting}
  15072. The \code{IndirectCallq} AST node includes an integer for the arity of
  15073. the function, that is, the number of parameters. That information is
  15074. useful in the \code{uncover\_live} pass for determining which
  15075. argument-passing registers are potentially read during the call.
  15076. For tail calls, the parameter passing is the same as non-tail calls:
  15077. generate instructions to move the arguments into the argument-passing
  15078. registers. After that we need to pop the frame from the procedure
  15079. call stack. However, we do not yet know how big the frame is; that
  15080. gets determined during register allocation. So, instead of generating
  15081. those instructions here, we invent a new instruction that means ``pop
  15082. the frame and then do an indirect jump,'' which we name
  15083. \code{TailJmp}. The abstract syntax for this instruction includes an
  15084. argument that specifies where to jump and an integer that represents
  15085. the arity of the function being called.
  15086. \section{Register Allocation}
  15087. \label{sec:register-allocation-r4}
  15088. The addition of functions requires some changes to all three aspects
  15089. of register allocation, which we discuss in the following subsections.
  15090. \subsection{Liveness Analysis}
  15091. \label{sec:liveness-analysis-r4}
  15092. \index{subject}{liveness analysis}
  15093. %% The rest of the passes need only minor modifications to handle the new
  15094. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  15095. %% \code{leaq}.
  15096. The \code{IndirectCallq} instruction should be treated like
  15097. \code{Callq} regarding its written locations $W$, in that they should
  15098. include all the caller-saved registers. Recall that the reason for
  15099. that is to force variables that are live across a function call to be assigned to callee-saved
  15100. registers or to be spilled to the stack.
  15101. Regarding the set of read locations $R$, the arity fields of
  15102. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  15103. argument-passing registers should be considered as read by those
  15104. instructions. Also, the target field of \code{TailJmp} and
  15105. \code{IndirectCallq} should be included in the set of read locations
  15106. $R$.
  15107. \subsection{Build Interference Graph}
  15108. \label{sec:build-interference-r4}
  15109. With the addition of function definitions, we compute a separate interference
  15110. graph for each function (not just one for the whole program).
  15111. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  15112. spill tuple-typed variables that are live during a call to
  15113. \code{collect}, the garbage collector. With the addition of functions
  15114. to our language, we need to revisit this issue. Functions that perform
  15115. allocation contain calls to the collector. Thus, we should not only
  15116. spill a tuple-typed variable when it is live during a call to
  15117. \code{collect}, but we should spill the variable if it is live during
  15118. a call to any user-defined function. Thus, in the
  15119. \code{build\_interference} pass, we recommend adding interference
  15120. edges between call-live tuple-typed variables and the callee-saved
  15121. registers (in addition to creating edges between
  15122. call-live variables and the caller-saved registers).
  15123. \subsection{Allocate Registers}
  15124. The primary change to the \code{allocate\_registers} pass is adding an
  15125. auxiliary function for handling definitions (the \Def{} nonterminal
  15126. shown in figure~\ref{fig:x86-3}) with one case for function
  15127. definitions. The logic is the same as described in
  15128. chapter~\ref{ch:register-allocation-Lvar} except that now register
  15129. allocation is performed many times, once for each function definition,
  15130. instead of just once for the whole program.
  15131. \section{Patch Instructions}
  15132. In \code{patch\_instructions}, you should deal with the x86
  15133. idiosyncrasy that the destination argument of \code{leaq} must be a
  15134. register. Additionally, you should ensure that the argument of
  15135. \code{TailJmp} is \itm{rax}, our reserved register---because we
  15136. trample many other registers before the tail call, as explained in the
  15137. next section.
  15138. \section{Generate Prelude and Conclusion}
  15139. Now that register allocation is complete, we can translate the
  15140. \code{TailJmp} into a sequence of instructions. A naive translation of
  15141. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15142. before the jump we need to pop the current frame to achieve efficient
  15143. tail calls. This sequence of instructions is the same as the code for
  15144. the conclusion of a function, except that the \code{retq} is replaced with
  15145. \code{jmp *$\itm{arg}$}.
  15146. Regarding function definitions, we generate a prelude and conclusion
  15147. for each one. This code is similar to the prelude and conclusion
  15148. generated for the \code{main} function presented in
  15149. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15150. carry out the following steps:
  15151. % TODO: .align the functions!
  15152. \begin{enumerate}
  15153. %% \item Start with \code{.global} and \code{.align} directives followed
  15154. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15155. %% example.)
  15156. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15157. pointer.
  15158. \item Push to the stack all the callee-saved registers that were
  15159. used for register allocation.
  15160. \item Move the stack pointer \code{rsp} down to make room for the
  15161. regular spills (aligned to 16 bytes).
  15162. \item Move the root stack pointer \code{r15} up by the size of the
  15163. root-stack frame for this function, which depends on the number of
  15164. spilled tuple-typed variables. \label{root-stack-init}
  15165. \item Initialize to zero all new entries in the root-stack frame.
  15166. \item Jump to the start block.
  15167. \end{enumerate}
  15168. The prelude of the \code{main} function has an additional task: call
  15169. the \code{initialize} function to set up the garbage collector, and
  15170. then move the value of the global \code{rootstack\_begin} in
  15171. \code{r15}. This initialization should happen before step
  15172. \ref{root-stack-init}, which depends on \code{r15}.
  15173. The conclusion of every function should do the following:
  15174. \begin{enumerate}
  15175. \item Move the stack pointer back up past the regular spills.
  15176. \item Restore the callee-saved registers by popping them from the
  15177. stack.
  15178. \item Move the root stack pointer back down by the size of the
  15179. root-stack frame for this function.
  15180. \item Restore \code{rbp} by popping it from the stack.
  15181. \item Return to the caller with the \code{retq} instruction.
  15182. \end{enumerate}
  15183. The output of this pass is \LangXIndCallFlat{}, which differs from
  15184. \LangXIndCall{} in that there is no longer an AST node for function
  15185. definitions. Instead, a program is just
  15186. \racket{an association list}\python{a dictionary}
  15187. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15188. {\if\edition\racketEd
  15189. \[
  15190. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15191. \]
  15192. \fi}
  15193. {\if\edition\pythonEd
  15194. \[
  15195. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15196. \]
  15197. \fi}
  15198. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15199. compiling \LangFun{} to x86.
  15200. \begin{exercise}\normalfont\normalsize
  15201. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15202. Create eight new programs that use functions including examples that
  15203. pass functions and return functions from other functions, recursive
  15204. functions, functions that create tuples, and functions that make tail
  15205. calls. Test your compiler on these new programs and all your
  15206. previously created test programs.
  15207. \end{exercise}
  15208. \begin{figure}[tbp]
  15209. \begin{tcolorbox}[colback=white]
  15210. {\if\edition\racketEd
  15211. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15212. \node (Lfun) at (0,2) {\large \LangFun{}};
  15213. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15214. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15215. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15216. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15217. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15218. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15219. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15220. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15221. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15222. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15223. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15224. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15225. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15226. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15227. \path[->,bend left=15] (Lfun) edge [above] node
  15228. {\ttfamily\footnotesize shrink} (Lfun-1);
  15229. \path[->,bend left=15] (Lfun-1) edge [above] node
  15230. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15231. \path[->,bend left=15] (Lfun-2) edge [above] node
  15232. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15233. \path[->,bend left=15] (F1-1) edge [left] node
  15234. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15235. \path[->,bend left=15] (F1-2) edge [below] node
  15236. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15237. \path[->,bend left=15] (F1-3) edge [below] node
  15238. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15239. \path[->,bend right=15] (F1-4) edge [above] node
  15240. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15241. \path[->,bend right=15] (F1-5) edge [right] node
  15242. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15243. \path[->,bend right=15] (C3-2) edge [right] node
  15244. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15245. \path[->,bend left=15] (x86-2) edge [right] node
  15246. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15247. \path[->,bend right=15] (x86-2-1) edge [below] node
  15248. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15249. \path[->,bend right=15] (x86-2-2) edge [right] node
  15250. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15251. \path[->,bend left=15] (x86-3) edge [above] node
  15252. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15253. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15254. \end{tikzpicture}
  15255. \fi}
  15256. {\if\edition\pythonEd\pythonColor
  15257. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15258. \node (Lfun) at (0,2) {\large \LangFun{}};
  15259. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15260. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15261. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15262. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15263. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15264. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15265. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15266. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15267. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15268. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15269. \path[->,bend left=15] (Lfun) edge [above] node
  15270. {\ttfamily\footnotesize shrink} (Lfun-2);
  15271. \path[->,bend left=15] (Lfun-2) edge [above] node
  15272. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15273. \path[->,bend left=15] (F1-1) edge [above] node
  15274. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15275. \path[->,bend left=15] (F1-2) edge [right] node
  15276. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15277. \path[->,bend right=15] (F1-4) edge [above] node
  15278. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15279. \path[->,bend right=15] (F1-5) edge [right] node
  15280. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15281. \path[->,bend left=15] (C3-2) edge [right] node
  15282. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15283. \path[->,bend right=15] (x86-2) edge [below] node
  15284. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15285. \path[->,bend left=15] (x86-3) edge [above] node
  15286. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15287. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15288. \end{tikzpicture}
  15289. \fi}
  15290. \end{tcolorbox}
  15291. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15292. \label{fig:Lfun-passes}
  15293. \end{figure}
  15294. \section{An Example Translation}
  15295. \label{sec:functions-example}
  15296. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15297. function in \LangFun{} to x86. The figure includes the results of
  15298. \code{explicate\_control} and \code{select\_instructions}.
  15299. \begin{figure}[hbtp]
  15300. \begin{tcolorbox}[colback=white]
  15301. \begin{tabular}{ll}
  15302. \begin{minipage}{0.4\textwidth}
  15303. % s3_2.rkt
  15304. {\if\edition\racketEd
  15305. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15306. (define (add [x : Integer]
  15307. [y : Integer])
  15308. : Integer
  15309. (+ x y))
  15310. (add 40 2)
  15311. \end{lstlisting}
  15312. \fi}
  15313. {\if\edition\pythonEd\pythonColor
  15314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15315. def add(x:int, y:int) -> int:
  15316. return x + y
  15317. print(add(40, 2))
  15318. \end{lstlisting}
  15319. \fi}
  15320. $\Downarrow$
  15321. {\if\edition\racketEd
  15322. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15323. (define (add86 [x87 : Integer]
  15324. [y88 : Integer])
  15325. : Integer
  15326. add86start:
  15327. return (+ x87 y88);
  15328. )
  15329. (define (main) : Integer ()
  15330. mainstart:
  15331. tmp89 = (fun-ref add86 2);
  15332. (tail-call tmp89 40 2)
  15333. )
  15334. \end{lstlisting}
  15335. \fi}
  15336. {\if\edition\pythonEd\pythonColor
  15337. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15338. def add(x:int, y:int) -> int:
  15339. addstart:
  15340. return x + y
  15341. def main() -> int:
  15342. mainstart:
  15343. fun.0 = add
  15344. tmp.1 = fun.0(40, 2)
  15345. print(tmp.1)
  15346. return 0
  15347. \end{lstlisting}
  15348. \fi}
  15349. \end{minipage}
  15350. &
  15351. $\Rightarrow$
  15352. \begin{minipage}{0.5\textwidth}
  15353. {\if\edition\racketEd
  15354. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15355. (define (add86) : Integer
  15356. add86start:
  15357. movq %rdi, x87
  15358. movq %rsi, y88
  15359. movq x87, %rax
  15360. addq y88, %rax
  15361. jmp inc1389conclusion
  15362. )
  15363. (define (main) : Integer
  15364. mainstart:
  15365. leaq (fun-ref add86 2), tmp89
  15366. movq $40, %rdi
  15367. movq $2, %rsi
  15368. tail-jmp tmp89
  15369. )
  15370. \end{lstlisting}
  15371. \fi}
  15372. {\if\edition\pythonEd\pythonColor
  15373. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15374. def add() -> int:
  15375. addstart:
  15376. movq %rdi, x
  15377. movq %rsi, y
  15378. movq x, %rax
  15379. addq y, %rax
  15380. jmp addconclusion
  15381. def main() -> int:
  15382. mainstart:
  15383. leaq add, fun.0
  15384. movq $40, %rdi
  15385. movq $2, %rsi
  15386. callq *fun.0
  15387. movq %rax, tmp.1
  15388. movq tmp.1, %rdi
  15389. callq print_int
  15390. movq $0, %rax
  15391. jmp mainconclusion
  15392. \end{lstlisting}
  15393. \fi}
  15394. $\Downarrow$
  15395. \end{minipage}
  15396. \end{tabular}
  15397. \begin{tabular}{ll}
  15398. \begin{minipage}{0.3\textwidth}
  15399. {\if\edition\racketEd
  15400. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15401. .globl add86
  15402. .align 8
  15403. add86:
  15404. pushq %rbp
  15405. movq %rsp, %rbp
  15406. jmp add86start
  15407. add86start:
  15408. movq %rdi, %rax
  15409. addq %rsi, %rax
  15410. jmp add86conclusion
  15411. add86conclusion:
  15412. popq %rbp
  15413. retq
  15414. \end{lstlisting}
  15415. \fi}
  15416. {\if\edition\pythonEd\pythonColor
  15417. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15418. .align 8
  15419. add:
  15420. pushq %rbp
  15421. movq %rsp, %rbp
  15422. subq $0, %rsp
  15423. jmp addstart
  15424. addstart:
  15425. movq %rdi, %rdx
  15426. movq %rsi, %rcx
  15427. movq %rdx, %rax
  15428. addq %rcx, %rax
  15429. jmp addconclusion
  15430. addconclusion:
  15431. subq $0, %r15
  15432. addq $0, %rsp
  15433. popq %rbp
  15434. retq
  15435. \end{lstlisting}
  15436. \fi}
  15437. \end{minipage}
  15438. &
  15439. \begin{minipage}{0.5\textwidth}
  15440. {\if\edition\racketEd
  15441. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15442. .globl main
  15443. .align 8
  15444. main:
  15445. pushq %rbp
  15446. movq %rsp, %rbp
  15447. movq $16384, %rdi
  15448. movq $16384, %rsi
  15449. callq initialize
  15450. movq rootstack_begin(%rip), %r15
  15451. jmp mainstart
  15452. mainstart:
  15453. leaq add86(%rip), %rcx
  15454. movq $40, %rdi
  15455. movq $2, %rsi
  15456. movq %rcx, %rax
  15457. popq %rbp
  15458. jmp *%rax
  15459. mainconclusion:
  15460. popq %rbp
  15461. retq
  15462. \end{lstlisting}
  15463. \fi}
  15464. {\if\edition\pythonEd\pythonColor
  15465. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15466. .globl main
  15467. .align 8
  15468. main:
  15469. pushq %rbp
  15470. movq %rsp, %rbp
  15471. subq $0, %rsp
  15472. movq $65536, %rdi
  15473. movq $65536, %rsi
  15474. callq initialize
  15475. movq rootstack_begin(%rip), %r15
  15476. jmp mainstart
  15477. mainstart:
  15478. leaq add(%rip), %rcx
  15479. movq $40, %rdi
  15480. movq $2, %rsi
  15481. callq *%rcx
  15482. movq %rax, %rcx
  15483. movq %rcx, %rdi
  15484. callq print_int
  15485. movq $0, %rax
  15486. jmp mainconclusion
  15487. mainconclusion:
  15488. subq $0, %r15
  15489. addq $0, %rsp
  15490. popq %rbp
  15491. retq
  15492. \end{lstlisting}
  15493. \fi}
  15494. \end{minipage}
  15495. \end{tabular}
  15496. \end{tcolorbox}
  15497. \caption{Example compilation of a simple function to x86.}
  15498. \label{fig:add-fun}
  15499. \end{figure}
  15500. % Challenge idea: inlining! (simple version)
  15501. % Further Reading
  15502. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15503. \chapter{Lexically Scoped Functions}
  15504. \label{ch:Llambda}
  15505. \setcounter{footnote}{0}
  15506. This chapter studies lexically scoped functions. Lexical
  15507. scoping\index{subject}{lexical scoping} means that a function's body
  15508. may refer to variables whose binding site is outside of the function,
  15509. in an enclosing scope.
  15510. %
  15511. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15512. in \LangLam{}, which extends \LangFun{} with the
  15513. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15514. functions. The body of the \key{lambda} refers to three variables:
  15515. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15516. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15517. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15518. function \code{f}}, and \code{x} is a parameter of function
  15519. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15520. result value. The main expression of the program includes two calls to
  15521. \code{f} with different arguments for \code{x}: first \code{5} and
  15522. then \code{3}. The functions returned from \code{f} are bound to
  15523. variables \code{g} and \code{h}. Even though these two functions were
  15524. created by the same \code{lambda}, they are really different functions
  15525. because they use different values for \code{x}. Applying \code{g} to
  15526. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15527. produces \code{22}, so the result of the program is \code{42}.
  15528. \begin{figure}[btp]
  15529. \begin{tcolorbox}[colback=white]
  15530. {\if\edition\racketEd
  15531. % lambda_test_21.rkt
  15532. \begin{lstlisting}
  15533. (define (f [x : Integer]) : (Integer -> Integer)
  15534. (let ([y 4])
  15535. (lambda: ([z : Integer]) : Integer
  15536. (+ x (+ y z)))))
  15537. (let ([g (f 5)])
  15538. (let ([h (f 3)])
  15539. (+ (g 11) (h 15))))
  15540. \end{lstlisting}
  15541. \fi}
  15542. {\if\edition\pythonEd\pythonColor
  15543. \begin{lstlisting}
  15544. def f(x : int) -> Callable[[int], int]:
  15545. y = 4
  15546. return lambda z: x + y + z
  15547. g = f(5)
  15548. h = f(3)
  15549. print(g(11) + h(15))
  15550. \end{lstlisting}
  15551. \fi}
  15552. \end{tcolorbox}
  15553. \caption{Example of a lexically scoped function.}
  15554. \label{fig:lexical-scoping}
  15555. \end{figure}
  15556. The approach that we take for implementing lexically scoped functions
  15557. is to compile them into top-level function definitions, translating
  15558. from \LangLam{} into \LangFun{}. However, the compiler must give
  15559. special treatment to variable occurrences such as \code{x} and
  15560. \code{y} in the body of the \code{lambda} shown in
  15561. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15562. may not refer to variables defined outside of it. To identify such
  15563. variable occurrences, we review the standard notion of free variable.
  15564. \begin{definition}\normalfont
  15565. A variable is \emph{free in expression} $e$ if the variable occurs
  15566. inside $e$ but does not have an enclosing definition that is also in
  15567. $e$.\index{subject}{free variable}
  15568. \end{definition}
  15569. For example, in the expression
  15570. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15571. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15572. only \code{x} and \code{y} are free in the following expression,
  15573. because \code{z} is defined by the \code{lambda}
  15574. {\if\edition\racketEd
  15575. \begin{lstlisting}
  15576. (lambda: ([z : Integer]) : Integer
  15577. (+ x (+ y z)))
  15578. \end{lstlisting}
  15579. \fi}
  15580. {\if\edition\pythonEd\pythonColor
  15581. \begin{lstlisting}
  15582. lambda z: x + y + z
  15583. \end{lstlisting}
  15584. \fi}
  15585. %
  15586. \noindent Thus the free variables of a \code{lambda} are the ones that
  15587. need special treatment. We need to transport at runtime the values
  15588. of those variables from the point where the \code{lambda} was created
  15589. to the point where the \code{lambda} is applied. An efficient solution
  15590. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15591. values of the free variables together with a function pointer into a
  15592. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15593. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15594. closure}
  15595. %
  15596. By design, we have all the ingredients to make closures:
  15597. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15598. function pointers. The function pointer resides at index $0$, and the
  15599. values for the free variables fill in the rest of the tuple.
  15600. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15601. to see how closures work. It is a three-step dance. The program calls
  15602. function \code{f}, which creates a closure for the \code{lambda}. The
  15603. closure is a tuple whose first element is a pointer to the top-level
  15604. function that we will generate for the \code{lambda}; the second
  15605. element is the value of \code{x}, which is \code{5}; and the third
  15606. element is \code{4}, the value of \code{y}. The closure does not
  15607. contain an element for \code{z} because \code{z} is not a free
  15608. variable of the \code{lambda}. Creating the closure is step 1 of the
  15609. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15610. shown in figure~\ref{fig:closures}.
  15611. %
  15612. The second call to \code{f} creates another closure, this time with
  15613. \code{3} in the second slot (for \code{x}). This closure is also
  15614. returned from \code{f} but bound to \code{h}, which is also shown in
  15615. figure~\ref{fig:closures}.
  15616. \begin{figure}[tbp]
  15617. \centering
  15618. \begin{minipage}{0.65\textwidth}
  15619. \begin{tcolorbox}[colback=white]
  15620. \includegraphics[width=\textwidth]{figs/closures}
  15621. \end{tcolorbox}
  15622. \end{minipage}
  15623. \caption{Flat closure representations for the two functions
  15624. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15625. \label{fig:closures}
  15626. \end{figure}
  15627. Continuing with the example, consider the application of \code{g} to
  15628. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15629. closure, we obtain the function pointer from the first element of the
  15630. closure and call it, passing in the closure itself and then the
  15631. regular arguments, in this case \code{11}. This technique for applying
  15632. a closure is step 2 of the dance.
  15633. %
  15634. But doesn't this \code{lambda} take only one argument, for parameter
  15635. \code{z}? The third and final step of the dance is generating a
  15636. top-level function for a \code{lambda}. We add an additional
  15637. parameter for the closure and insert an initialization at the beginning
  15638. of the function for each free variable, to bind those variables to the
  15639. appropriate elements from the closure parameter.
  15640. %
  15641. This three-step dance is known as \emph{closure
  15642. conversion}\index{subject}{closure conversion}. We discuss the
  15643. details of closure conversion in section~\ref{sec:closure-conversion}
  15644. and show the code generated from the example in
  15645. section~\ref{sec:example-lambda}. First, we define the syntax and
  15646. semantics of \LangLam{} in section~\ref{sec:r5}.
  15647. \section{The \LangLam{} Language}
  15648. \label{sec:r5}
  15649. The definitions of the concrete syntax and abstract syntax for
  15650. \LangLam{}, a language with anonymous functions and lexical scoping,
  15651. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15652. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15653. for \LangFun{}, which already has syntax for function application.
  15654. %
  15655. \python{The syntax also includes an assignment statement that includes
  15656. a type annotation for the variable on the left-hand side, which
  15657. facilitates the type checking of \code{lambda} expressions that we
  15658. discuss later in this section.}
  15659. %
  15660. \racket{The \code{procedure-arity} operation returns the number of parameters
  15661. of a given function, an operation that we need for the translation
  15662. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15663. %
  15664. \python{The \code{arity} operation returns the number of parameters of
  15665. a given function, an operation that we need for the translation
  15666. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15667. The \code{arity} operation is not in Python, but the same functionality
  15668. is available in a more complex form. We include \code{arity} in the
  15669. \LangLam{} source language to enable testing.}
  15670. \newcommand{\LlambdaGrammarRacket}{
  15671. \begin{array}{lcl}
  15672. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15673. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15674. \end{array}
  15675. }
  15676. \newcommand{\LlambdaASTRacket}{
  15677. \begin{array}{lcl}
  15678. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15679. \itm{op} &::=& \code{procedure-arity}
  15680. \end{array}
  15681. }
  15682. \newcommand{\LlambdaGrammarPython}{
  15683. \begin{array}{lcl}
  15684. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15685. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15686. \end{array}
  15687. }
  15688. \newcommand{\LlambdaASTPython}{
  15689. \begin{array}{lcl}
  15690. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15691. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15692. \end{array}
  15693. }
  15694. % include AnnAssign in ASTPython
  15695. \begin{figure}[tp]
  15696. \centering
  15697. \begin{tcolorbox}[colback=white]
  15698. \small
  15699. {\if\edition\racketEd
  15700. \[
  15701. \begin{array}{l}
  15702. \gray{\LintGrammarRacket{}} \\ \hline
  15703. \gray{\LvarGrammarRacket{}} \\ \hline
  15704. \gray{\LifGrammarRacket{}} \\ \hline
  15705. \gray{\LwhileGrammarRacket} \\ \hline
  15706. \gray{\LtupGrammarRacket} \\ \hline
  15707. \gray{\LfunGrammarRacket} \\ \hline
  15708. \LlambdaGrammarRacket \\
  15709. \begin{array}{lcl}
  15710. \LangLamM{} &::=& \Def\ldots \; \Exp
  15711. \end{array}
  15712. \end{array}
  15713. \]
  15714. \fi}
  15715. {\if\edition\pythonEd\pythonColor
  15716. \[
  15717. \begin{array}{l}
  15718. \gray{\LintGrammarPython{}} \\ \hline
  15719. \gray{\LvarGrammarPython{}} \\ \hline
  15720. \gray{\LifGrammarPython{}} \\ \hline
  15721. \gray{\LwhileGrammarPython} \\ \hline
  15722. \gray{\LtupGrammarPython} \\ \hline
  15723. \gray{\LfunGrammarPython} \\ \hline
  15724. \LlambdaGrammarPython \\
  15725. \begin{array}{lcl}
  15726. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15727. \end{array}
  15728. \end{array}
  15729. \]
  15730. \fi}
  15731. \end{tcolorbox}
  15732. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15733. with \key{lambda}.}
  15734. \label{fig:Llam-concrete-syntax}
  15735. \index{subject}{Llambda@\LangLam{} concrete syntax}
  15736. \end{figure}
  15737. \begin{figure}[tp]
  15738. \centering
  15739. \begin{tcolorbox}[colback=white]
  15740. \small
  15741. {\if\edition\racketEd
  15742. \[\arraycolsep=3pt
  15743. \begin{array}{l}
  15744. \gray{\LintOpAST} \\ \hline
  15745. \gray{\LvarASTRacket{}} \\ \hline
  15746. \gray{\LifASTRacket{}} \\ \hline
  15747. \gray{\LwhileASTRacket{}} \\ \hline
  15748. \gray{\LtupASTRacket{}} \\ \hline
  15749. \gray{\LfunASTRacket} \\ \hline
  15750. \LlambdaASTRacket \\
  15751. \begin{array}{lcl}
  15752. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15753. \end{array}
  15754. \end{array}
  15755. \]
  15756. \fi}
  15757. {\if\edition\pythonEd\pythonColor
  15758. \[
  15759. \begin{array}{l}
  15760. \gray{\LintASTPython} \\ \hline
  15761. \gray{\LvarASTPython{}} \\ \hline
  15762. \gray{\LifASTPython{}} \\ \hline
  15763. \gray{\LwhileASTPython{}} \\ \hline
  15764. \gray{\LtupASTPython{}} \\ \hline
  15765. \gray{\LfunASTPython} \\ \hline
  15766. \LlambdaASTPython \\
  15767. \begin{array}{lcl}
  15768. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15769. \end{array}
  15770. \end{array}
  15771. \]
  15772. \fi}
  15773. \end{tcolorbox}
  15774. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15775. \label{fig:Llam-syntax}
  15776. \index{subject}{Llambda@\LangLam{} abstract syntax}
  15777. \end{figure}
  15778. Figure~\ref{fig:interp-Llambda} shows the definitional
  15779. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15780. \key{Lambda} saves the current environment inside the returned
  15781. function value. Recall that during function application, the
  15782. environment stored in the function value, extended with the mapping of
  15783. parameters to argument values, is used to interpret the body of the
  15784. function.
  15785. \begin{figure}[tbp]
  15786. \begin{tcolorbox}[colback=white]
  15787. {\if\edition\racketEd
  15788. \begin{lstlisting}
  15789. (define interp-Llambda-class
  15790. (class interp-Lfun-class
  15791. (super-new)
  15792. (define/override (interp-op op)
  15793. (match op
  15794. ['procedure-arity
  15795. (lambda (v)
  15796. (match v
  15797. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15798. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15799. [else (super interp-op op)]))
  15800. (define/override ((interp-exp env) e)
  15801. (define recur (interp-exp env))
  15802. (match e
  15803. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15804. `(function ,xs ,body ,env)]
  15805. [else ((super interp-exp env) e)]))
  15806. ))
  15807. (define (interp-Llambda p)
  15808. (send (new interp-Llambda-class) interp-program p))
  15809. \end{lstlisting}
  15810. \fi}
  15811. {\if\edition\pythonEd\pythonColor
  15812. \begin{lstlisting}
  15813. class InterpLlambda(InterpLfun):
  15814. def arity(self, v):
  15815. match v:
  15816. case Function(name, params, body, env):
  15817. return len(params)
  15818. case _:
  15819. raise Exception('Llambda arity unexpected ' + repr(v))
  15820. def interp_exp(self, e, env):
  15821. match e:
  15822. case Call(Name('arity'), [fun]):
  15823. f = self.interp_exp(fun, env)
  15824. return self.arity(f)
  15825. case Lambda(params, body):
  15826. return Function('lambda', params, [Return(body)], env)
  15827. case _:
  15828. return super().interp_exp(e, env)
  15829. def interp_stmt(self, s, env, cont):
  15830. match s:
  15831. case AnnAssign(lhs, typ, value, simple):
  15832. env[lhs.id] = self.interp_exp(value, env)
  15833. return self.interp_stmts(cont, env)
  15834. case Pass():
  15835. return self.interp_stmts(cont, env)
  15836. case _:
  15837. return super().interp_stmt(s, env, cont)
  15838. \end{lstlisting}
  15839. \fi}
  15840. \end{tcolorbox}
  15841. \caption{Interpreter for \LangLam{}.}
  15842. \label{fig:interp-Llambda}
  15843. \end{figure}
  15844. {\if\edition\racketEd
  15845. %
  15846. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15847. \key{lambda} form. The body of the \key{lambda} is checked in an
  15848. environment that includes the current environment (because it is
  15849. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15850. require the body's type to match the declared return type.
  15851. %
  15852. \fi}
  15853. {\if\edition\pythonEd\pythonColor
  15854. %
  15855. Figures~\ref{fig:type-check-Llambda} and
  15856. \ref{fig:type-check-Llambda-part2} define the type checker for
  15857. \LangLam{}, which is more complex than one might expect. The reason
  15858. for the added complexity is that the syntax of \key{lambda} does not
  15859. include type annotations for the parameters or return type. Instead
  15860. they must be inferred. There are many approaches to type inference
  15861. from which to choose, of varying degrees of complexity. We choose one
  15862. of the simpler approaches, bidirectional type
  15863. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15864. book is compilation, not type inference.
  15865. The main idea of bidirectional type inference is to add an auxiliary
  15866. function, here named \code{check\_exp}, that takes an expected type
  15867. and checks whether the given expression is of that type. Thus, in
  15868. \code{check\_exp}, type information flows in a top-down manner with
  15869. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15870. function, where type information flows in a primarily bottom-up
  15871. manner.
  15872. %
  15873. The idea then is to use \code{check\_exp} in all the places where we
  15874. already know what the type of an expression should be, such as in the
  15875. \code{return} statement of a top-level function definition or on the
  15876. right-hand side of an annotated assignment statement.
  15877. With regard to \code{lambda}, it is straightforward to check a
  15878. \code{lambda} inside \code{check\_exp} because the expected type
  15879. provides the parameter types and the return type. On the other hand,
  15880. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15881. that we do not allow \code{lambda} in contexts in which we don't already
  15882. know its type. This restriction does not incur a loss of
  15883. expressiveness for \LangLam{} because it is straightforward to modify
  15884. a program to sidestep the restriction, for example, by using an
  15885. annotated assignment statement to assign the \code{lambda} to a
  15886. temporary variable.
  15887. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15888. checker records their type in a \code{has\_type} field. This type
  15889. information is used further on in this chapter.
  15890. %
  15891. \fi}
  15892. \begin{figure}[tbp]
  15893. \begin{tcolorbox}[colback=white]
  15894. {\if\edition\racketEd
  15895. \begin{lstlisting}
  15896. (define (type-check-Llambda env)
  15897. (lambda (e)
  15898. (match e
  15899. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15900. (define-values (new-body bodyT)
  15901. ((type-check-exp (append (map cons xs Ts) env)) body))
  15902. (define ty `(,@Ts -> ,rT))
  15903. (cond
  15904. [(equal? rT bodyT)
  15905. (values (HasType (Lambda params rT new-body) ty) ty)]
  15906. [else
  15907. (error "mismatch in return type" bodyT rT)])]
  15908. ...
  15909. )))
  15910. \end{lstlisting}
  15911. \fi}
  15912. {\if\edition\pythonEd\pythonColor
  15913. \begin{lstlisting}
  15914. class TypeCheckLlambda(TypeCheckLfun):
  15915. def type_check_exp(self, e, env):
  15916. match e:
  15917. case Name(id):
  15918. e.has_type = env[id]
  15919. return env[id]
  15920. case Lambda(params, body):
  15921. raise Exception('cannot synthesize a type for a lambda')
  15922. case Call(Name('arity'), [func]):
  15923. func_t = self.type_check_exp(func, env)
  15924. match func_t:
  15925. case FunctionType(params_t, return_t):
  15926. return IntType()
  15927. case _:
  15928. raise Exception('in arity, unexpected ' + repr(func_t))
  15929. case _:
  15930. return super().type_check_exp(e, env)
  15931. def check_exp(self, e, ty, env):
  15932. match e:
  15933. case Lambda(params, body):
  15934. e.has_type = ty
  15935. match ty:
  15936. case FunctionType(params_t, return_t):
  15937. new_env = env.copy().update(zip(params, params_t))
  15938. self.check_exp(body, return_t, new_env)
  15939. case _:
  15940. raise Exception('lambda does not have type ' + str(ty))
  15941. case Call(func, args):
  15942. func_t = self.type_check_exp(func, env)
  15943. match func_t:
  15944. case FunctionType(params_t, return_t):
  15945. for (arg, param_t) in zip(args, params_t):
  15946. self.check_exp(arg, param_t, env)
  15947. self.check_type_equal(return_t, ty, e)
  15948. case _:
  15949. raise Exception('type_check_exp: in call, unexpected ' + \
  15950. repr(func_t))
  15951. case _:
  15952. t = self.type_check_exp(e, env)
  15953. self.check_type_equal(t, ty, e)
  15954. \end{lstlisting}
  15955. \fi}
  15956. \end{tcolorbox}
  15957. \caption{Type checking \LangLam{}\python{, part 1}.}
  15958. \label{fig:type-check-Llambda}
  15959. \end{figure}
  15960. {\if\edition\pythonEd\pythonColor
  15961. \begin{figure}[tbp]
  15962. \begin{tcolorbox}[colback=white]
  15963. \begin{lstlisting}
  15964. def check_stmts(self, ss, return_ty, env):
  15965. if len(ss) == 0:
  15966. return
  15967. match ss[0]:
  15968. case FunctionDef(name, params, body, dl, returns, comment):
  15969. new_env = env.copy().update(params)
  15970. rt = self.check_stmts(body, returns, new_env)
  15971. self.check_stmts(ss[1:], return_ty, env)
  15972. case Return(value):
  15973. self.check_exp(value, return_ty, env)
  15974. case Assign([Name(id)], value):
  15975. if id in env:
  15976. self.check_exp(value, env[id], env)
  15977. else:
  15978. env[id] = self.type_check_exp(value, env)
  15979. self.check_stmts(ss[1:], return_ty, env)
  15980. case Assign([Subscript(tup, Constant(index), Store())], value):
  15981. tup_t = self.type_check_exp(tup, env)
  15982. match tup_t:
  15983. case TupleType(ts):
  15984. self.check_exp(value, ts[index], env)
  15985. case _:
  15986. raise Exception('expected a tuple, not ' + repr(tup_t))
  15987. self.check_stmts(ss[1:], return_ty, env)
  15988. case AnnAssign(Name(id), ty_annot, value, simple):
  15989. ss[0].annotation = ty_annot
  15990. if id in env:
  15991. self.check_type_equal(env[id], ty_annot)
  15992. else:
  15993. env[id] = ty_annot
  15994. self.check_exp(value, ty_annot, env)
  15995. self.check_stmts(ss[1:], return_ty, env)
  15996. case _:
  15997. self.type_check_stmts(ss, env)
  15998. def type_check(self, p):
  15999. match p:
  16000. case Module(body):
  16001. env = {}
  16002. for s in body:
  16003. match s:
  16004. case FunctionDef(name, params, bod, dl, returns, comment):
  16005. params_t = [t for (x,t) in params]
  16006. env[name] = FunctionType(params_t, returns)
  16007. self.check_stmts(body, int, env)
  16008. \end{lstlisting}
  16009. \end{tcolorbox}
  16010. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  16011. \label{fig:type-check-Llambda-part2}
  16012. \end{figure}
  16013. \fi}
  16014. \clearpage
  16015. \section{Assignment and Lexically Scoped Functions}
  16016. \label{sec:assignment-scoping}
  16017. The combination of lexically scoped functions and assignment to
  16018. variables raises a challenge with the flat-closure approach to
  16019. implementing lexically scoped functions. Consider the following
  16020. example in which function \code{f} has a free variable \code{x} that
  16021. is changed after \code{f} is created but before the call to \code{f}.
  16022. % loop_test_11.rkt
  16023. {\if\edition\racketEd
  16024. \begin{lstlisting}
  16025. (let ([x 0])
  16026. (let ([y 0])
  16027. (let ([z 20])
  16028. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16029. (begin
  16030. (set! x 10)
  16031. (set! y 12)
  16032. (f y))))))
  16033. \end{lstlisting}
  16034. \fi}
  16035. {\if\edition\pythonEd\pythonColor
  16036. % box_free_assign.py
  16037. \begin{lstlisting}
  16038. def g(z : int) -> int:
  16039. x = 0
  16040. y = 0
  16041. f : Callable[[int],int] = lambda a: a + x + z
  16042. x = 10
  16043. y = 12
  16044. return f(y)
  16045. print(g(20))
  16046. \end{lstlisting}
  16047. \fi} The correct output for this example is \code{42} because the call
  16048. to \code{f} is required to use the current value of \code{x} (which is
  16049. \code{10}). Unfortunately, the closure conversion pass
  16050. (section~\ref{sec:closure-conversion}) generates code for the
  16051. \code{lambda} that copies the old value of \code{x} into a
  16052. closure. Thus, if we naively applied closure conversion, the output of
  16053. this program would be \code{32}.
  16054. A first attempt at solving this problem would be to save a pointer to
  16055. \code{x} in the closure and change the occurrences of \code{x} inside
  16056. the lambda to dereference the pointer. Of course, this would require
  16057. assigning \code{x} to the stack and not to a register. However, the
  16058. problem goes a bit deeper.
  16059. Consider the following example that returns a function that refers to
  16060. a local variable of the enclosing function:
  16061. \begin{center}
  16062. \begin{minipage}{\textwidth}
  16063. {\if\edition\racketEd
  16064. \begin{lstlisting}
  16065. (define (f) : ( -> Integer)
  16066. (let ([x 0])
  16067. (let ([g (lambda: () : Integer x)])
  16068. (begin
  16069. (set! x 42)
  16070. g))))
  16071. ((f))
  16072. \end{lstlisting}
  16073. \fi}
  16074. {\if\edition\pythonEd\pythonColor
  16075. % counter.py
  16076. \begin{lstlisting}
  16077. def f():
  16078. x = 0
  16079. g = lambda: x
  16080. x = 42
  16081. return g
  16082. print(f()())
  16083. \end{lstlisting}
  16084. \fi}
  16085. \end{minipage}
  16086. \end{center}
  16087. In this example, the lifetime of \code{x} extends beyond the lifetime
  16088. of the call to \code{f}. Thus, if we were to store \code{x} on the
  16089. stack frame for the call to \code{f}, it would be gone by the time we
  16090. called \code{g}, leaving us with dangling pointers for
  16091. \code{x}. This example demonstrates that when a variable occurs free
  16092. inside a function, its lifetime becomes indefinite. Thus, the value of
  16093. the variable needs to live on the heap. The verb
  16094. \emph{box}\index{subject}{box} is often used for allocating a single
  16095. value on the heap, producing a pointer, and
  16096. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  16097. %
  16098. We introduce a new pass named \code{convert\_assignments} to address
  16099. this challenge.
  16100. %
  16101. \python{But before diving into that, we have one more
  16102. problem to discuss.}
  16103. {\if\edition\pythonEd\pythonColor
  16104. \section{Uniquify Variables}
  16105. \label{sec:uniquify-lambda}
  16106. With the addition of \code{lambda} we have a complication to deal
  16107. with: name shadowing. Consider the following program with a function
  16108. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  16109. \code{lambda} expressions. The first \code{lambda} has a parameter
  16110. that is also named \code{x}.
  16111. \begin{lstlisting}
  16112. def f(x:int, y:int) -> Callable[[int], int]:
  16113. g : Callable[[int],int] = (lambda x: x + y)
  16114. h : Callable[[int],int] = (lambda y: x + y)
  16115. x = input_int()
  16116. return g
  16117. print(f(0, 10)(32))
  16118. \end{lstlisting}
  16119. Many of our compiler passes rely on being able to connect variable
  16120. uses with their definitions using just the name of the
  16121. variable. However, in the example above, the name of the variable does
  16122. not uniquely determine its definition. To solve this problem we
  16123. recommend implementing a pass named \code{uniquify} that renames every
  16124. variable in the program to make sure that they are all unique.
  16125. The following shows the result of \code{uniquify} for the example
  16126. above. The \code{x} parameter of function \code{f} is renamed to
  16127. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  16128. renamed to \code{x\_4}.
  16129. \begin{lstlisting}
  16130. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  16131. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  16132. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  16133. x_0 = input_int()
  16134. return g_2
  16135. def main() -> int :
  16136. print(f(0, 10)(32))
  16137. return 0
  16138. \end{lstlisting}
  16139. \fi} % pythonEd
  16140. %% \section{Reveal Functions}
  16141. %% \label{sec:reveal-functions-r5}
  16142. %% \racket{To support the \code{procedure-arity} operator we need to
  16143. %% communicate the arity of a function to the point of closure
  16144. %% creation.}
  16145. %% %
  16146. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16147. %% function at runtime. Thus, we need to communicate the arity of a
  16148. %% function to the point of closure creation.}
  16149. %% %
  16150. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16151. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16152. %% \[
  16153. %% \begin{array}{lcl}
  16154. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16155. %% \end{array}
  16156. %% \]
  16157. \section{Assignment Conversion}
  16158. \label{sec:convert-assignments}
  16159. The purpose of the \code{convert\_assignments} pass is to address the
  16160. challenge regarding the interaction between variable assignments and
  16161. closure conversion. First we identify which variables need to be
  16162. boxed, and then we transform the program to box those variables. In
  16163. general, boxing introduces runtime overhead that we would like to
  16164. avoid, so we should box as few variables as possible. We recommend
  16165. boxing the variables in the intersection of the following two sets of
  16166. variables:
  16167. \begin{enumerate}
  16168. \item The variables that are free in a \code{lambda}.
  16169. \item The variables that appear on the left-hand side of an
  16170. assignment.
  16171. \end{enumerate}
  16172. The first condition is a must but the second condition is
  16173. conservative. It is possible to develop a more liberal condition using
  16174. static program analysis.
  16175. Consider again the first example from
  16176. section~\ref{sec:assignment-scoping}:
  16177. %
  16178. {\if\edition\racketEd
  16179. \begin{lstlisting}
  16180. (let ([x 0])
  16181. (let ([y 0])
  16182. (let ([z 20])
  16183. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16184. (begin
  16185. (set! x 10)
  16186. (set! y 12)
  16187. (f y))))))
  16188. \end{lstlisting}
  16189. \fi}
  16190. {\if\edition\pythonEd\pythonColor
  16191. \begin{lstlisting}
  16192. def g(z : int) -> int:
  16193. x = 0
  16194. y = 0
  16195. f : Callable[[int],int] = lambda a: a + x + z
  16196. x = 10
  16197. y = 12
  16198. return f(y)
  16199. print(g(20))
  16200. \end{lstlisting}
  16201. \fi}
  16202. %
  16203. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16204. side of assignments. The variables \code{x} and \code{z} occur free
  16205. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16206. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16207. three transformations: initialize \code{x} with a tuple whose element
  16208. is uninitialized, replace reads from \code{x} with tuple reads, and
  16209. replace each assignment to \code{x} with a tuple write. The output of
  16210. \code{convert\_assignments} for this example is as follows:
  16211. %
  16212. {\if\edition\racketEd
  16213. \begin{lstlisting}
  16214. (define (main) : Integer
  16215. (let ([x0 (vector 0)])
  16216. (let ([y1 0])
  16217. (let ([z2 20])
  16218. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16219. (+ a3 (+ (vector-ref x0 0) z2)))])
  16220. (begin
  16221. (vector-set! x0 0 10)
  16222. (set! y1 12)
  16223. (f4 y1)))))))
  16224. \end{lstlisting}
  16225. \fi}
  16226. %
  16227. {\if\edition\pythonEd\pythonColor
  16228. \begin{lstlisting}
  16229. def g(z : int)-> int:
  16230. x = (uninitialized(int),)
  16231. x[0] = 0
  16232. y = 0
  16233. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16234. x[0] = 10
  16235. y = 12
  16236. return f(y)
  16237. def main() -> int:
  16238. print(g(20))
  16239. return 0
  16240. \end{lstlisting}
  16241. \fi}
  16242. To compute the free variables of all the \code{lambda} expressions, we
  16243. recommend defining the following two auxiliary functions:
  16244. \begin{enumerate}
  16245. \item \code{free\_variables} computes the free variables of an expression, and
  16246. \item \code{free\_in\_lambda} collects all the variables that are
  16247. free in any of the \code{lambda} expressions, using
  16248. \code{free\_variables} in the case for each \code{lambda}.
  16249. \end{enumerate}
  16250. {\if\edition\racketEd
  16251. %
  16252. To compute the variables that are assigned to, we recommend updating
  16253. the \code{collect-set!} function that we introduced in
  16254. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16255. as \code{Lambda}.
  16256. %
  16257. \fi}
  16258. {\if\edition\pythonEd\pythonColor
  16259. %
  16260. To compute the variables that are assigned to, we recommend defining
  16261. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16262. the set of variables that occur in the left-hand side of an assignment
  16263. statement and otherwise returns the empty set.
  16264. %
  16265. \fi}
  16266. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16267. free in a \code{lambda} and that are assigned to in the enclosing
  16268. function definition.
  16269. Next we discuss the \code{convert\_assignments} pass. In the case for
  16270. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16271. $\VAR{x}$ to a tuple read.
  16272. %
  16273. {\if\edition\racketEd
  16274. \begin{lstlisting}
  16275. (Var |$x$|)
  16276. |$\Rightarrow$|
  16277. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16278. \end{lstlisting}
  16279. \fi}
  16280. %
  16281. {\if\edition\pythonEd\pythonColor
  16282. \begin{lstlisting}
  16283. Name(|$x$|)
  16284. |$\Rightarrow$|
  16285. Subscript(Name(|$x$|), Constant(0), Load())
  16286. \end{lstlisting}
  16287. \fi}
  16288. %
  16289. \noindent In the case for assignment, recursively process the
  16290. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16291. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16292. as follows:
  16293. %
  16294. {\if\edition\racketEd
  16295. \begin{lstlisting}
  16296. (SetBang |$x$| |$\itm{rhs}$|)
  16297. |$\Rightarrow$|
  16298. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16299. \end{lstlisting}
  16300. \fi}
  16301. {\if\edition\pythonEd\pythonColor
  16302. \begin{lstlisting}
  16303. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16304. |$\Rightarrow$|
  16305. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16306. \end{lstlisting}
  16307. \fi}
  16308. %
  16309. {\if\edition\racketEd
  16310. The case for \code{Lambda} is nontrivial, but it is similar to the
  16311. case for function definitions, which we discuss next.
  16312. \fi}
  16313. %
  16314. To translate a function definition, we first compute $\mathit{AF}$,
  16315. the intersection of the variables that are free in a \code{lambda} and
  16316. that are assigned to. We then apply assignment conversion to the body
  16317. of the function definition. Finally, we box the parameters of this
  16318. function definition that are in $\mathit{AF}$. For example,
  16319. the parameter \code{x} of the following function \code{g}
  16320. needs to be boxed:
  16321. {\if\edition\racketEd
  16322. \begin{lstlisting}
  16323. (define (g [x : Integer]) : Integer
  16324. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16325. (begin
  16326. (set! x 10)
  16327. (f 32))))
  16328. \end{lstlisting}
  16329. \fi}
  16330. %
  16331. {\if\edition\pythonEd\pythonColor
  16332. \begin{lstlisting}
  16333. def g(x : int) -> int:
  16334. f : Callable[[int],int] = lambda a: a + x
  16335. x = 10
  16336. return f(32)
  16337. \end{lstlisting}
  16338. \fi}
  16339. %
  16340. \noindent We box parameter \code{x} by creating a local variable named
  16341. \code{x} that is initialized to a tuple whose contents is the value of
  16342. the parameter, which is renamed to \code{x\_0}.
  16343. %
  16344. {\if\edition\racketEd
  16345. \begin{lstlisting}
  16346. (define (g [x_0 : Integer]) : Integer
  16347. (let ([x (vector x_0)])
  16348. (let ([f (lambda: ([a : Integer]) : Integer
  16349. (+ a (vector-ref x 0)))])
  16350. (begin
  16351. (vector-set! x 0 10)
  16352. (f 32)))))
  16353. \end{lstlisting}
  16354. \fi}
  16355. %
  16356. {\if\edition\pythonEd\pythonColor
  16357. \begin{lstlisting}
  16358. def g(x_0 : int)-> int:
  16359. x = (x_0,)
  16360. f : Callable[[int], int] = (lambda a: a + x[0])
  16361. x[0] = 10
  16362. return f(32)
  16363. \end{lstlisting}
  16364. \fi}
  16365. \section{Closure Conversion}
  16366. \label{sec:closure-conversion}
  16367. \index{subject}{closure conversion}
  16368. The compiling of lexically scoped functions into top-level function
  16369. definitions and flat closures is accomplished in the pass
  16370. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16371. and before \code{limit\_functions}.
  16372. As usual, we implement the pass as a recursive function over the
  16373. AST. The interesting cases are for \key{lambda} and function
  16374. application. We transform a \key{lambda} expression into an expression
  16375. that creates a closure, that is, a tuple for which the first element
  16376. is a function pointer and the rest of the elements are the values of
  16377. the free variables of the \key{lambda}.
  16378. %
  16379. However, we use the \code{Closure} AST node instead of using a tuple
  16380. so that we can record the arity.
  16381. %
  16382. In the generated code that follows, \itm{fvs} is the list of free
  16383. variables of the lambda and \itm{name} is a unique symbol generated to
  16384. identify the lambda.
  16385. %
  16386. \racket{The \itm{arity} is the number of parameters (the length of
  16387. \itm{ps}).}
  16388. %
  16389. {\if\edition\racketEd
  16390. \begin{lstlisting}
  16391. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16392. |$\Rightarrow$|
  16393. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16394. \end{lstlisting}
  16395. \fi}
  16396. %
  16397. {\if\edition\pythonEd\pythonColor
  16398. \begin{lstlisting}
  16399. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16400. |$\Rightarrow$|
  16401. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16402. \end{lstlisting}
  16403. \fi}
  16404. %
  16405. In addition to transforming each \key{Lambda} AST node into a
  16406. tuple, we create a top-level function definition for each
  16407. \key{Lambda}, as shown next.\\
  16408. \begin{minipage}{0.8\textwidth}
  16409. {\if\edition\racketEd
  16410. \begin{lstlisting}
  16411. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16412. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16413. ...
  16414. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16415. |\itm{body'}|)...))
  16416. \end{lstlisting}
  16417. \fi}
  16418. {\if\edition\pythonEd\pythonColor
  16419. \begin{lstlisting}
  16420. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16421. |$\itm{fvs}_1$| = clos[1]
  16422. |$\ldots$|
  16423. |$\itm{fvs}_m$| = clos[|$m$|]
  16424. |\itm{body'}|
  16425. \end{lstlisting}
  16426. \fi}
  16427. \end{minipage}\\
  16428. %
  16429. The \code{clos} parameter refers to the closure. The type
  16430. \itm{closTy} is a tuple type for which the first element type is
  16431. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16432. rest of the element types are the types of the free variables in the
  16433. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16434. is nontrivial to give a type to the function in the closure's
  16435. type.\footnote{To give an accurate type to a closure, we would need to
  16436. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16437. %
  16438. \racket{Translate the type
  16439. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16440. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16441. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16442. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16443. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16444. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16445. %% The dummy type is considered to be equal to any other type during type
  16446. %% checking.
  16447. The free variables become local variables that are initialized with
  16448. their values in the closure.
  16449. Closure conversion turns every function into a tuple, so the type
  16450. annotations in the program must also be translated. We recommend
  16451. defining an auxiliary recursive function for this purpose. Function
  16452. types should be translated as follows:
  16453. %
  16454. {\if\edition\racketEd
  16455. \begin{lstlisting}
  16456. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16457. |$\Rightarrow$|
  16458. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16459. \end{lstlisting}
  16460. \fi}
  16461. {\if\edition\pythonEd\pythonColor
  16462. \begin{lstlisting}
  16463. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16464. |$\Rightarrow$|
  16465. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16466. \end{lstlisting}
  16467. \fi}
  16468. %
  16469. This type indicates that the first thing in the tuple is a
  16470. function. The first parameter of the function is a tuple (a closure)
  16471. and the rest of the parameters are the ones from the original
  16472. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16473. omits the types of the free variables because (1) those types are not
  16474. available in this context, and (2) we do not need them in the code that
  16475. is generated for function application. So this type describes only the
  16476. first component of the closure tuple. At runtime the tuple may have
  16477. more components, but we ignore them at this point.
  16478. We transform function application into code that retrieves the
  16479. function from the closure and then calls the function, passing the
  16480. closure as the first argument. We place $e'$ in a temporary variable
  16481. to avoid code duplication.
  16482. \begin{center}
  16483. \begin{minipage}{\textwidth}
  16484. {\if\edition\racketEd
  16485. \begin{lstlisting}
  16486. (Apply |$e$| |$\itm{es}$|)
  16487. |$\Rightarrow$|
  16488. (Let |$\itm{tmp}$| |$e'$|
  16489. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16490. \end{lstlisting}
  16491. \fi}
  16492. %
  16493. {\if\edition\pythonEd\pythonColor
  16494. \begin{lstlisting}
  16495. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16496. |$\Rightarrow$|
  16497. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16498. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16499. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16500. \end{lstlisting}
  16501. \fi}
  16502. \end{minipage}
  16503. \end{center}
  16504. There is also the question of what to do with references to top-level
  16505. function definitions. To maintain a uniform translation of function
  16506. application, we turn function references into closures.
  16507. \begin{tabular}{lll}
  16508. \begin{minipage}{0.2\textwidth}
  16509. {\if\edition\racketEd
  16510. \begin{lstlisting}
  16511. (FunRef |$f$| |$n$|)
  16512. \end{lstlisting}
  16513. \fi}
  16514. {\if\edition\pythonEd\pythonColor
  16515. \begin{lstlisting}
  16516. FunRef(|$f$|, |$n$|)
  16517. \end{lstlisting}
  16518. \fi}
  16519. \end{minipage}
  16520. &
  16521. $\Rightarrow\qquad$
  16522. &
  16523. \begin{minipage}{0.5\textwidth}
  16524. {\if\edition\racketEd
  16525. \begin{lstlisting}
  16526. (Closure |$n$| (list (FunRef |$f$| |$n$|)))
  16527. \end{lstlisting}
  16528. \fi}
  16529. {\if\edition\pythonEd\pythonColor
  16530. \begin{lstlisting}
  16531. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16532. \end{lstlisting}
  16533. \fi}
  16534. \end{minipage}
  16535. \end{tabular} \\
  16536. We no longer need the annotated assignment statement \code{AnnAssign}
  16537. to support the type checking of \code{lambda} expressions, so we
  16538. translate it to a regular \code{Assign} statement.
  16539. The top-level function definitions need to be updated to take an extra
  16540. closure parameter, but that parameter is ignored in the body of those
  16541. functions.
  16542. \subsection{An Example Translation}
  16543. \label{sec:example-lambda}
  16544. Figure~\ref{fig:lexical-functions-example} shows the result of
  16545. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16546. program demonstrating lexical scoping that we discussed at the
  16547. beginning of this chapter.
  16548. \begin{figure}[tbp]
  16549. \begin{tcolorbox}[colback=white]
  16550. \begin{minipage}{0.8\textwidth}
  16551. {\if\edition\racketEd
  16552. % tests/lambda_test_6.rkt
  16553. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16554. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16555. (let ([y8 4])
  16556. (lambda: ([z9 : Integer]) : Integer
  16557. (+ x7 (+ y8 z9)))))
  16558. (define (main) : Integer
  16559. (let ([g0 ((fun-ref f6 1) 5)])
  16560. (let ([h1 ((fun-ref f6 1) 3)])
  16561. (+ (g0 11) (h1 15)))))
  16562. \end{lstlisting}
  16563. $\Rightarrow$
  16564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16565. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16566. (let ([y8 4])
  16567. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16568. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16569. (let ([x7 (vector-ref fvs3 1)])
  16570. (let ([y8 (vector-ref fvs3 2)])
  16571. (+ x7 (+ y8 z9)))))
  16572. (define (main) : Integer
  16573. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16574. ((vector-ref clos5 0) clos5 5))])
  16575. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16576. ((vector-ref clos6 0) clos6 3))])
  16577. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16578. \end{lstlisting}
  16579. \fi}
  16580. %
  16581. {\if\edition\pythonEd\pythonColor
  16582. % free_var.py
  16583. \begin{lstlisting}
  16584. def f(x: int) -> Callable[[int],int]:
  16585. y = 4
  16586. return lambda z: x + y + z
  16587. g = f(5)
  16588. h = f(3)
  16589. print(g(11) + h(15))
  16590. \end{lstlisting}
  16591. $\Rightarrow$
  16592. \begin{lstlisting}
  16593. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16594. x = fvs_1[1]
  16595. y = fvs_1[2]
  16596. return (x + y[0] + z)
  16597. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16598. y = (uninitialized(int),)
  16599. y[0] = 4
  16600. return closure{1}({lambda_0}, x, y)
  16601. def main() -> int:
  16602. g = (begin: clos_3 = closure{1}({f})
  16603. clos_3[0](clos_3, 5))
  16604. h = (begin: clos_4 = closure{1}({f})
  16605. clos_4[0](clos_4, 3))
  16606. print((begin: clos_5 = g
  16607. clos_5[0](clos_5, 11))
  16608. + (begin: clos_6 = h
  16609. clos_6[0](clos_6, 15)))
  16610. return 0
  16611. \end{lstlisting}
  16612. \fi}
  16613. \end{minipage}
  16614. \end{tcolorbox}
  16615. \caption{Example of closure conversion.}
  16616. \label{fig:lexical-functions-example}
  16617. \end{figure}
  16618. \begin{exercise}\normalfont\normalsize
  16619. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16620. Create five new programs that use \key{lambda} functions and make use of
  16621. lexical scoping. Test your compiler on these new programs and all
  16622. your previously created test programs.
  16623. \end{exercise}
  16624. \section{Expose Allocation}
  16625. \label{sec:expose-allocation-r5}
  16626. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16627. allocates and initializes a tuple, similar to the translation of the
  16628. tuple creation in section~\ref{sec:expose-allocation}. The main
  16629. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16630. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16631. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16632. type, but only a single element tuple type. The types of the tuple
  16633. elements that correspond to the free variables of the closure should
  16634. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16635. can be used to adjust the result type.
  16636. \section{Explicate Control and \LangCLam{}}
  16637. \label{sec:explicate-r5}
  16638. The output language of \code{explicate\_control} is \LangCLam{}; the
  16639. definition of its abstract syntax is shown in
  16640. figure~\ref{fig:Clam-syntax}.
  16641. %
  16642. \racket{The only differences with respect to \LangCFun{} are the
  16643. addition of the \code{AllocateClosure} form to the grammar for
  16644. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16645. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16646. similar to the handling of other expressions such as primitive
  16647. operators.}
  16648. %
  16649. \python{The differences with respect to \LangCFun{} are the
  16650. additions of \code{Uninitialized}, \code{AllocateClosure},
  16651. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16652. \code{explicate\_control} pass is similar to the handling of other
  16653. expressions such as primitive operators.}
  16654. \newcommand{\ClambdaASTRacket}{
  16655. \begin{array}{lcl}
  16656. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16657. \itm{op} &::= & \code{procedure-arity}
  16658. \end{array}
  16659. }
  16660. \newcommand{\ClambdaASTPython}{
  16661. \begin{array}{lcl}
  16662. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16663. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16664. &\MID& \ARITY{\Atm}
  16665. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16666. \end{array}
  16667. }
  16668. \begin{figure}[tp]
  16669. \begin{tcolorbox}[colback=white]
  16670. \small
  16671. {\if\edition\racketEd
  16672. \[
  16673. \begin{array}{l}
  16674. \gray{\CvarASTRacket} \\ \hline
  16675. \gray{\CifASTRacket} \\ \hline
  16676. \gray{\CloopASTRacket} \\ \hline
  16677. \gray{\CtupASTRacket} \\ \hline
  16678. \gray{\CfunASTRacket} \\ \hline
  16679. \ClambdaASTRacket \\
  16680. \begin{array}{lcl}
  16681. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16682. \end{array}
  16683. \end{array}
  16684. \]
  16685. \fi}
  16686. {\if\edition\pythonEd\pythonColor
  16687. \[
  16688. \begin{array}{l}
  16689. \gray{\CifASTPython} \\ \hline
  16690. \gray{\CtupASTPython} \\ \hline
  16691. \gray{\CfunASTPython} \\ \hline
  16692. \ClambdaASTPython \\
  16693. \begin{array}{lcl}
  16694. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16695. \end{array}
  16696. \end{array}
  16697. \]
  16698. \fi}
  16699. \end{tcolorbox}
  16700. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16701. \label{fig:Clam-syntax}
  16702. \index{subject}{Clambda@\LangCLam{} abstract syntax}
  16703. \end{figure}
  16704. \section{Select Instructions}
  16705. \label{sec:select-instructions-Llambda}
  16706. \index{subject}{select instructions}
  16707. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16708. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16709. (section~\ref{sec:select-instructions-gc}). The only difference is
  16710. that you should place the \itm{arity} in the tag that is stored at
  16711. position $0$ of the tuple. Recall that in
  16712. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16713. was not used. We store the arity in the $5$ bits starting at position
  16714. $58$.
  16715. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16716. instructions that access the tag from position $0$ of the vector and
  16717. extract the $5$ bits starting at position $58$ from the tag.}
  16718. %
  16719. \python{Compile a call to the \code{arity} operator to a sequence of
  16720. instructions that access the tag from position $0$ of the tuple
  16721. (representing a closure) and extract the $5$ bits starting at position
  16722. $58$ from the tag.}
  16723. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16724. needed for the compilation of \LangLam{}.
  16725. \begin{figure}[bthp]
  16726. \begin{tcolorbox}[colback=white]
  16727. {\if\edition\racketEd
  16728. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16729. \node (Lfun) at (0,2) {\large \LangLam{}};
  16730. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16731. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16732. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16733. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16734. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16735. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16736. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16737. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16738. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16739. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16740. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16741. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16742. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16743. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16744. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16745. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16746. \path[->,bend left=15] (Lfun) edge [above] node
  16747. {\ttfamily\footnotesize shrink} (Lfun-2);
  16748. \path[->,bend left=15] (Lfun-2) edge [above] node
  16749. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16750. \path[->,bend left=15] (Lfun-3) edge [above] node
  16751. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16752. \path[->,bend left=15] (F1-0) edge [left] node
  16753. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16754. \path[->,bend left=15] (F1-1) edge [below] node
  16755. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16756. \path[->,bend right=15] (F1-2) edge [above] node
  16757. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16758. \path[->,bend right=15] (F1-3) edge [above] node
  16759. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16760. \path[->,bend left=15] (F1-4) edge [right] node
  16761. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16762. \path[->,bend right=15] (F1-5) edge [below] node
  16763. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16764. \path[->,bend left=15] (F1-6) edge [above] node
  16765. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16766. \path[->] (C3-2) edge [right] node
  16767. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16768. \path[->,bend right=15] (x86-2) edge [right] node
  16769. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16770. \path[->,bend right=15] (x86-2-1) edge [below] node
  16771. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16772. \path[->,bend right=15] (x86-2-2) edge [right] node
  16773. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16774. \path[->,bend left=15] (x86-3) edge [above] node
  16775. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16776. \path[->,bend left=15] (x86-4) edge [right] node
  16777. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16778. \end{tikzpicture}
  16779. \fi}
  16780. {\if\edition\pythonEd\pythonColor
  16781. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16782. \node (Lfun) at (0,2) {\large \LangLam{}};
  16783. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16784. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16785. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16786. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16787. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16788. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16789. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16790. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16791. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16792. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16793. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16794. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16795. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16796. \path[->,bend left=15] (Lfun) edge [above] node
  16797. {\ttfamily\footnotesize shrink} (Lfun-2);
  16798. \path[->,bend left=15] (Lfun-2) edge [above] node
  16799. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16800. \path[->,bend left=15] (Lfun-3) edge [above] node
  16801. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16802. \path[->,bend left=15] (F1-0) edge [left] node
  16803. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16804. \path[->,bend left=15] (F1-1) edge [below] node
  16805. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16806. \path[->,bend left=15] (F1-2) edge [below] node
  16807. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16808. \path[->,bend right=15] (F1-3) edge [above] node
  16809. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16810. \path[->,bend right=15] (F1-5) edge [right] node
  16811. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16812. \path[->,bend left=15] (F1-6) edge [right] node
  16813. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16814. \path[->,bend right=15] (C3-2) edge [right] node
  16815. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16816. \path[->,bend right=15] (x86-2) edge [below] node
  16817. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16818. \path[->,bend right=15] (x86-3) edge [below] node
  16819. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16820. \path[->,bend left=15] (x86-4) edge [above] node
  16821. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16822. \end{tikzpicture}
  16823. \fi}
  16824. \end{tcolorbox}
  16825. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16826. functions.}
  16827. \label{fig:Llambda-passes}
  16828. \end{figure}
  16829. \clearpage
  16830. \section{Challenge: Optimize Closures}
  16831. \label{sec:optimize-closures}
  16832. In this chapter we compile lexically scoped functions into a
  16833. relatively efficient representation: flat closures. However, even this
  16834. representation comes with some overhead. For example, consider the
  16835. following program with a function \code{tail\_sum} that does not have
  16836. any free variables and where all the uses of \code{tail\_sum} are in
  16837. applications in which we know that only \code{tail\_sum} is being applied
  16838. (and not any other functions):
  16839. \begin{center}
  16840. \begin{minipage}{0.95\textwidth}
  16841. {\if\edition\racketEd
  16842. \begin{lstlisting}
  16843. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16844. (if (eq? n 0)
  16845. s
  16846. (tail_sum (- n 1) (+ n s))))
  16847. (+ (tail_sum 3 0) 36)
  16848. \end{lstlisting}
  16849. \fi}
  16850. {\if\edition\pythonEd\pythonColor
  16851. \begin{lstlisting}
  16852. def tail_sum(n : int, s : int) -> int:
  16853. if n == 0:
  16854. return s
  16855. else:
  16856. return tail_sum(n - 1, n + s)
  16857. print(tail_sum(3, 0) + 36)
  16858. \end{lstlisting}
  16859. \fi}
  16860. \end{minipage}
  16861. \end{center}
  16862. As described in this chapter, we uniformly apply closure conversion to
  16863. all functions, obtaining the following output for this program:
  16864. \begin{center}
  16865. \begin{minipage}{0.95\textwidth}
  16866. {\if\edition\racketEd
  16867. \begin{lstlisting}
  16868. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16869. (if (eq? n2 0)
  16870. s3
  16871. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16872. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16873. (define (main) : Integer
  16874. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16875. ((vector-ref clos6 0) clos6 3 0)) 27))
  16876. \end{lstlisting}
  16877. \fi}
  16878. {\if\edition\pythonEd\pythonColor
  16879. \begin{lstlisting}
  16880. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16881. if n_0 == 0:
  16882. return s_1
  16883. else:
  16884. return (begin: clos_2 = (tail_sum,)
  16885. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16886. def main() -> int :
  16887. print((begin: clos_4 = (tail_sum,)
  16888. clos_4[0](clos_4, 3, 0)) + 36)
  16889. return 0
  16890. \end{lstlisting}
  16891. \fi}
  16892. \end{minipage}
  16893. \end{center}
  16894. If this program were compiled according to the previous chapter, there
  16895. would be no allocation and the calls to \code{tail\_sum} would be
  16896. direct calls. In contrast, the program presented here allocates memory
  16897. for each closure and the calls to \code{tail\_sum} are indirect. These
  16898. two differences incur considerable overhead in a program such as this,
  16899. in which the allocations and indirect calls occur inside a tight loop.
  16900. One might think that this problem is trivial to solve: can't we just
  16901. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16902. and compile them to direct calls instead of treating it like a call to
  16903. a closure? We would also drop the new \code{fvs} parameter of
  16904. \code{tail\_sum}.
  16905. %
  16906. However, this problem is not so trivial, because a global function may
  16907. \emph{escape} and become involved in applications that also involve
  16908. closures. Consider the following example in which the application
  16909. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16910. application because the \code{lambda} may flow into \code{f}, but the
  16911. \code{inc} function might also flow into \code{f}:
  16912. \begin{center}
  16913. \begin{minipage}{\textwidth}
  16914. % lambda_test_30.rkt
  16915. {\if\edition\racketEd
  16916. \begin{lstlisting}
  16917. (define (inc [x : Integer]) : Integer
  16918. (+ x 1))
  16919. (let ([y (read)])
  16920. (let ([f (if (eq? (read) 0)
  16921. inc
  16922. (lambda: ([x : Integer]) : Integer (- x y)))])
  16923. (f 41)))
  16924. \end{lstlisting}
  16925. \fi}
  16926. {\if\edition\pythonEd\pythonColor
  16927. \begin{lstlisting}
  16928. def add1(x : int) -> int:
  16929. return x + 1
  16930. y = input_int()
  16931. g : Callable[[int], int] = lambda x: x - y
  16932. f = add1 if input_int() == 0 else g
  16933. print(f(41))
  16934. \end{lstlisting}
  16935. \fi}
  16936. \end{minipage}
  16937. \end{center}
  16938. If a global function name is used in any way other than as the
  16939. operator in a direct call, then we say that the function
  16940. \emph{escapes}. If a global function does not escape, then we do not
  16941. need to perform closure conversion on the function.
  16942. \begin{exercise}\normalfont\normalsize
  16943. Implement an auxiliary function for detecting which global
  16944. functions escape. Using that function, implement an improved version
  16945. of closure conversion that does not apply closure conversion to
  16946. global functions that do not escape but instead compiles them as
  16947. regular functions. Create several new test cases that check whether
  16948. your compiler properly detects whether global functions escape or not.
  16949. \end{exercise}
  16950. So far we have reduced the overhead of calling global functions, but
  16951. it would also be nice to reduce the overhead of calling a
  16952. \code{lambda} when we can determine at compile time which
  16953. \code{lambda} will be called. We refer to such calls as \emph{known
  16954. calls}. Consider the following example in which a \code{lambda} is
  16955. bound to \code{f} and then applied.
  16956. {\if\edition\racketEd
  16957. % lambda_test_9.rkt
  16958. \begin{lstlisting}
  16959. (let ([y (read)])
  16960. (let ([f (lambda: ([x : Integer]) : Integer
  16961. (+ x y))])
  16962. (f 21)))
  16963. \end{lstlisting}
  16964. \fi}
  16965. {\if\edition\pythonEd\pythonColor
  16966. \begin{lstlisting}
  16967. y = input_int()
  16968. f : Callable[[int],int] = lambda x: x + y
  16969. print(f(21))
  16970. \end{lstlisting}
  16971. \fi}
  16972. %
  16973. \noindent Closure conversion compiles the application
  16974. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16975. %
  16976. {\if\edition\racketEd
  16977. \begin{lstlisting}
  16978. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16979. (let ([y2 (vector-ref fvs6 1)])
  16980. (+ x3 y2)))
  16981. (define (main) : Integer
  16982. (let ([y2 (read)])
  16983. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16984. ((vector-ref f4 0) f4 21))))
  16985. \end{lstlisting}
  16986. \fi}
  16987. {\if\edition\pythonEd\pythonColor
  16988. \begin{lstlisting}
  16989. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16990. y_1 = fvs_4[1]
  16991. return x_2 + y_1[0]
  16992. def main() -> int:
  16993. y_1 = (777,)
  16994. y_1[0] = input_int()
  16995. f_0 = (lambda_3, y_1)
  16996. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16997. return 0
  16998. \end{lstlisting}
  16999. \fi}
  17000. %
  17001. \noindent However, we can instead compile the application
  17002. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  17003. %
  17004. {\if\edition\racketEd
  17005. \begin{lstlisting}
  17006. (define (main) : Integer
  17007. (let ([y2 (read)])
  17008. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  17009. ((fun-ref lambda5 1) f4 21))))
  17010. \end{lstlisting}
  17011. \fi}
  17012. {\if\edition\pythonEd\pythonColor
  17013. \begin{lstlisting}
  17014. def main() -> int:
  17015. y_1 = (777,)
  17016. y_1[0] = input_int()
  17017. f_0 = (lambda_3, y_1)
  17018. print(lambda_3(f_0, 21))
  17019. return 0
  17020. \end{lstlisting}
  17021. \fi}
  17022. The problem of determining which \code{lambda} will be called from a
  17023. particular application is quite challenging in general and the topic
  17024. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  17025. following exercise we recommend that you compile an application to a
  17026. direct call when the operator is a variable and \racket{the variable
  17027. is \code{let}-bound to a closure}\python{the previous assignment to
  17028. the variable is a closure}. This can be accomplished by maintaining
  17029. an environment that maps variables to function names. Extend the
  17030. environment whenever you encounter a closure on the right-hand side of
  17031. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  17032. name of the global function for the closure. This pass should come
  17033. after closure conversion.
  17034. \begin{exercise}\normalfont\normalsize
  17035. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  17036. compiles known calls into direct calls. Verify that your compiler is
  17037. successful in this regard on several example programs.
  17038. \end{exercise}
  17039. These exercises only scratch the surface of closure optimization. A
  17040. good next step for the interested reader is to look at the work of
  17041. \citet{Keep:2012ab}.
  17042. \section{Further Reading}
  17043. The notion of lexically scoped functions predates modern computers by
  17044. about a decade. They were invented by \citet{Church:1932aa}, who
  17045. proposed the lambda calculus as a foundation for logic. Anonymous
  17046. functions were included in the LISP~\citep{McCarthy:1960dz}
  17047. programming language but were initially dynamically scoped. The Scheme
  17048. dialect of LISP adopted lexical scoping, and
  17049. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  17050. Scheme programs. However, environments were represented as linked
  17051. lists, so variable look-up was linear in the size of the
  17052. environment. \citet{Appel91} gives a detailed description of several
  17053. closure representations. In this chapter we represent environments
  17054. using flat closures, which were invented by
  17055. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  17056. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  17057. closures, variable look-up is constant time but the time to create a
  17058. closure is proportional to the number of its free variables. Flat
  17059. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  17060. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  17061. % todo: related work on assignment conversion (e.g. orbit and rabbit
  17062. % compilers)
  17063. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17064. \chapter{Dynamic Typing}
  17065. \label{ch:Ldyn}
  17066. \index{subject}{dynamic typing}
  17067. \setcounter{footnote}{0}
  17068. In this chapter we learn how to compile \LangDyn{}, a dynamically
  17069. typed language that is a subset of \racket{Racket}\python{Python}. The
  17070. focus on dynamic typing is in contrast to the previous chapters, which
  17071. have studied the compilation of statically typed languages. In
  17072. dynamically typed languages such as \LangDyn{}, a particular
  17073. expression may produce a value of a different type each time it is
  17074. executed. Consider the following example with a conditional \code{if}
  17075. expression that may return a Boolean or an integer depending on the
  17076. input to the program:
  17077. % part of dynamic_test_25.rkt
  17078. {\if\edition\racketEd
  17079. \begin{lstlisting}
  17080. (not (if (eq? (read) 1) #f 0))
  17081. \end{lstlisting}
  17082. \fi}
  17083. {\if\edition\pythonEd\pythonColor
  17084. \begin{lstlisting}
  17085. not (False if input_int() == 1 else 0)
  17086. \end{lstlisting}
  17087. \fi}
  17088. Languages that allow expressions to produce different kinds of values
  17089. are called \emph{polymorphic}, a word composed of the Greek roots
  17090. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  17091. There are several kinds of polymorphism in programming languages, such as
  17092. subtype polymorphism\index{subject}{subtype polymorphism} and
  17093. parametric polymorphism\index{subject}{parametric polymorphism}
  17094. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  17095. study in this chapter does not have a special name; it is the kind
  17096. that arises in dynamically typed languages.
  17097. Another characteristic of dynamically typed languages is that
  17098. their primitive operations, such as \code{not}, are often defined to operate
  17099. on many different types of values. In fact, in
  17100. \racket{Racket}\python{Python}, the \code{not} operator produces a
  17101. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  17102. given anything else it returns \FALSE{}.
  17103. Furthermore, even when primitive operations restrict their inputs to
  17104. values of a certain type, this restriction is enforced at runtime
  17105. instead of during compilation. For example, the tuple read
  17106. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  17107. results in a runtime error because the first argument must
  17108. be a tuple, not a Boolean.
  17109. \section{The \LangDyn{} Language}
  17110. \newcommand{\LdynGrammarRacket}{
  17111. \begin{array}{rcl}
  17112. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  17113. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  17114. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  17115. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  17116. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  17117. \end{array}
  17118. }
  17119. \newcommand{\LdynASTRacket}{
  17120. \begin{array}{lcl}
  17121. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17122. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  17123. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  17124. \end{array}
  17125. }
  17126. \begin{figure}[tp]
  17127. \centering
  17128. \begin{tcolorbox}[colback=white]
  17129. \small
  17130. {\if\edition\racketEd
  17131. \[
  17132. \begin{array}{l}
  17133. \gray{\LintGrammarRacket{}} \\ \hline
  17134. \gray{\LvarGrammarRacket{}} \\ \hline
  17135. \gray{\LifGrammarRacket{}} \\ \hline
  17136. \gray{\LwhileGrammarRacket} \\ \hline
  17137. \gray{\LtupGrammarRacket} \\ \hline
  17138. \LdynGrammarRacket \\
  17139. \begin{array}{rcl}
  17140. \LangDynM{} &::=& \Def\ldots\; \Exp
  17141. \end{array}
  17142. \end{array}
  17143. \]
  17144. \fi}
  17145. {\if\edition\pythonEd\pythonColor
  17146. \[
  17147. \begin{array}{rcl}
  17148. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17149. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17150. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17151. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17152. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17153. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17154. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17155. \MID \CLEN{\Exp} \\
  17156. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17157. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17158. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17159. \MID \Var\mathop{\key{=}}\Exp \\
  17160. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17161. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17162. &\MID& \CRETURN{\Exp} \\
  17163. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17164. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17165. \end{array}
  17166. \]
  17167. \fi}
  17168. \end{tcolorbox}
  17169. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17170. \label{fig:r7-concrete-syntax}
  17171. \index{subject}{Ldyn@\LangDyn{} concrete syntax}
  17172. \end{figure}
  17173. \begin{figure}[tp]
  17174. \centering
  17175. \begin{tcolorbox}[colback=white]
  17176. \small
  17177. {\if\edition\racketEd
  17178. \[
  17179. \begin{array}{l}
  17180. \gray{\LintASTRacket{}} \\ \hline
  17181. \gray{\LvarASTRacket{}} \\ \hline
  17182. \gray{\LifASTRacket{}} \\ \hline
  17183. \gray{\LwhileASTRacket} \\ \hline
  17184. \gray{\LtupASTRacket} \\ \hline
  17185. \LdynASTRacket \\
  17186. \begin{array}{lcl}
  17187. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17188. \end{array}
  17189. \end{array}
  17190. \]
  17191. \fi}
  17192. {\if\edition\pythonEd\pythonColor
  17193. \[
  17194. \begin{array}{rcl}
  17195. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17196. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17197. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17198. \MID \code{Is()} \\
  17199. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17200. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17201. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17202. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17203. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17204. &\MID& \VAR{\Var{}}
  17205. \MID \BOOL{\itm{bool}}
  17206. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17207. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17208. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17209. &\MID& \LEN{\Exp} \\
  17210. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17211. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17212. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17213. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17214. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17215. &\MID& \RETURN{\Exp} \\
  17216. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17217. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17218. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17219. \end{array}
  17220. \]
  17221. \fi}
  17222. \end{tcolorbox}
  17223. \caption{The abstract syntax of \LangDyn{}.}
  17224. \label{fig:r7-syntax}
  17225. \index{subject}{Ldyn@\LangDyn{} abstract syntax}
  17226. \end{figure}
  17227. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17228. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17229. %
  17230. There is no type checker for \LangDyn{} because it checks types only
  17231. at runtime.
  17232. The definitional interpreter for \LangDyn{} is presented in
  17233. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17234. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17235. \INT{n}. Instead of simply returning the integer \code{n} (as
  17236. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17237. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17238. value} that combines an underlying value with a tag that identifies
  17239. what kind of value it is. We define the following \racket{struct}\python{class}
  17240. to represent tagged values:
  17241. %
  17242. {\if\edition\racketEd
  17243. \begin{lstlisting}
  17244. (struct Tagged (value tag) #:transparent)
  17245. \end{lstlisting}
  17246. \fi}
  17247. {\if\edition\pythonEd\pythonColor
  17248. \begin{minipage}{\textwidth}
  17249. \begin{lstlisting}
  17250. @dataclass(eq=True)
  17251. class Tagged(Value):
  17252. value : Value
  17253. tag : str
  17254. def __str__(self):
  17255. return str(self.value)
  17256. \end{lstlisting}
  17257. \end{minipage}
  17258. \fi}
  17259. %
  17260. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17261. \code{Vector}, and \code{Procedure}.}
  17262. %
  17263. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17264. \skey{tuple}, and \skey{function}.}
  17265. %
  17266. Tags are closely related to types but do not always capture all the
  17267. information that a type does.
  17268. %
  17269. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17270. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17271. Any)} is tagged with \code{Procedure}.}
  17272. %
  17273. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17274. is tagged with \skey{tuple} and a function of type
  17275. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17276. is tagged with \skey{function}.}
  17277. Next consider the match case for accessing the element of a tuple.
  17278. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17279. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17280. argument is a tuple and the second is an integer.
  17281. \racket{
  17282. If they are not, a \code{trapped-error} is raised. Recall from
  17283. section~\ref{sec:interp_Lint} that when a definition interpreter
  17284. raises a \code{trapped-error} error, the compiled code must also
  17285. signal an error by exiting with return code \code{255}. A
  17286. \code{trapped-error} is also raised if the index is not less than the
  17287. length of the vector.
  17288. }
  17289. %
  17290. \python{If they are not, an exception is raised. The compiled code
  17291. must also signal an error by exiting with return code \code{255}. A
  17292. exception is also raised if the index is not less than the length of the
  17293. tuple or if it is negative.}
  17294. \begin{figure}[tbp]
  17295. \begin{tcolorbox}[colback=white]
  17296. {\if\edition\racketEd
  17297. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17298. (define ((interp-Ldyn-exp env) ast)
  17299. (define recur (interp-Ldyn-exp env))
  17300. (match ast
  17301. [(Var x) (unbox (lookup x env)]
  17302. [(Int n) (Tagged n 'Integer)]
  17303. [(Bool b) (Tagged b 'Boolean)]
  17304. [(Lambda xs rt body)
  17305. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17306. [(Prim 'vector es)
  17307. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17308. [(Prim 'vector-ref (list e1 e2))
  17309. (define vec (recur e1)) (define i (recur e2))
  17310. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17311. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17312. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17313. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17314. [(Prim 'vector-set! (list e1 e2 e3))
  17315. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17316. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17317. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17318. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17319. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17320. (Tagged (void) 'Void)]
  17321. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17322. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17323. [(Prim 'or (list e1 e2))
  17324. (define v1 (recur e1))
  17325. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17326. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17327. [(Prim op (list e1))
  17328. #:when (set-member? type-predicates op)
  17329. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17330. [(Prim op es)
  17331. (define args (map recur es))
  17332. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17333. (unless (for/or ([expected-tags (op-tags op)])
  17334. (equal? expected-tags tags))
  17335. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17336. (tag-value
  17337. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17338. [(If q t f)
  17339. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17340. [(Apply f es)
  17341. (define new-f (recur f)) (define args (map recur es))
  17342. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17343. (match f-val
  17344. [`(function ,xs ,body ,lam-env)
  17345. (unless (eq? (length xs) (length args))
  17346. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17347. (define new-env (append (map cons xs args) lam-env))
  17348. ((interp-Ldyn-exp new-env) body)]
  17349. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17350. \end{lstlisting}
  17351. \fi}
  17352. {\if\edition\pythonEd\pythonColor
  17353. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17354. class InterpLdyn(InterpLlambda):
  17355. def interp_exp(self, e, env):
  17356. match e:
  17357. case Constant(n):
  17358. return self.tag(super().interp_exp(e, env))
  17359. case Tuple(es, Load()):
  17360. return self.tag(super().interp_exp(e, env))
  17361. case Lambda(params, body):
  17362. return self.tag(super().interp_exp(e, env))
  17363. case Call(Name('input_int'), []):
  17364. return self.tag(super().interp_exp(e, env))
  17365. case BinOp(left, Add(), right):
  17366. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17367. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17368. case BinOp(left, Sub(), right):
  17369. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17370. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17371. case UnaryOp(USub(), e1):
  17372. v = self.interp_exp(e1, env)
  17373. return self.tag(- self.untag(v, 'int', e))
  17374. case IfExp(test, body, orelse):
  17375. v = self.interp_exp(test, env)
  17376. if self.untag(v, 'bool', e):
  17377. return self.interp_exp(body, env)
  17378. else:
  17379. return self.interp_exp(orelse, env)
  17380. case UnaryOp(Not(), e1):
  17381. v = self.interp_exp(e1, env)
  17382. return self.tag(not self.untag(v, 'bool', e))
  17383. case BoolOp(And(), values):
  17384. left = values[0]; right = values[1]
  17385. l = self.interp_exp(left, env)
  17386. if self.untag(l, 'bool', e):
  17387. return self.interp_exp(right, env)
  17388. else:
  17389. return self.tag(False)
  17390. case BoolOp(Or(), values):
  17391. left = values[0]; right = values[1]
  17392. l = self.interp_exp(left, env)
  17393. if self.untag(l, 'bool', e):
  17394. return self.tag(True)
  17395. else:
  17396. return self.interp_exp(right, env)
  17397. \end{lstlisting}
  17398. \fi}
  17399. \end{tcolorbox}
  17400. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17401. \label{fig:interp-Ldyn}
  17402. \end{figure}
  17403. {\if\edition\pythonEd\pythonColor
  17404. \begin{figure}[tbp]
  17405. \begin{tcolorbox}[colback=white]
  17406. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17407. # interp_exp continued
  17408. case Compare(left, [cmp], [right]):
  17409. l = self.interp_exp(left, env)
  17410. r = self.interp_exp(right, env)
  17411. if l.tag == r.tag:
  17412. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17413. else:
  17414. raise Exception('interp Compare unexpected '
  17415. + repr(l) + ' ' + repr(r))
  17416. case Subscript(tup, index, Load()):
  17417. t = self.interp_exp(tup, env)
  17418. n = self.interp_exp(index, env)
  17419. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17420. case Call(Name('len'), [tup]):
  17421. t = self.interp_exp(tup, env)
  17422. return self.tag(len(self.untag(t, 'tuple', e)))
  17423. case _:
  17424. return self.tag(super().interp_exp(e, env))
  17425. def interp_stmt(self, s, env, cont):
  17426. match s:
  17427. case If(test, body, orelse):
  17428. v = self.interp_exp(test, env)
  17429. match self.untag(v, 'bool', s):
  17430. case True:
  17431. return self.interp_stmts(body + cont, env)
  17432. case False:
  17433. return self.interp_stmts(orelse + cont, env)
  17434. case While(test, body, []):
  17435. v = self.interp_exp(test, env)
  17436. if self.untag(v, 'bool', test):
  17437. self.interp_stmts(body + [s] + cont, env)
  17438. else:
  17439. return self.interp_stmts(cont, env)
  17440. case Assign([Subscript(tup, index)], value):
  17441. tup = self.interp_exp(tup, env)
  17442. index = self.interp_exp(index, env)
  17443. tup_v = self.untag(tup, 'tuple', s)
  17444. index_v = self.untag(index, 'int', s)
  17445. tup_v[index_v] = self.interp_exp(value, env)
  17446. return self.interp_stmts(cont, env)
  17447. case FunctionDef(name, params, bod, dl, returns, comment):
  17448. if isinstance(params, ast.arguments):
  17449. ps = [p.arg for p in params.args]
  17450. else:
  17451. ps = [x for (x,t) in params]
  17452. env[name] = self.tag(Function(name, ps, bod, env))
  17453. return self.interp_stmts(cont, env)
  17454. case _:
  17455. return super().interp_stmt(s, env, cont)
  17456. \end{lstlisting}
  17457. \end{tcolorbox}
  17458. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17459. \label{fig:interp-Ldyn-2}
  17460. \end{figure}
  17461. \fi}
  17462. \begin{figure}[tbp]
  17463. \begin{tcolorbox}[colback=white]
  17464. {\if\edition\racketEd
  17465. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17466. (define (interp-op op)
  17467. (match op
  17468. ['+ fx+]
  17469. ['- fx-]
  17470. ['read read-fixnum]
  17471. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17472. ['< (lambda (v1 v2)
  17473. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17474. ['<= (lambda (v1 v2)
  17475. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17476. ['> (lambda (v1 v2)
  17477. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17478. ['>= (lambda (v1 v2)
  17479. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17480. ['boolean? boolean?]
  17481. ['integer? fixnum?]
  17482. ['void? void?]
  17483. ['vector? vector?]
  17484. ['vector-length vector-length]
  17485. ['procedure? (match-lambda
  17486. [`(functions ,xs ,body ,env) #t] [else #f])]
  17487. [else (error 'interp-op "unknown operator" op)]))
  17488. (define (op-tags op)
  17489. (match op
  17490. ['+ '((Integer Integer))]
  17491. ['- '((Integer Integer) (Integer))]
  17492. ['read '(())]
  17493. ['not '((Boolean))]
  17494. ['< '((Integer Integer))]
  17495. ['<= '((Integer Integer))]
  17496. ['> '((Integer Integer))]
  17497. ['>= '((Integer Integer))]
  17498. ['vector-length '((Vector))]))
  17499. (define type-predicates
  17500. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17501. (define (tag-value v)
  17502. (cond [(boolean? v) (Tagged v 'Boolean)]
  17503. [(fixnum? v) (Tagged v 'Integer)]
  17504. [(procedure? v) (Tagged v 'Procedure)]
  17505. [(vector? v) (Tagged v 'Vector)]
  17506. [(void? v) (Tagged v 'Void)]
  17507. [else (error 'tag-value "unidentified value ~a" v)]))
  17508. (define (check-tag val expected ast)
  17509. (define tag (Tagged-tag val))
  17510. (unless (eq? tag expected)
  17511. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17512. \end{lstlisting}
  17513. \fi}
  17514. {\if\edition\pythonEd\pythonColor
  17515. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17516. class InterpLdyn(InterpLlambda):
  17517. def tag(self, v):
  17518. if v is True or v is False:
  17519. return Tagged(v, 'bool')
  17520. elif isinstance(v, int):
  17521. return Tagged(v, 'int')
  17522. elif isinstance(v, Function):
  17523. return Tagged(v, 'function')
  17524. elif isinstance(v, tuple):
  17525. return Tagged(v, 'tuple')
  17526. elif isinstance(v, type(None)):
  17527. return Tagged(v, 'none')
  17528. else:
  17529. raise Exception('tag: unexpected ' + repr(v))
  17530. def untag(self, v, expected_tag, ast):
  17531. match v:
  17532. case Tagged(val, tag) if tag == expected_tag:
  17533. return val
  17534. case _:
  17535. raise TrappedError('expected Tagged value with '
  17536. + expected_tag + ', not ' + ' ' + repr(v))
  17537. def apply_fun(self, fun, args, e):
  17538. f = self.untag(fun, 'function', e)
  17539. return super().apply_fun(f, args, e)
  17540. \end{lstlisting}
  17541. \fi}
  17542. \end{tcolorbox}
  17543. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17544. \label{fig:interp-Ldyn-aux}
  17545. \end{figure}
  17546. %\clearpage
  17547. \section{Representation of Tagged Values}
  17548. The interpreter for \LangDyn{} introduced a new kind of value: the
  17549. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17550. represent tagged values at the bit level. Because almost every
  17551. operation in \LangDyn{} involves manipulating tagged values, the
  17552. representation must be efficient. Recall that all our values are 64
  17553. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17554. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17555. $011$ for procedures, and $101$ for the void value\python{,
  17556. \key{None}}. We define the following auxiliary function for mapping
  17557. types to tag codes:
  17558. %
  17559. {\if\edition\racketEd
  17560. \begin{align*}
  17561. \itm{tagof}(\key{Integer}) &= 001 \\
  17562. \itm{tagof}(\key{Boolean}) &= 100 \\
  17563. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17564. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17565. \itm{tagof}(\key{Void}) &= 101
  17566. \end{align*}
  17567. \fi}
  17568. {\if\edition\pythonEd\pythonColor
  17569. \begin{align*}
  17570. \itm{tagof}(\key{IntType()}) &= 001 \\
  17571. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17572. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17573. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17574. \itm{tagof}(\key{type(None)}) &= 101
  17575. \end{align*}
  17576. \fi}
  17577. %
  17578. This stealing of 3 bits comes at some price: integers are now restricted
  17579. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17580. affect tuples and procedures because those values are addresses, and
  17581. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17582. they are always $000$. Thus, we do not lose information by overwriting
  17583. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17584. to recover the original address.
  17585. To make tagged values into first-class entities, we can give them a
  17586. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17587. operations such as \code{Inject} and \code{Project} for creating and
  17588. using them, yielding the statically typed \LangAny{} intermediate
  17589. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17590. section~\ref{sec:compile-r7}; in the next section we describe the
  17591. \LangAny{} language in greater detail.
  17592. \section{The \LangAny{} Language}
  17593. \label{sec:Rany-lang}
  17594. \newcommand{\LanyASTRacket}{
  17595. \begin{array}{lcl}
  17596. \Type &::= & \ANYTY \\
  17597. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17598. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17599. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17600. \itm{op} &::= & \code{any-vector-length}
  17601. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17602. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17603. \MID \code{procedure?} \MID \code{void?} \\
  17604. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17605. \end{array}
  17606. }
  17607. \newcommand{\LanyASTPython}{
  17608. \begin{array}{lcl}
  17609. \Type &::= & \key{AnyType()} \\
  17610. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17611. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17612. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17613. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17614. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17615. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17616. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17617. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17618. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17619. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17620. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17621. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17622. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17623. \end{array}
  17624. }
  17625. \begin{figure}[tp]
  17626. \centering
  17627. \begin{tcolorbox}[colback=white]
  17628. \small
  17629. {\if\edition\racketEd
  17630. \[
  17631. \begin{array}{l}
  17632. \gray{\LintOpAST} \\ \hline
  17633. \gray{\LvarASTRacket{}} \\ \hline
  17634. \gray{\LifASTRacket{}} \\ \hline
  17635. \gray{\LwhileASTRacket{}} \\ \hline
  17636. \gray{\LtupASTRacket{}} \\ \hline
  17637. \gray{\LfunASTRacket} \\ \hline
  17638. \gray{\LlambdaASTRacket} \\ \hline
  17639. \LanyASTRacket \\
  17640. \begin{array}{lcl}
  17641. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17642. \end{array}
  17643. \end{array}
  17644. \]
  17645. \fi}
  17646. {\if\edition\pythonEd\pythonColor
  17647. \[
  17648. \begin{array}{l}
  17649. \gray{\LintASTPython} \\ \hline
  17650. \gray{\LvarASTPython{}} \\ \hline
  17651. \gray{\LifASTPython{}} \\ \hline
  17652. \gray{\LwhileASTPython{}} \\ \hline
  17653. \gray{\LtupASTPython{}} \\ \hline
  17654. \gray{\LfunASTPython} \\ \hline
  17655. \gray{\LlambdaASTPython} \\ \hline
  17656. \LanyASTPython \\
  17657. \begin{array}{lcl}
  17658. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17659. \end{array}
  17660. \end{array}
  17661. \]
  17662. \fi}
  17663. \end{tcolorbox}
  17664. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17665. \label{fig:Lany-syntax}
  17666. \index{subject}{Lany@\LangAny{} abstract syntax}
  17667. \end{figure}
  17668. The definition of the abstract syntax of \LangAny{} is given in
  17669. figure~\ref{fig:Lany-syntax}.
  17670. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17671. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17672. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17673. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17674. converts the tagged value produced by expression $e$ into a value of
  17675. type $T$ or halts the program if the type tag does not match $T$.
  17676. %
  17677. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17678. restricted to be a flat type (the nonterminal $\FType$) which
  17679. simplifies the implementation and complies with the needs for
  17680. compiling \LangDyn{}.
  17681. The \racket{\code{any-vector}} operators
  17682. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17683. operations so that they can be applied to a value of type
  17684. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17685. tuple operations in that the index is not restricted to a literal
  17686. integer in the grammar but is allowed to be any expression.
  17687. \racket{The type predicates such as
  17688. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17689. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17690. the predicate and return {\FALSE} otherwise.}
  17691. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17692. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17693. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17694. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17695. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17696. \begin{figure}[btp]
  17697. \begin{tcolorbox}[colback=white]
  17698. {\if\edition\racketEd
  17699. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17700. (define type-check-Lany-class
  17701. (class type-check-Llambda-class
  17702. (super-new)
  17703. (inherit check-type-equal?)
  17704. (define/override (type-check-exp env)
  17705. (lambda (e)
  17706. (define recur (type-check-exp env))
  17707. (match e
  17708. [(Inject e1 ty)
  17709. (unless (flat-ty? ty)
  17710. (error 'type-check "may only inject from flat type, not ~a" ty))
  17711. (define-values (new-e1 e-ty) (recur e1))
  17712. (check-type-equal? e-ty ty e)
  17713. (values (Inject new-e1 ty) 'Any)]
  17714. [(Project e1 ty)
  17715. (unless (flat-ty? ty)
  17716. (error 'type-check "may only project to flat type, not ~a" ty))
  17717. (define-values (new-e1 e-ty) (recur e1))
  17718. (check-type-equal? e-ty 'Any e)
  17719. (values (Project new-e1 ty) ty)]
  17720. [(Prim 'any-vector-length (list e1))
  17721. (define-values (e1^ t1) (recur e1))
  17722. (check-type-equal? t1 'Any e)
  17723. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17724. [(Prim 'any-vector-ref (list e1 e2))
  17725. (define-values (e1^ t1) (recur e1))
  17726. (define-values (e2^ t2) (recur e2))
  17727. (check-type-equal? t1 'Any e)
  17728. (check-type-equal? t2 'Integer e)
  17729. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17730. [(Prim 'any-vector-set! (list e1 e2 e3))
  17731. (define-values (e1^ t1) (recur e1))
  17732. (define-values (e2^ t2) (recur e2))
  17733. (define-values (e3^ t3) (recur e3))
  17734. (check-type-equal? t1 'Any e)
  17735. (check-type-equal? t2 'Integer e)
  17736. (check-type-equal? t3 'Any e)
  17737. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17738. [(Prim pred (list e1))
  17739. #:when (set-member? (type-predicates) pred)
  17740. (define-values (new-e1 e-ty) (recur e1))
  17741. (check-type-equal? e-ty 'Any e)
  17742. (values (Prim pred (list new-e1)) 'Boolean)]
  17743. [(Prim 'eq? (list arg1 arg2))
  17744. (define-values (e1 t1) (recur arg1))
  17745. (define-values (e2 t2) (recur arg2))
  17746. (match* (t1 t2)
  17747. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17748. [(other wise) (check-type-equal? t1 t2 e)])
  17749. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17750. [else ((super type-check-exp env) e)])))
  17751. ))
  17752. \end{lstlisting}
  17753. \fi}
  17754. {\if\edition\pythonEd\pythonColor
  17755. \begin{lstlisting}
  17756. class TypeCheckLany(TypeCheckLlambda):
  17757. def type_check_exp(self, e, env):
  17758. match e:
  17759. case Inject(value, typ):
  17760. self.check_exp(value, typ, env)
  17761. return AnyType()
  17762. case Project(value, typ):
  17763. self.check_exp(value, AnyType(), env)
  17764. return typ
  17765. case Call(Name('any_tuple_load'), [tup, index]):
  17766. self.check_exp(tup, AnyType(), env)
  17767. self.check_exp(index, IntType(), env)
  17768. return AnyType()
  17769. case Call(Name('any_len'), [tup]):
  17770. self.check_exp(tup, AnyType(), env)
  17771. return IntType()
  17772. case Call(Name('arity'), [fun]):
  17773. ty = self.type_check_exp(fun, env)
  17774. match ty:
  17775. case FunctionType(ps, rt):
  17776. return IntType()
  17777. case TupleType([FunctionType(ps,rs)]):
  17778. return IntType()
  17779. case _:
  17780. raise Exception('type check arity unexpected ' + repr(ty))
  17781. case Call(Name('make_any'), [value, tag]):
  17782. self.type_check_exp(value, env)
  17783. self.check_exp(tag, IntType(), env)
  17784. return AnyType()
  17785. case AnnLambda(params, returns, body):
  17786. new_env = {x:t for (x,t) in env.items()}
  17787. for (x,t) in params:
  17788. new_env[x] = t
  17789. return_t = self.type_check_exp(body, new_env)
  17790. self.check_type_equal(returns, return_t, e)
  17791. return FunctionType([t for (x,t) in params], return_t)
  17792. case _:
  17793. return super().type_check_exp(e, env)
  17794. \end{lstlisting}
  17795. \fi}
  17796. \end{tcolorbox}
  17797. \caption{Type checker for the \LangAny{} language.}
  17798. \label{fig:type-check-Lany}
  17799. \end{figure}
  17800. {\if\edition\racketEd
  17801. \begin{figure}[tbp]
  17802. \begin{tcolorbox}[colback=white]
  17803. \begin{lstlisting}
  17804. (define/override (operator-types)
  17805. (append
  17806. '((integer? . ((Any) . Boolean))
  17807. (vector? . ((Any) . Boolean))
  17808. (procedure? . ((Any) . Boolean))
  17809. (void? . ((Any) . Boolean)))
  17810. (super operator-types)))
  17811. (define/public (type-predicates)
  17812. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17813. (define/public (flat-ty? ty)
  17814. (match ty
  17815. [(or `Integer `Boolean `Void) #t]
  17816. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17817. [`(,ts ... -> ,rt)
  17818. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17819. [else #f]))
  17820. \end{lstlisting}
  17821. \end{tcolorbox}
  17822. \caption{Auxiliary methods for type checking \LangAny{}.}
  17823. \label{fig:type-check-Lany-aux}
  17824. \end{figure}
  17825. \fi}
  17826. \begin{figure}[tbp]
  17827. \begin{tcolorbox}[colback=white]
  17828. {\if\edition\racketEd
  17829. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17830. (define interp-Lany-class
  17831. (class interp-Llambda-class
  17832. (super-new)
  17833. (define/override (interp-op op)
  17834. (match op
  17835. ['boolean? (match-lambda
  17836. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17837. [else #f])]
  17838. ['integer? (match-lambda
  17839. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17840. [else #f])]
  17841. ['vector? (match-lambda
  17842. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17843. [else #f])]
  17844. ['procedure? (match-lambda
  17845. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17846. [else #f])]
  17847. ['eq? (match-lambda*
  17848. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17849. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17850. [ls (apply (super interp-op op) ls)])]
  17851. ['any-vector-ref (lambda (v i)
  17852. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17853. ['any-vector-set! (lambda (v i a)
  17854. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17855. ['any-vector-length (lambda (v)
  17856. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17857. [else (super interp-op op)]))
  17858. (define/override ((interp-exp env) e)
  17859. (define recur (interp-exp env))
  17860. (match e
  17861. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17862. [(Project e ty2) (apply-project (recur e) ty2)]
  17863. [else ((super interp-exp env) e)]))
  17864. ))
  17865. (define (interp-Lany p)
  17866. (send (new interp-Lany-class) interp-program p))
  17867. \end{lstlisting}
  17868. \fi}
  17869. {\if\edition\pythonEd\pythonColor
  17870. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17871. class InterpLany(InterpLlambda):
  17872. def interp_exp(self, e, env):
  17873. match e:
  17874. case Inject(value, typ):
  17875. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17876. case Project(value, typ):
  17877. match self.interp_exp(value, env):
  17878. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17879. return val
  17880. case _:
  17881. raise Exception('failed project to ' + self.type_to_tag(typ))
  17882. case Call(Name('any_tuple_load'), [tup, index]):
  17883. match self.interp_exp(tup, env):
  17884. case Tagged(v, tag):
  17885. return v[self.interp_exp(index, env)]
  17886. case _:
  17887. raise Exception('in any_tuple_load untagged value')
  17888. case Call(Name('any_len'), [value]):
  17889. match self.interp_exp(value, env):
  17890. case Tagged(value, tag):
  17891. return len(value)
  17892. case _:
  17893. raise Exception('interp any_len untagged value')
  17894. case Call(Name('arity'), [fun]):
  17895. return self.arity(self.interp_exp(fun, env))
  17896. case _:
  17897. return super().interp_exp(e, env)
  17898. \end{lstlisting}
  17899. \fi}
  17900. \end{tcolorbox}
  17901. \caption{Interpreter for \LangAny{}.}
  17902. \label{fig:interp-Lany}
  17903. \end{figure}
  17904. \begin{figure}[btp]
  17905. \begin{tcolorbox}[colback=white]
  17906. {\if\edition\racketEd
  17907. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17908. (define/public (apply-inject v tg) (Tagged v tg))
  17909. (define/public (apply-project v ty2)
  17910. (define tag2 (any-tag ty2))
  17911. (match v
  17912. [(Tagged v1 tag1)
  17913. (cond
  17914. [(eq? tag1 tag2)
  17915. (match ty2
  17916. [`(Vector ,ts ...)
  17917. (define l1 ((interp-op 'vector-length) v1))
  17918. (cond
  17919. [(eq? l1 (length ts)) v1]
  17920. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17921. l1 (length ts))])]
  17922. [`(,ts ... -> ,rt)
  17923. (match v1
  17924. [`(function ,xs ,body ,env)
  17925. (cond [(eq? (length xs) (length ts)) v1]
  17926. [else
  17927. (error 'apply-project "arity mismatch ~a != ~a"
  17928. (length xs) (length ts))])]
  17929. [else (error 'apply-project "expected function not ~a" v1)])]
  17930. [else v1])]
  17931. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17932. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17933. \end{lstlisting}
  17934. \fi}
  17935. {\if\edition\pythonEd\pythonColor
  17936. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17937. class InterpLany(InterpLlambda):
  17938. def type_to_tag(self, typ):
  17939. match typ:
  17940. case FunctionType(params, rt):
  17941. return 'function'
  17942. case TupleType(fields):
  17943. return 'tuple'
  17944. case IntType():
  17945. return 'int'
  17946. case BoolType():
  17947. return 'bool'
  17948. case _:
  17949. raise Exception('type_to_tag unexpected ' + repr(typ))
  17950. def arity(self, v):
  17951. match v:
  17952. case Function(name, params, body, env):
  17953. return len(params)
  17954. case _:
  17955. raise Exception('Lany arity unexpected ' + repr(v))
  17956. \end{lstlisting}
  17957. \fi}
  17958. \end{tcolorbox}
  17959. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17960. \label{fig:interp-Lany-aux}
  17961. \end{figure}
  17962. \clearpage
  17963. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17964. \label{sec:compile-r7}
  17965. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17966. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17967. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17968. is that given any subexpression $e$ in the \LangDyn{} program, the
  17969. pass will produce an expression $e'$ in \LangAny{} that has type
  17970. \ANYTY{}. For example, the first row in
  17971. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17972. \TRUE{}, which must be injected to produce an expression of type
  17973. \ANYTY{}.
  17974. %
  17975. The compilation of addition is shown in the second row of
  17976. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17977. representative of many primitive operations: the arguments have type
  17978. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17979. be performed.
  17980. The compilation of \key{lambda} (third row of
  17981. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17982. produce type annotations: we simply use \ANYTY{}.
  17983. %
  17984. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17985. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17986. this pass has to account for some differences in behavior between
  17987. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17988. permissive than \LangAny{} regarding what kind of values can be used
  17989. in various places. For example, the condition of an \key{if} does
  17990. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17991. of the same type (in that case the result is \code{\#f}).}
  17992. \begin{figure}[btp]
  17993. \centering
  17994. \begin{tcolorbox}[colback=white]
  17995. {\if\edition\racketEd
  17996. \begin{tabular}{lll}
  17997. \begin{minipage}{0.27\textwidth}
  17998. \begin{lstlisting}
  17999. #t
  18000. \end{lstlisting}
  18001. \end{minipage}
  18002. &
  18003. $\Rightarrow$
  18004. &
  18005. \begin{minipage}{0.65\textwidth}
  18006. \begin{lstlisting}
  18007. (inject #t Boolean)
  18008. \end{lstlisting}
  18009. \end{minipage}
  18010. \\[2ex]\hline
  18011. \begin{minipage}{0.27\textwidth}
  18012. \begin{lstlisting}
  18013. (+ |$e_1$| |$e_2$|)
  18014. \end{lstlisting}
  18015. \end{minipage}
  18016. &
  18017. $\Rightarrow$
  18018. &
  18019. \begin{minipage}{0.65\textwidth}
  18020. \begin{lstlisting}
  18021. (inject
  18022. (+ (project |$e'_1$| Integer)
  18023. (project |$e'_2$| Integer))
  18024. Integer)
  18025. \end{lstlisting}
  18026. \end{minipage}
  18027. \\[2ex]\hline
  18028. \begin{minipage}{0.27\textwidth}
  18029. \begin{lstlisting}
  18030. (lambda (|$x_1 \ldots$|) |$e$|)
  18031. \end{lstlisting}
  18032. \end{minipage}
  18033. &
  18034. $\Rightarrow$
  18035. &
  18036. \begin{minipage}{0.65\textwidth}
  18037. \begin{lstlisting}
  18038. (inject
  18039. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  18040. (Any|$\ldots$|Any -> Any))
  18041. \end{lstlisting}
  18042. \end{minipage}
  18043. \\[2ex]\hline
  18044. \begin{minipage}{0.27\textwidth}
  18045. \begin{lstlisting}
  18046. (|$e_0$| |$e_1 \ldots e_n$|)
  18047. \end{lstlisting}
  18048. \end{minipage}
  18049. &
  18050. $\Rightarrow$
  18051. &
  18052. \begin{minipage}{0.65\textwidth}
  18053. \begin{lstlisting}
  18054. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  18055. \end{lstlisting}
  18056. \end{minipage}
  18057. \\[2ex]\hline
  18058. \begin{minipage}{0.27\textwidth}
  18059. \begin{lstlisting}
  18060. (vector-ref |$e_1$| |$e_2$|)
  18061. \end{lstlisting}
  18062. \end{minipage}
  18063. &
  18064. $\Rightarrow$
  18065. &
  18066. \begin{minipage}{0.65\textwidth}
  18067. \begin{lstlisting}
  18068. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  18069. \end{lstlisting}
  18070. \end{minipage}
  18071. \\[2ex]\hline
  18072. \begin{minipage}{0.27\textwidth}
  18073. \begin{lstlisting}
  18074. (if |$e_1$| |$e_2$| |$e_3$|)
  18075. \end{lstlisting}
  18076. \end{minipage}
  18077. &
  18078. $\Rightarrow$
  18079. &
  18080. \begin{minipage}{0.65\textwidth}
  18081. \begin{lstlisting}
  18082. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18083. \end{lstlisting}
  18084. \end{minipage}
  18085. \\[2ex]\hline
  18086. \begin{minipage}{0.27\textwidth}
  18087. \begin{lstlisting}
  18088. (eq? |$e_1$| |$e_2$|)
  18089. \end{lstlisting}
  18090. \end{minipage}
  18091. &
  18092. $\Rightarrow$
  18093. &
  18094. \begin{minipage}{0.65\textwidth}
  18095. \begin{lstlisting}
  18096. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18097. \end{lstlisting}
  18098. \end{minipage}
  18099. \\[2ex]\hline
  18100. \begin{minipage}{0.27\textwidth}
  18101. \begin{lstlisting}
  18102. (not |$e_1$|)
  18103. \end{lstlisting}
  18104. \end{minipage}
  18105. &
  18106. $\Rightarrow$
  18107. &
  18108. \begin{minipage}{0.65\textwidth}
  18109. \begin{lstlisting}
  18110. (if (eq? |$e'_1$| (inject #f Boolean))
  18111. (inject #t Boolean) (inject #f Boolean))
  18112. \end{lstlisting}
  18113. \end{minipage}
  18114. \end{tabular}
  18115. \fi}
  18116. {\if\edition\pythonEd\pythonColor
  18117. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  18118. \begin{minipage}{0.23\textwidth}
  18119. \begin{lstlisting}
  18120. True
  18121. \end{lstlisting}
  18122. \end{minipage}
  18123. &
  18124. $\Rightarrow$
  18125. &
  18126. \begin{minipage}{0.7\textwidth}
  18127. \begin{lstlisting}
  18128. Inject(True, BoolType())
  18129. \end{lstlisting}
  18130. \end{minipage}
  18131. \\[2ex]\hline
  18132. \begin{minipage}{0.23\textwidth}
  18133. \begin{lstlisting}
  18134. |$e_1$| + |$e_2$|
  18135. \end{lstlisting}
  18136. \end{minipage}
  18137. &
  18138. $\Rightarrow$
  18139. &
  18140. \begin{minipage}{0.7\textwidth}
  18141. \begin{lstlisting}
  18142. Inject(Project(|$e'_1$|, IntType())
  18143. + Project(|$e'_2$|, IntType()),
  18144. IntType())
  18145. \end{lstlisting}
  18146. \end{minipage}
  18147. \\[2ex]\hline
  18148. \begin{minipage}{0.23\textwidth}
  18149. \begin{lstlisting}
  18150. lambda |$x_1 \ldots$|: |$e$|
  18151. \end{lstlisting}
  18152. \end{minipage}
  18153. &
  18154. $\Rightarrow$
  18155. &
  18156. \begin{minipage}{0.7\textwidth}
  18157. \begin{lstlisting}
  18158. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18159. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18160. \end{lstlisting}
  18161. \end{minipage}
  18162. \\[2ex]\hline
  18163. \begin{minipage}{0.23\textwidth}
  18164. \begin{lstlisting}
  18165. |$e_0$|(|$e_1 \ldots e_n$|)
  18166. \end{lstlisting}
  18167. \end{minipage}
  18168. &
  18169. $\Rightarrow$
  18170. &
  18171. \begin{minipage}{0.7\textwidth}
  18172. \begin{lstlisting}
  18173. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18174. AnyType())), |$e'_1, \ldots, e'_n$|)
  18175. \end{lstlisting}
  18176. \end{minipage}
  18177. \\[2ex]\hline
  18178. \begin{minipage}{0.23\textwidth}
  18179. \begin{lstlisting}
  18180. |$e_1$|[|$e_2$|]
  18181. \end{lstlisting}
  18182. \end{minipage}
  18183. &
  18184. $\Rightarrow$
  18185. &
  18186. \begin{minipage}{0.7\textwidth}
  18187. \begin{lstlisting}
  18188. Call(Name('any_tuple_load'),
  18189. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18190. \end{lstlisting}
  18191. \end{minipage}
  18192. %% \begin{minipage}{0.23\textwidth}
  18193. %% \begin{lstlisting}
  18194. %% |$e_2$| if |$e_1$| else |$e_3$|
  18195. %% \end{lstlisting}
  18196. %% \end{minipage}
  18197. %% &
  18198. %% $\Rightarrow$
  18199. %% &
  18200. %% \begin{minipage}{0.7\textwidth}
  18201. %% \begin{lstlisting}
  18202. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18203. %% \end{lstlisting}
  18204. %% \end{minipage}
  18205. %% \\[2ex]\hline
  18206. %% \begin{minipage}{0.23\textwidth}
  18207. %% \begin{lstlisting}
  18208. %% (eq? |$e_1$| |$e_2$|)
  18209. %% \end{lstlisting}
  18210. %% \end{minipage}
  18211. %% &
  18212. %% $\Rightarrow$
  18213. %% &
  18214. %% \begin{minipage}{0.7\textwidth}
  18215. %% \begin{lstlisting}
  18216. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18217. %% \end{lstlisting}
  18218. %% \end{minipage}
  18219. %% \\[2ex]\hline
  18220. %% \begin{minipage}{0.23\textwidth}
  18221. %% \begin{lstlisting}
  18222. %% (not |$e_1$|)
  18223. %% \end{lstlisting}
  18224. %% \end{minipage}
  18225. %% &
  18226. %% $\Rightarrow$
  18227. %% &
  18228. %% \begin{minipage}{0.7\textwidth}
  18229. %% \begin{lstlisting}
  18230. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18231. %% (inject #t Boolean) (inject #f Boolean))
  18232. %% \end{lstlisting}
  18233. %% \end{minipage}
  18234. %% \\[2ex]\hline
  18235. \\\hline
  18236. \end{tabular}
  18237. \fi}
  18238. \end{tcolorbox}
  18239. \caption{Cast insertion.}
  18240. \label{fig:compile-r7-Lany}
  18241. \end{figure}
  18242. \section{Reveal Casts}
  18243. \label{sec:reveal-casts-Lany}
  18244. % TODO: define R'_6
  18245. In the \code{reveal\_casts} pass, we recommend compiling
  18246. \code{Project} into a conditional expression that checks whether the
  18247. value's tag matches the target type; if it does, the value is
  18248. converted to a value of the target type by removing the tag; if it
  18249. does not, the program exits.
  18250. %
  18251. {\if\edition\racketEd
  18252. %
  18253. To perform these actions we need a new primitive operation,
  18254. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18255. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18256. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18257. underlying value from a tagged value. The \code{ValueOf} form
  18258. includes the type for the underlying value that is used by the type
  18259. checker.
  18260. %
  18261. \fi}
  18262. %
  18263. {\if\edition\pythonEd\pythonColor
  18264. %
  18265. To perform these actions we need two new AST classes: \code{TagOf} and
  18266. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18267. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18268. the underlying value from a tagged value. The \code{ValueOf}
  18269. operation includes the type for the underlying value that is used by
  18270. the type checker.
  18271. %
  18272. \fi}
  18273. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18274. \code{Project} can be translated as follows:
  18275. \begin{center}
  18276. \begin{minipage}{1.0\textwidth}
  18277. {\if\edition\racketEd
  18278. \begin{lstlisting}
  18279. (Project |$e$| |$\FType$|)
  18280. |$\Rightarrow$|
  18281. (Let |$\itm{tmp}$| |$e'$|
  18282. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18283. (Int |$\itm{tagof}(\FType)$|)))
  18284. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18285. (Exit)))
  18286. \end{lstlisting}
  18287. \fi}
  18288. {\if\edition\pythonEd\pythonColor
  18289. \begin{lstlisting}
  18290. Project(|$e$|, |$\FType$|)
  18291. |$\Rightarrow$|
  18292. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18293. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18294. [Constant(|$\itm{tagof}(\FType)$|)]),
  18295. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18296. Call(Name('exit'), [])))
  18297. \end{lstlisting}
  18298. \fi}
  18299. \end{minipage}
  18300. \end{center}
  18301. If the target type of the projection is a tuple or function type, then
  18302. there is a bit more work to do. For tuples, check that the length of
  18303. the tuple type matches the length of the tuple. For functions, check
  18304. that the number of parameters in the function type matches the
  18305. function's arity.
  18306. Regarding \code{Inject}, we recommend compiling it to a slightly
  18307. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18308. takes a tag instead of a type.
  18309. \begin{center}
  18310. \begin{minipage}{1.0\textwidth}
  18311. {\if\edition\racketEd
  18312. \begin{lstlisting}
  18313. (Inject |$e$| |$\FType$|)
  18314. |$\Rightarrow$|
  18315. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18316. \end{lstlisting}
  18317. \fi}
  18318. {\if\edition\pythonEd\pythonColor
  18319. \begin{lstlisting}
  18320. Inject(|$e$|, |$\FType$|)
  18321. |$\Rightarrow$|
  18322. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18323. \end{lstlisting}
  18324. \fi}
  18325. \end{minipage}
  18326. \end{center}
  18327. {\if\edition\pythonEd\pythonColor
  18328. %
  18329. The introduction of \code{make\_any} makes it difficult to use
  18330. bidirectional type checking because we no longer have an expected type
  18331. to use for type checking the expression $e'$. Thus, we run into
  18332. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18333. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18334. annotated lambda) that contains its return type and the types of its
  18335. parameters.
  18336. %
  18337. \fi}
  18338. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18339. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18340. translation of \code{Project}.}
  18341. {\if\edition\racketEd
  18342. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18343. combine the projection action with the vector operation. Also, the
  18344. read and write operations allow arbitrary expressions for the index, so
  18345. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18346. cannot guarantee that the index is within bounds. Thus, we insert code
  18347. to perform bounds checking at runtime. The translation for
  18348. \code{any-vector-ref} is as follows, and the other two operations are
  18349. translated in a similar way:
  18350. \begin{center}
  18351. \begin{minipage}{0.95\textwidth}
  18352. \begin{lstlisting}
  18353. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18354. |$\Rightarrow$|
  18355. (Let |$v$| |$e'_1$|
  18356. (Let |$i$| |$e'_2$|
  18357. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18358. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18359. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18360. (Exit))
  18361. (Exit))))
  18362. \end{lstlisting}
  18363. \end{minipage}
  18364. \end{center}
  18365. \fi}
  18366. %
  18367. {\if\edition\pythonEd\pythonColor
  18368. %
  18369. The \code{any\_tuple\_load} operation combines the projection action
  18370. with the load operation. Also, the load operation allows arbitrary
  18371. expressions for the index, so the type checker for \LangAny{}
  18372. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18373. within bounds. Thus, we insert code to perform bounds checking at
  18374. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18375. \begin{lstlisting}
  18376. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18377. |$\Rightarrow$|
  18378. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18379. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18380. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18381. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18382. Call(Name('exit'), [])),
  18383. Call(Name('exit'), [])))
  18384. \end{lstlisting}
  18385. \fi}
  18386. {\if\edition\pythonEd\pythonColor
  18387. \section{Assignment Conversion}
  18388. \label{sec:convert-assignments-Lany}
  18389. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18390. \code{AnnLambda} AST classes.
  18391. \section{Closure Conversion}
  18392. \label{sec:closure-conversion-Lany}
  18393. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18394. \code{AnnLambda} AST classes.
  18395. \fi}
  18396. \section{Remove Complex Operands}
  18397. \label{sec:rco-Lany}
  18398. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18399. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18400. %
  18401. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18402. complex expressions. Their subexpressions must be atomic.}
  18403. \section{Explicate Control and \LangCAny{}}
  18404. \label{sec:explicate-Lany}
  18405. The output of \code{explicate\_control} is the \LangCAny{} language,
  18406. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18407. %
  18408. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18409. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18410. note that the index argument of \code{vector-ref} and
  18411. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18412. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18413. %
  18414. \python{Update the auxiliary functions \code{explicate\_tail},
  18415. \code{explicate\_effect}, and \code{explicate\_pred} as
  18416. appropriate to handle the new expressions in \LangCAny{}. }
  18417. \newcommand{\CanyASTPython}{
  18418. \begin{array}{lcl}
  18419. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18420. &\MID& \key{TagOf}\LP \Atm \RP
  18421. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18422. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18423. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18424. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18425. \end{array}
  18426. }
  18427. \newcommand{\CanyASTRacket}{
  18428. \begin{array}{lcl}
  18429. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18430. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18431. &\MID& \VALUEOF{\Atm}{\FType} \\
  18432. \Tail &::= & \LP\key{Exit}\RP
  18433. \end{array}
  18434. }
  18435. \begin{figure}[tp]
  18436. \begin{tcolorbox}[colback=white]
  18437. \small
  18438. {\if\edition\racketEd
  18439. \[
  18440. \begin{array}{l}
  18441. \gray{\CvarASTRacket} \\ \hline
  18442. \gray{\CifASTRacket} \\ \hline
  18443. \gray{\CloopASTRacket} \\ \hline
  18444. \gray{\CtupASTRacket} \\ \hline
  18445. \gray{\CfunASTRacket} \\ \hline
  18446. \gray{\ClambdaASTRacket} \\ \hline
  18447. \CanyASTRacket \\
  18448. \begin{array}{lcl}
  18449. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18450. \end{array}
  18451. \end{array}
  18452. \]
  18453. \fi}
  18454. {\if\edition\pythonEd\pythonColor
  18455. \[
  18456. \begin{array}{l}
  18457. \gray{\CifASTPython} \\ \hline
  18458. \gray{\CtupASTPython} \\ \hline
  18459. \gray{\CfunASTPython} \\ \hline
  18460. \gray{\ClambdaASTPython} \\ \hline
  18461. \CanyASTPython \\
  18462. \begin{array}{lcl}
  18463. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18464. \end{array}
  18465. \end{array}
  18466. \]
  18467. \fi}
  18468. \end{tcolorbox}
  18469. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18470. \label{fig:c5-syntax}
  18471. \index{subject}{Cany@\LangCAny{} abstract syntax}
  18472. \end{figure}
  18473. \section{Select Instructions}
  18474. \label{sec:select-Lany}
  18475. \index{subject}{select instructions}
  18476. In the \code{select\_instructions} pass, we translate the primitive
  18477. operations on the \ANYTY{} type to x86 instructions that manipulate
  18478. the three tag bits of the tagged value. In the following descriptions,
  18479. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18480. of translating $e$ into an x86 argument:
  18481. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18482. We recommend compiling the
  18483. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18484. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18485. shifts the destination to the left by the number of bits specified by its
  18486. source argument (in this case three, the length of the tag), and it
  18487. preserves the sign of the integer. We use the \key{orq} instruction to
  18488. combine the tag and the value to form the tagged value.
  18489. {\if\edition\racketEd
  18490. \begin{lstlisting}
  18491. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18492. |$\Rightarrow$|
  18493. movq |$e'$|, |\itm{lhs'}|
  18494. salq $3, |\itm{lhs'}|
  18495. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18496. \end{lstlisting}
  18497. \fi}
  18498. %
  18499. {\if\edition\pythonEd\pythonColor
  18500. \begin{lstlisting}
  18501. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18502. |$\Rightarrow$|
  18503. movq |$e'$|, |\itm{lhs'}|
  18504. salq $3, |\itm{lhs'}|
  18505. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18506. \end{lstlisting}
  18507. \fi}
  18508. %
  18509. The instruction selection\index{subject}{instruction selection} for
  18510. tuples and procedures is different because there is no need to shift
  18511. them to the left. The rightmost 3 bits are already zeros, so we simply
  18512. combine the value and the tag using \key{orq}. \\
  18513. %
  18514. {\if\edition\racketEd
  18515. \begin{center}
  18516. \begin{minipage}{\textwidth}
  18517. \begin{lstlisting}
  18518. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18519. |$\Rightarrow$|
  18520. movq |$e'$|, |\itm{lhs'}|
  18521. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18522. \end{lstlisting}
  18523. \end{minipage}
  18524. \end{center}
  18525. \fi}
  18526. %
  18527. {\if\edition\pythonEd\pythonColor
  18528. \begin{lstlisting}
  18529. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18530. |$\Rightarrow$|
  18531. movq |$e'$|, |\itm{lhs'}|
  18532. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18533. \end{lstlisting}
  18534. \fi}
  18535. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18536. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18537. operation extracts the type tag from a value of type \ANYTY{}. The
  18538. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18539. bitwise-and of the value with $111$ ($7$ decimal).
  18540. %
  18541. {\if\edition\racketEd
  18542. \begin{lstlisting}
  18543. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18544. |$\Rightarrow$|
  18545. movq |$e'$|, |\itm{lhs'}|
  18546. andq $7, |\itm{lhs'}|
  18547. \end{lstlisting}
  18548. \fi}
  18549. %
  18550. {\if\edition\pythonEd\pythonColor
  18551. \begin{lstlisting}
  18552. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18553. |$\Rightarrow$|
  18554. movq |$e'$|, |\itm{lhs'}|
  18555. andq $7, |\itm{lhs'}|
  18556. \end{lstlisting}
  18557. \fi}
  18558. \paragraph{\code{ValueOf}}
  18559. The instructions for \key{ValueOf} also differ, depending on whether
  18560. the type $T$ is a pointer (tuple or function) or not (integer or
  18561. Boolean). The following shows the instruction
  18562. selection for integers and
  18563. Booleans, in which we produce an untagged value by shifting it to the
  18564. right by 3 bits:
  18565. %
  18566. {\if\edition\racketEd
  18567. \begin{lstlisting}
  18568. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18569. |$\Rightarrow$|
  18570. movq |$e'$|, |\itm{lhs'}|
  18571. sarq $3, |\itm{lhs'}|
  18572. \end{lstlisting}
  18573. \fi}
  18574. %
  18575. {\if\edition\pythonEd\pythonColor
  18576. \begin{lstlisting}
  18577. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18578. |$\Rightarrow$|
  18579. movq |$e'$|, |\itm{lhs'}|
  18580. sarq $3, |\itm{lhs'}|
  18581. \end{lstlisting}
  18582. \fi}
  18583. %
  18584. In the case for tuples and procedures, we zero out the rightmost 3
  18585. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18586. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18587. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18588. Finally, we apply \code{andq} with the tagged value to get the desired
  18589. result.
  18590. %
  18591. {\if\edition\racketEd
  18592. \begin{lstlisting}
  18593. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18594. |$\Rightarrow$|
  18595. movq $|$-8$|, |\itm{lhs'}|
  18596. andq |$e'$|, |\itm{lhs'}|
  18597. \end{lstlisting}
  18598. \fi}
  18599. %
  18600. {\if\edition\pythonEd\pythonColor
  18601. \begin{lstlisting}
  18602. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18603. |$\Rightarrow$|
  18604. movq $|$-8$|, |\itm{lhs'}|
  18605. andq |$e'$|, |\itm{lhs'}|
  18606. \end{lstlisting}
  18607. \fi}
  18608. %% \paragraph{Type Predicates} We leave it to the reader to
  18609. %% devise a sequence of instructions to implement the type predicates
  18610. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18611. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18612. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18613. operation combines the effect of \code{ValueOf} with accessing the
  18614. length of a tuple from the tag stored at the zero index of the tuple.
  18615. {\if\edition\racketEd
  18616. \begin{lstlisting}
  18617. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18618. |$\Longrightarrow$|
  18619. movq $|$-8$|, %r11
  18620. andq |$e_1'$|, %r11
  18621. movq 0(%r11), %r11
  18622. andq $126, %r11
  18623. sarq $1, %r11
  18624. movq %r11, |$\itm{lhs'}$|
  18625. \end{lstlisting}
  18626. \fi}
  18627. {\if\edition\pythonEd\pythonColor
  18628. \begin{lstlisting}
  18629. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18630. |$\Longrightarrow$|
  18631. movq $|$-8$|, %r11
  18632. andq |$e_1'$|, %r11
  18633. movq 0(%r11), %r11
  18634. andq $126, %r11
  18635. sarq $1, %r11
  18636. movq %r11, |$\itm{lhs'}$|
  18637. \end{lstlisting}
  18638. \fi}
  18639. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18640. This operation combines the effect of \code{ValueOf} with reading an
  18641. element of the tuple (see
  18642. section~\ref{sec:select-instructions-gc}). However, the index may be
  18643. an arbitrary atom, so instead of computing the offset at compile time,
  18644. we must generate instructions to compute the offset at runtime as
  18645. follows. Note the use of the new instruction \code{imulq}.
  18646. \begin{center}
  18647. \begin{minipage}{0.96\textwidth}
  18648. {\if\edition\racketEd
  18649. \begin{lstlisting}
  18650. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18651. |$\Longrightarrow$|
  18652. movq |$\neg 111$|, %r11
  18653. andq |$e_1'$|, %r11
  18654. movq |$e_2'$|, %rax
  18655. addq $1, %rax
  18656. imulq $8, %rax
  18657. addq %rax, %r11
  18658. movq 0(%r11) |$\itm{lhs'}$|
  18659. \end{lstlisting}
  18660. \fi}
  18661. %
  18662. {\if\edition\pythonEd\pythonColor
  18663. \begin{lstlisting}
  18664. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18665. |$\Longrightarrow$|
  18666. movq $|$-8$|, %r11
  18667. andq |$e_1'$|, %r11
  18668. movq |$e_2'$|, %rax
  18669. addq $1, %rax
  18670. imulq $8, %rax
  18671. addq %rax, %r11
  18672. movq 0(%r11) |$\itm{lhs'}$|
  18673. \end{lstlisting}
  18674. \fi}
  18675. \end{minipage}
  18676. \end{center}
  18677. % $ pacify font lock
  18678. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18679. %% The code generation for
  18680. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18681. %% analogous to the above translation for reading from a tuple.
  18682. \section{Register Allocation for \LangAny{} }
  18683. \label{sec:register-allocation-Lany}
  18684. \index{subject}{register allocation}
  18685. There is an interesting interaction between tagged values and garbage
  18686. collection that has an impact on register allocation. A variable of
  18687. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18688. that needs to be inspected and copied during garbage collection. Thus,
  18689. we need to treat variables of type \ANYTY{} in a similar way to
  18690. variables of tuple type for purposes of register allocation,
  18691. with particular attention to the following:
  18692. \begin{itemize}
  18693. \item If a variable of type \ANYTY{} is live during a function call,
  18694. then it must be spilled. This can be accomplished by changing
  18695. \code{build\_interference} to mark all variables of type \ANYTY{}
  18696. that are live after a \code{callq} to be interfering with all the
  18697. registers.
  18698. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18699. the root stack instead of the normal procedure call stack.
  18700. \end{itemize}
  18701. Another concern regarding the root stack is that the garbage collector
  18702. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18703. tagged value that points to a tuple, and (3) a tagged value that is
  18704. not a tuple. We enable this differentiation by choosing not to use the
  18705. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18706. reserved for identifying plain old pointers to tuples. That way, if
  18707. one of the first three bits is set, then we have a tagged value and
  18708. inspecting the tag can differentiate between tuples ($010$) and the
  18709. other kinds of values.
  18710. %% \begin{exercise}\normalfont
  18711. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18712. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18713. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18714. %% compiler on these new programs and all of your previously created test
  18715. %% programs.
  18716. %% \end{exercise}
  18717. \begin{exercise}\normalfont\normalsize
  18718. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18719. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18720. by removing type annotations. Add five more test programs that
  18721. specifically rely on the language being dynamically typed. That is,
  18722. they should not be legal programs in a statically typed language, but
  18723. nevertheless they should be valid \LangDyn{} programs that run to
  18724. completion without error.
  18725. \end{exercise}
  18726. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18727. for the compilation of \LangDyn{}.
  18728. \begin{figure}[bthp]
  18729. \begin{tcolorbox}[colback=white]
  18730. {\if\edition\racketEd
  18731. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18732. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18733. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18734. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18735. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18736. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18737. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18738. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18739. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18740. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18741. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18742. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18743. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18744. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18745. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18746. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18747. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18748. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18749. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18750. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18751. \path[->,bend left=15] (Lfun) edge [above] node
  18752. {\ttfamily\footnotesize shrink} (Lfun-2);
  18753. \path[->,bend left=15] (Lfun-2) edge [above] node
  18754. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18755. \path[->,bend left=15] (Lfun-3) edge [above] node
  18756. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18757. \path[->,bend left=15] (Lfun-4) edge [left] node
  18758. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18759. \path[->,bend left=15] (Lfun-5) edge [below] node
  18760. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18761. \path[->,bend left=15] (Lfun-6) edge [below] node
  18762. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18763. \path[->,bend right=15] (Lfun-7) edge [above] node
  18764. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18765. \path[->,bend right=15] (F1-2) edge [right] node
  18766. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18767. \path[->,bend right=15] (F1-3) edge [below] node
  18768. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18769. \path[->,bend right=15] (F1-4) edge [below] node
  18770. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18771. \path[->,bend left=15] (F1-5) edge [above] node
  18772. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18773. \path[->,bend left=10] (F1-6) edge [below] node
  18774. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18775. \path[->,bend left=15] (C3-2) edge [right] node
  18776. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18777. \path[->,bend right=15] (x86-2) edge [right] node
  18778. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18779. \path[->,bend right=15] (x86-2-1) edge [below] node
  18780. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18781. \path[->,bend right=15] (x86-2-2) edge [right] node
  18782. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18783. \path[->,bend left=15] (x86-3) edge [above] node
  18784. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18785. \path[->,bend left=15] (x86-4) edge [right] node
  18786. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18787. \end{tikzpicture}
  18788. \fi}
  18789. {\if\edition\pythonEd\pythonColor
  18790. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18791. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18792. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18793. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18794. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18795. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18796. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18797. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18798. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18799. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18800. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18801. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18802. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18803. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18804. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18805. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18806. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18807. \path[->,bend left=15] (Lfun) edge [above] node
  18808. {\ttfamily\footnotesize shrink} (Lfun-2);
  18809. \path[->,bend left=15] (Lfun-2) edge [above] node
  18810. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18811. \path[->,bend left=15] (Lfun-3) edge [above] node
  18812. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18813. \path[->,bend left=15] (Lfun-4) edge [left] node
  18814. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18815. \path[->,bend left=15] (Lfun-5) edge [below] node
  18816. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18817. \path[->,bend right=15] (Lfun-6) edge [above] node
  18818. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18819. \path[->,bend right=15] (Lfun-7) edge [above] node
  18820. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18821. \path[->,bend right=15] (F1-2) edge [right] node
  18822. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18823. \path[->,bend right=15] (F1-3) edge [below] node
  18824. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18825. \path[->,bend left=15] (F1-5) edge [above] node
  18826. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18827. \path[->,bend left=10] (F1-6) edge [below] node
  18828. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18829. \path[->,bend right=15] (C3-2) edge [right] node
  18830. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18831. \path[->,bend right=15] (x86-2) edge [below] node
  18832. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18833. \path[->,bend right=15] (x86-3) edge [below] node
  18834. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18835. \path[->,bend left=15] (x86-4) edge [above] node
  18836. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18837. \end{tikzpicture}
  18838. \fi}
  18839. \end{tcolorbox}
  18840. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18841. \label{fig:Ldyn-passes}
  18842. \end{figure}
  18843. % Further Reading
  18844. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18845. %% {\if\edition\pythonEd\pythonColor
  18846. %% \chapter{Objects}
  18847. %% \label{ch:Lobject}
  18848. %% \index{subject}{objects}
  18849. %% \index{subject}{classes}
  18850. %% \setcounter{footnote}{0}
  18851. %% \fi}
  18852. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18853. \chapter{Gradual Typing}
  18854. \label{ch:Lgrad}
  18855. \index{subject}{gradual typing}
  18856. \setcounter{footnote}{0}
  18857. This chapter studies the language \LangGrad{}, in which the programmer
  18858. can choose between static and dynamic type checking in different parts
  18859. of a program, thereby mixing the statically typed \LangLam{} language
  18860. with the dynamically typed \LangDyn{}. There are several approaches to
  18861. mixing static and dynamic typing, including multilanguage
  18862. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18863. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18864. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18865. programmer controls the amount of static versus dynamic checking by
  18866. adding or removing type annotations on parameters and
  18867. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18868. The definition of the concrete syntax of \LangGrad{} is shown in
  18869. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18870. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18871. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18872. annotations are optional, which is specified in the grammar using the
  18873. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18874. annotations are not optional, but we use the \CANYTY{} type when a type
  18875. annotation is absent.
  18876. %
  18877. Both the type checker and the interpreter for \LangGrad{} require some
  18878. interesting changes to enable gradual typing, which we discuss in the
  18879. next two sections.
  18880. \newcommand{\LgradGrammarRacket}{
  18881. \begin{array}{lcl}
  18882. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18883. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18884. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18885. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18886. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18887. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18888. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18889. \end{array}
  18890. }
  18891. \newcommand{\LgradASTRacket}{
  18892. \begin{array}{lcl}
  18893. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18894. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18895. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18896. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18897. \itm{op} &::=& \code{procedure-arity} \\
  18898. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18899. \end{array}
  18900. }
  18901. \newcommand{\LgradGrammarPython}{
  18902. \begin{array}{lcl}
  18903. \Type &::=& \key{Any}
  18904. \MID \key{int}
  18905. \MID \key{bool}
  18906. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18907. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18908. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18909. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18910. \MID \CARITY{\Exp} \\
  18911. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18912. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18913. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18914. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18915. \end{array}
  18916. }
  18917. \newcommand{\LgradASTPython}{
  18918. \begin{array}{lcl}
  18919. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18920. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18921. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18922. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18923. &\MID& \ARITY{\Exp} \\
  18924. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18925. \MID \RETURN{\Exp} \\
  18926. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18927. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18928. \end{array}
  18929. }
  18930. \begin{figure}[tbp]
  18931. \centering
  18932. \begin{tcolorbox}[colback=white]
  18933. \vspace{-5pt}
  18934. \small
  18935. {\if\edition\racketEd
  18936. \[
  18937. \begin{array}{l}
  18938. \gray{\LintGrammarRacket{}} \\ \hline
  18939. \gray{\LvarGrammarRacket{}} \\ \hline
  18940. \gray{\LifGrammarRacket{}} \\ \hline
  18941. \gray{\LwhileGrammarRacket} \\ \hline
  18942. \gray{\LtupGrammarRacket} \\ \hline
  18943. \LgradGrammarRacket \\
  18944. \begin{array}{lcl}
  18945. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18946. \end{array}
  18947. \end{array}
  18948. \]
  18949. \fi}
  18950. {\if\edition\pythonEd\pythonColor
  18951. \[
  18952. \begin{array}{l}
  18953. \gray{\LintGrammarPython{}} \\ \hline
  18954. \gray{\LvarGrammarPython{}} \\ \hline
  18955. \gray{\LifGrammarPython{}} \\ \hline
  18956. \gray{\LwhileGrammarPython} \\ \hline
  18957. \gray{\LtupGrammarPython} \\ \hline
  18958. \LgradGrammarPython \\
  18959. \begin{array}{lcl}
  18960. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18961. \end{array}
  18962. \end{array}
  18963. \]
  18964. \fi}
  18965. \end{tcolorbox}
  18966. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18967. \label{fig:Lgrad-concrete-syntax}
  18968. \index{subject}{L?@\LangGrad{} concrete syntax}
  18969. \end{figure}
  18970. \begin{figure}[tbp]
  18971. \centering
  18972. \begin{tcolorbox}[colback=white]
  18973. \small
  18974. {\if\edition\racketEd
  18975. \[
  18976. \begin{array}{l}
  18977. \gray{\LintOpAST} \\ \hline
  18978. \gray{\LvarASTRacket{}} \\ \hline
  18979. \gray{\LifASTRacket{}} \\ \hline
  18980. \gray{\LwhileASTRacket{}} \\ \hline
  18981. \gray{\LtupASTRacket{}} \\ \hline
  18982. \LgradASTRacket \\
  18983. \begin{array}{lcl}
  18984. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18985. \end{array}
  18986. \end{array}
  18987. \]
  18988. \fi}
  18989. {\if\edition\pythonEd\pythonColor
  18990. \[
  18991. \begin{array}{l}
  18992. \gray{\LintASTPython{}} \\ \hline
  18993. \gray{\LvarASTPython{}} \\ \hline
  18994. \gray{\LifASTPython{}} \\ \hline
  18995. \gray{\LwhileASTPython} \\ \hline
  18996. \gray{\LtupASTPython} \\ \hline
  18997. \LgradASTPython \\
  18998. \begin{array}{lcl}
  18999. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19000. \end{array}
  19001. \end{array}
  19002. \]
  19003. \fi}
  19004. \end{tcolorbox}
  19005. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  19006. \label{fig:Lgrad-syntax}
  19007. \index{subject}{L?@\LangGrad{} abstract syntax}
  19008. \end{figure}
  19009. % TODO: more road map -Jeremy
  19010. %\clearpage
  19011. \section{Type Checking \LangGrad{}}
  19012. \label{sec:gradual-type-check}
  19013. We begin by discussing the type checking of a partially typed variant
  19014. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  19015. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  19016. statically typed, so there is nothing special happening there with
  19017. respect to type checking. On the other hand, the \code{inc} function
  19018. does not have type annotations, so the type checker assigns the type
  19019. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  19020. \code{+} operator inside \code{inc}. It expects both arguments to have
  19021. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  19022. a gradually typed language, such differences are allowed so long as
  19023. the types are \emph{consistent}; that is, they are equal except in
  19024. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  19025. is consistent with every other type. Figure~\ref{fig:consistent}
  19026. shows the definition of the
  19027. \racket{\code{consistent?}}\python{\code{consistent}} method.
  19028. %
  19029. So the type checker allows the \code{+} operator to be applied
  19030. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  19031. %
  19032. Next consider the call to the \code{map} function shown in
  19033. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  19034. tuple. The \code{inc} function has type
  19035. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  19036. but parameter \code{f} of \code{map} has type
  19037. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19038. The type checker for \LangGrad{} accepts this call because the two types are
  19039. consistent.
  19040. \begin{figure}[hbtp]
  19041. % gradual_test_9.rkt
  19042. \begin{tcolorbox}[colback=white]
  19043. {\if\edition\racketEd
  19044. \begin{lstlisting}
  19045. (define (map [f : (Integer -> Integer)]
  19046. [v : (Vector Integer Integer)])
  19047. : (Vector Integer Integer)
  19048. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19049. (define (inc x) (+ x 1))
  19050. (vector-ref (map inc (vector 0 41)) 1)
  19051. \end{lstlisting}
  19052. \fi}
  19053. {\if\edition\pythonEd\pythonColor
  19054. \begin{lstlisting}
  19055. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19056. return f(v[0]), f(v[1])
  19057. def inc(x):
  19058. return x + 1
  19059. t = map(inc, (0, 41))
  19060. print(t[1])
  19061. \end{lstlisting}
  19062. \fi}
  19063. \end{tcolorbox}
  19064. \caption{A partially typed version of the \code{map} example.}
  19065. \label{fig:gradual-map}
  19066. \end{figure}
  19067. \begin{figure}[tbp]
  19068. \begin{tcolorbox}[colback=white]
  19069. {\if\edition\racketEd
  19070. \begin{lstlisting}
  19071. (define/public (consistent? t1 t2)
  19072. (match* (t1 t2)
  19073. [('Integer 'Integer) #t]
  19074. [('Boolean 'Boolean) #t]
  19075. [('Void 'Void) #t]
  19076. [('Any t2) #t]
  19077. [(t1 'Any) #t]
  19078. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19079. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  19080. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19081. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  19082. (consistent? rt1 rt2))]
  19083. [(other wise) #f]))
  19084. \end{lstlisting}
  19085. \fi}
  19086. {\if\edition\pythonEd\pythonColor
  19087. \begin{lstlisting}
  19088. def consistent(self, t1, t2):
  19089. match (t1, t2):
  19090. case (AnyType(), _):
  19091. return True
  19092. case (_, AnyType()):
  19093. return True
  19094. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19095. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  19096. case (TupleType(ts1), TupleType(ts2)):
  19097. return all(map(self.consistent, ts1, ts2))
  19098. case (_, _):
  19099. return t1 == t2
  19100. \end{lstlisting}
  19101. \fi}
  19102. \vspace{-5pt}
  19103. \end{tcolorbox}
  19104. \caption{The consistency method on types.}
  19105. \label{fig:consistent}
  19106. \end{figure}
  19107. It is also helpful to consider how gradual typing handles programs with an
  19108. error, such as applying \code{map} to a function that sometimes
  19109. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  19110. type checker for \LangGrad{} accepts this program because the type of
  19111. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  19112. \code{map}; that is,
  19113. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  19114. is consistent with
  19115. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19116. One might say that a gradual type checker is optimistic in that it
  19117. accepts programs that might execute without a runtime type error.
  19118. %
  19119. The definition of the type checker for \LangGrad{} is shown in
  19120. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  19121. and \ref{fig:type-check-Lgradual-3}.
  19122. %% \begin{figure}[tp]
  19123. %% \centering
  19124. %% \fbox{
  19125. %% \begin{minipage}{0.96\textwidth}
  19126. %% \small
  19127. %% \[
  19128. %% \begin{array}{lcl}
  19129. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  19130. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  19131. %% \end{array}
  19132. %% \]
  19133. %% \end{minipage}
  19134. %% }
  19135. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  19136. %% \label{fig:Lgrad-prime-syntax}
  19137. %% \end{figure}
  19138. \begin{figure}[tbp]
  19139. \begin{tcolorbox}[colback=white]
  19140. {\if\edition\racketEd
  19141. \begin{lstlisting}
  19142. (define (map [f : (Integer -> Integer)]
  19143. [v : (Vector Integer Integer)])
  19144. : (Vector Integer Integer)
  19145. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19146. (define (inc x) (+ x 1))
  19147. (define (true) #t)
  19148. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19149. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19150. \end{lstlisting}
  19151. \fi}
  19152. {\if\edition\pythonEd\pythonColor
  19153. \begin{lstlisting}
  19154. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19155. return f(v[0]), f(v[1])
  19156. def inc(x):
  19157. return x + 1
  19158. def true():
  19159. return True
  19160. def maybe_inc(x):
  19161. return inc(x) if input_int() == 0 else true()
  19162. t = map(maybe_inc, (0, 41))
  19163. print(t[1])
  19164. \end{lstlisting}
  19165. \fi}
  19166. \vspace{-5pt}
  19167. \end{tcolorbox}
  19168. \caption{A variant of the \code{map} example with an error.}
  19169. \label{fig:map-maybe_inc}
  19170. \end{figure}
  19171. Running this program with input \code{1} triggers an
  19172. error when the \code{maybe\_inc} function returns
  19173. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19174. performs checking at runtime to ensure the integrity of the static
  19175. types, such as the
  19176. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19177. annotation on
  19178. parameter \code{f} of \code{map}.
  19179. Here we give a preview of how the runtime checking is accomplished;
  19180. the following sections provide the details.
  19181. The runtime checking is carried out by a new \code{Cast} AST node that
  19182. is generated in a new pass named \code{cast\_insert}. The output of
  19183. \code{cast\_insert} is a program in the \LangCast{} language, which
  19184. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19185. %
  19186. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19187. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19188. inserted every time the type checker encounters two types that are
  19189. consistent but not equal. In the \code{inc} function, \code{x} is
  19190. cast to \INTTY{} and the result of the \code{+} is cast to
  19191. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19192. is cast from
  19193. \racket{\code{(Any -> Any)}}
  19194. \python{\code{Callable[[Any], Any]}}
  19195. to
  19196. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19197. %
  19198. In the next section we see how to interpret the \code{Cast} node.
  19199. \begin{figure}[btp]
  19200. \begin{tcolorbox}[colback=white]
  19201. {\if\edition\racketEd
  19202. \begin{lstlisting}
  19203. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19204. : (Vector Integer Integer)
  19205. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19206. (define (inc [x : Any]) : Any
  19207. (cast (+ (cast x Any Integer) 1) Integer Any))
  19208. (define (true) : Any (cast #t Boolean Any))
  19209. (define (maybe_inc [x : Any]) : Any
  19210. (if (eq? 0 (read)) (inc x) (true)))
  19211. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19212. (vector 0 41)) 0)
  19213. \end{lstlisting}
  19214. \fi}
  19215. {\if\edition\pythonEd\pythonColor
  19216. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19217. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19218. return f(v[0]), f(v[1])
  19219. def inc(x : Any) -> Any:
  19220. return Cast(Cast(x, Any, int) + 1, int, Any)
  19221. def true() -> Any:
  19222. return Cast(True, bool, Any)
  19223. def maybe_inc(x : Any) -> Any:
  19224. return inc(x) if input_int() == 0 else true()
  19225. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19226. (0, 41))
  19227. print(t[1])
  19228. \end{lstlisting}
  19229. \fi}
  19230. \vspace{-5pt}
  19231. \end{tcolorbox}
  19232. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19233. and \code{maybe\_inc} example.}
  19234. \label{fig:map-cast}
  19235. \end{figure}
  19236. {\if\edition\pythonEd\pythonColor
  19237. \begin{figure}[tbp]
  19238. \begin{tcolorbox}[colback=white]
  19239. \begin{lstlisting}
  19240. class TypeCheckLgrad(TypeCheckLlambda):
  19241. def type_check_exp(self, e, env) -> Type:
  19242. match e:
  19243. case Name(id):
  19244. return env[id]
  19245. case Constant(value) if isinstance(value, bool):
  19246. return BoolType()
  19247. case Constant(value) if isinstance(value, int):
  19248. return IntType()
  19249. case Call(Name('input_int'), []):
  19250. return IntType()
  19251. case BinOp(left, op, right):
  19252. left_type = self.type_check_exp(left, env)
  19253. self.check_consistent(left_type, IntType(), left)
  19254. right_type = self.type_check_exp(right, env)
  19255. self.check_consistent(right_type, IntType(), right)
  19256. return IntType()
  19257. case IfExp(test, body, orelse):
  19258. test_t = self.type_check_exp(test, env)
  19259. self.check_consistent(test_t, BoolType(), test)
  19260. body_t = self.type_check_exp(body, env)
  19261. orelse_t = self.type_check_exp(orelse, env)
  19262. self.check_consistent(body_t, orelse_t, e)
  19263. return self.join_types(body_t, orelse_t)
  19264. case Call(func, args):
  19265. func_t = self.type_check_exp(func, env)
  19266. args_t = [self.type_check_exp(arg, env) for arg in args]
  19267. match func_t:
  19268. case FunctionType(params_t, return_t) \
  19269. if len(params_t) == len(args_t):
  19270. for (arg_t, param_t) in zip(args_t, params_t):
  19271. self.check_consistent(param_t, arg_t, e)
  19272. return return_t
  19273. case AnyType():
  19274. return AnyType()
  19275. case _:
  19276. raise Exception('type_check_exp: in call, unexpected '
  19277. + repr(func_t))
  19278. ...
  19279. case _:
  19280. raise Exception('type_check_exp: unexpected ' + repr(e))
  19281. \end{lstlisting}
  19282. \end{tcolorbox}
  19283. \caption{Type checking expressions in the \LangGrad{} language.}
  19284. \label{fig:type-check-Lgradual-1}
  19285. \end{figure}
  19286. \begin{figure}[tbp]
  19287. \begin{tcolorbox}[colback=white]
  19288. \begin{lstlisting}
  19289. def check_exp(self, e, expected_ty, env):
  19290. match e:
  19291. case Lambda(params, body):
  19292. match expected_ty:
  19293. case FunctionType(params_t, return_t):
  19294. new_env = env.copy().update(zip(params, params_t))
  19295. e.has_type = expected_ty
  19296. body_ty = self.type_check_exp(body, new_env)
  19297. self.check_consistent(body_ty, return_t)
  19298. case AnyType():
  19299. new_env = env.copy().update((p, AnyType()) for p in params)
  19300. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19301. body_ty = self.type_check_exp(body, new_env)
  19302. case _:
  19303. raise Exception('lambda is not of type ' + str(expected_ty))
  19304. case _:
  19305. e_ty = self.type_check_exp(e, env)
  19306. self.check_consistent(e_ty, expected_ty, e)
  19307. \end{lstlisting}
  19308. \end{tcolorbox}
  19309. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19310. \label{fig:type-check-Lgradual-2}
  19311. \end{figure}
  19312. \begin{figure}[tbp]
  19313. \begin{tcolorbox}[colback=white]
  19314. \begin{lstlisting}
  19315. def type_check_stmt(self, s, env, return_type):
  19316. match s:
  19317. case Assign([Name(id)], value):
  19318. value_ty = self.type_check_exp(value, env)
  19319. if id in env:
  19320. self.check_consistent(env[id], value_ty, value)
  19321. else:
  19322. env[id] = value_ty
  19323. ...
  19324. case _:
  19325. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19326. def type_check_stmts(self, ss, env, return_type):
  19327. for s in ss:
  19328. self.type_check_stmt(s, env, return_type)
  19329. \end{lstlisting}
  19330. \end{tcolorbox}
  19331. \caption{Type checking statements in the \LangGrad{} language.}
  19332. \label{fig:type-check-Lgradual-3}
  19333. \end{figure}
  19334. \clearpage
  19335. \begin{figure}[tbp]
  19336. \begin{tcolorbox}[colback=white]
  19337. \begin{lstlisting}
  19338. def join_types(self, t1, t2):
  19339. match (t1, t2):
  19340. case (AnyType(), _):
  19341. return t2
  19342. case (_, AnyType()):
  19343. return t1
  19344. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19345. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19346. self.join_types(rt1,rt2))
  19347. case (TupleType(ts1), TupleType(ts2)):
  19348. return TupleType(list(map(self.join_types, ts1, ts2)))
  19349. case (_, _):
  19350. return t1
  19351. def check_consistent(self, t1, t2, e):
  19352. if not self.consistent(t1, t2):
  19353. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19354. + repr(t2) + ' in ' + repr(e))
  19355. \end{lstlisting}
  19356. \end{tcolorbox}
  19357. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19358. \label{fig:type-check-Lgradual-aux}
  19359. \end{figure}
  19360. \fi}
  19361. {\if\edition\racketEd
  19362. \begin{figure}[tbp]
  19363. \begin{tcolorbox}[colback=white]
  19364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19365. (define/override (type-check-exp env)
  19366. (lambda (e)
  19367. (define recur (type-check-exp env))
  19368. (match e
  19369. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19370. (define-values (new-es ts)
  19371. (for/lists (exprs types) ([e es])
  19372. (recur e)))
  19373. (define t-ret (type-check-op op ts e))
  19374. (values (Prim op new-es) t-ret)]
  19375. [(Prim 'eq? (list e1 e2))
  19376. (define-values (e1^ t1) (recur e1))
  19377. (define-values (e2^ t2) (recur e2))
  19378. (check-consistent? t1 t2 e)
  19379. (define T (meet t1 t2))
  19380. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19381. [(Prim 'and (list e1 e2))
  19382. (recur (If e1 e2 (Bool #f)))]
  19383. [(Prim 'or (list e1 e2))
  19384. (define tmp (gensym 'tmp))
  19385. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19386. [(If e1 e2 e3)
  19387. (define-values (e1^ T1) (recur e1))
  19388. (define-values (e2^ T2) (recur e2))
  19389. (define-values (e3^ T3) (recur e3))
  19390. (check-consistent? T1 'Boolean e)
  19391. (check-consistent? T2 T3 e)
  19392. (define Tif (meet T2 T3))
  19393. (values (If e1^ e2^ e3^) Tif)]
  19394. [(SetBang x e1)
  19395. (define-values (e1^ T1) (recur e1))
  19396. (define varT (dict-ref env x))
  19397. (check-consistent? T1 varT e)
  19398. (values (SetBang x e1^) 'Void)]
  19399. [(WhileLoop e1 e2)
  19400. (define-values (e1^ T1) (recur e1))
  19401. (check-consistent? T1 'Boolean e)
  19402. (define-values (e2^ T2) ((type-check-exp env) e2))
  19403. (values (WhileLoop e1^ e2^) 'Void)]
  19404. [(Prim 'vector-length (list e1))
  19405. (define-values (e1^ t) (recur e1))
  19406. (match t
  19407. [`(Vector ,ts ...)
  19408. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19409. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19410. \end{lstlisting}
  19411. \end{tcolorbox}
  19412. \caption{Type checker for the \LangGrad{} language, part 1.}
  19413. \label{fig:type-check-Lgradual-1}
  19414. \end{figure}
  19415. \begin{figure}[tbp]
  19416. \begin{tcolorbox}[colback=white]
  19417. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19418. [(Prim 'vector-ref (list e1 e2))
  19419. (define-values (e1^ t1) (recur e1))
  19420. (define-values (e2^ t2) (recur e2))
  19421. (check-consistent? t2 'Integer e)
  19422. (match t1
  19423. [`(Vector ,ts ...)
  19424. (match e2^
  19425. [(Int i)
  19426. (unless (and (0 . <= . i) (i . < . (length ts)))
  19427. (error 'type-check "invalid index ~a in ~a" i e))
  19428. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19429. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19430. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19431. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19432. [(Prim 'vector-set! (list e1 e2 e3) )
  19433. (define-values (e1^ t1) (recur e1))
  19434. (define-values (e2^ t2) (recur e2))
  19435. (define-values (e3^ t3) (recur e3))
  19436. (check-consistent? t2 'Integer e)
  19437. (match t1
  19438. [`(Vector ,ts ...)
  19439. (match e2^
  19440. [(Int i)
  19441. (unless (and (0 . <= . i) (i . < . (length ts)))
  19442. (error 'type-check "invalid index ~a in ~a" i e))
  19443. (check-consistent? (list-ref ts i) t3 e)
  19444. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19445. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19446. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19447. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19448. [(Apply e1 e2s)
  19449. (define-values (e1^ T1) (recur e1))
  19450. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19451. (match T1
  19452. [`(,T1ps ... -> ,T1rt)
  19453. (for ([T2 T2s] [Tp T1ps])
  19454. (check-consistent? T2 Tp e))
  19455. (values (Apply e1^ e2s^) T1rt)]
  19456. [`Any (values (Apply e1^ e2s^) 'Any)]
  19457. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19458. [(Lambda params Tr e1)
  19459. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19460. (match p
  19461. [`[,x : ,T] (values x T)]
  19462. [(? symbol? x) (values x 'Any)])))
  19463. (define-values (e1^ T1)
  19464. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19465. (check-consistent? Tr T1 e)
  19466. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19467. `(,@Ts -> ,Tr))]
  19468. [else ((super type-check-exp env) e)]
  19469. )))
  19470. \end{lstlisting}
  19471. \end{tcolorbox}
  19472. \caption{Type checker for the \LangGrad{} language, part 2.}
  19473. \label{fig:type-check-Lgradual-2}
  19474. \end{figure}
  19475. \begin{figure}[tbp]
  19476. \begin{tcolorbox}[colback=white]
  19477. \begin{lstlisting}
  19478. (define/override (type-check-def env)
  19479. (lambda (e)
  19480. (match e
  19481. [(Def f params rt info body)
  19482. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19483. (match p
  19484. [`[,x : ,T] (values x T)]
  19485. [(? symbol? x) (values x 'Any)])))
  19486. (define new-env (append (map cons xs ps) env))
  19487. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19488. (check-consistent? ty^ rt e)
  19489. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19490. [else (error 'type-check "ill-formed function definition ~a" e)]
  19491. )))
  19492. (define/override (type-check-program e)
  19493. (match e
  19494. [(Program info body)
  19495. (define-values (body^ ty) ((type-check-exp '()) body))
  19496. (check-consistent? ty 'Integer e)
  19497. (ProgramDefsExp info '() body^)]
  19498. [(ProgramDefsExp info ds body)
  19499. (define new-env (for/list ([d ds])
  19500. (cons (Def-name d) (fun-def-type d))))
  19501. (define ds^ (for/list ([d ds])
  19502. ((type-check-def new-env) d)))
  19503. (define-values (body^ ty) ((type-check-exp new-env) body))
  19504. (check-consistent? ty 'Integer e)
  19505. (ProgramDefsExp info ds^ body^)]
  19506. [else (super type-check-program e)]))
  19507. \end{lstlisting}
  19508. \end{tcolorbox}
  19509. \caption{Type checker for the \LangGrad{} language, part 3.}
  19510. \label{fig:type-check-Lgradual-3}
  19511. \end{figure}
  19512. \begin{figure}[tbp]
  19513. \begin{tcolorbox}[colback=white]
  19514. \begin{lstlisting}
  19515. (define/public (join t1 t2)
  19516. (match* (t1 t2)
  19517. [('Integer 'Integer) 'Integer]
  19518. [('Boolean 'Boolean) 'Boolean]
  19519. [('Void 'Void) 'Void]
  19520. [('Any t2) t2]
  19521. [(t1 'Any) t1]
  19522. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19523. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19524. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19525. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19526. -> ,(join rt1 rt2))]))
  19527. (define/public (meet t1 t2)
  19528. (match* (t1 t2)
  19529. [('Integer 'Integer) 'Integer]
  19530. [('Boolean 'Boolean) 'Boolean]
  19531. [('Void 'Void) 'Void]
  19532. [('Any t2) 'Any]
  19533. [(t1 'Any) 'Any]
  19534. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19535. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19536. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19537. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19538. -> ,(meet rt1 rt2))]))
  19539. (define/public (check-consistent? t1 t2 e)
  19540. (unless (consistent? t1 t2)
  19541. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19542. (define explicit-prim-ops
  19543. (set-union
  19544. (type-predicates)
  19545. (set 'procedure-arity 'eq? 'not 'and 'or
  19546. 'vector 'vector-length 'vector-ref 'vector-set!
  19547. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19548. (define/override (fun-def-type d)
  19549. (match d
  19550. [(Def f params rt info body)
  19551. (define ps
  19552. (for/list ([p params])
  19553. (match p
  19554. [`[,x : ,T] T]
  19555. [(? symbol?) 'Any]
  19556. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19557. `(,@ps -> ,rt)]
  19558. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19559. \end{lstlisting}
  19560. \end{tcolorbox}
  19561. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19562. \label{fig:type-check-Lgradual-aux}
  19563. \end{figure}
  19564. \fi}
  19565. \section{Interpreting \LangCast{} }
  19566. \label{sec:interp-casts}
  19567. The runtime behavior of casts involving simple types such as
  19568. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19569. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19570. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19571. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19572. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19573. operator, by checking the value's tag and either retrieving
  19574. the underlying integer or signaling an error if the tag is not the
  19575. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19576. %
  19577. Things get more interesting with casts involving
  19578. \racket{function and tuple types}\python{function, tuple, and array types}.
  19579. Consider the cast of the function \code{maybe\_inc} from
  19580. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19581. to
  19582. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19583. shown in figure~\ref{fig:map-maybe_inc}.
  19584. When the \code{maybe\_inc} function flows through
  19585. this cast at runtime, we don't know whether it will return
  19586. an integer, because that depends on the input from the user.
  19587. The \LangCast{} interpreter therefore delays the checking
  19588. of the cast until the function is applied. To do so it
  19589. wraps \code{maybe\_inc} in a new function that casts its parameter
  19590. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19591. casts the return value from \CANYTY{} to \INTTY{}.
  19592. {\if\edition\pythonEd\pythonColor
  19593. %
  19594. There are further complications regarding casts on mutable data,
  19595. such as the \code{list} type introduced in
  19596. the challenge assignment of section~\ref{sec:arrays}.
  19597. %
  19598. \fi}
  19599. %
  19600. Consider the example presented in figure~\ref{fig:map-bang} that
  19601. defines a partially typed version of \code{map} whose parameter
  19602. \code{v} has type
  19603. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19604. and that updates \code{v} in place
  19605. instead of returning a new tuple. We name this function
  19606. \code{map\_inplace}. We apply \code{map\_inplace} to
  19607. \racket{a tuple}\python{an array} of integers, so the type checker
  19608. inserts a cast from
  19609. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19610. to
  19611. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19612. A naive way for the \LangCast{} interpreter to cast between
  19613. \racket{tuple}\python{array} types would be to build a new
  19614. \racket{tuple}\python{array} whose elements are the result
  19615. of casting each of the original elements to the target
  19616. type. However, this approach is not valid for mutable data structures.
  19617. In the example of figure~\ref{fig:map-bang},
  19618. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19619. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19620. the original one.
  19621. Instead the interpreter needs to create a new kind of value, a
  19622. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19623. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19624. and then applies a
  19625. cast to the resulting value. On a write, the proxy casts the argument
  19626. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19627. \racket{
  19628. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19629. \code{0} from \INTTY{} to \CANYTY{}.
  19630. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19631. from \CANYTY{} to \INTTY{}.
  19632. }
  19633. \python{
  19634. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19635. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19636. For the subscript on the left of the assignment,
  19637. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19638. }
  19639. Finally we consider casts between the \CANYTY{} type and higher-order types
  19640. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19641. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19642. have a type annotation, so it is given type \CANYTY{}. In the call to
  19643. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19644. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19645. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19646. \code{Inject}, but that doesn't work because
  19647. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19648. a flat type. Instead, we must first cast to
  19649. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19650. and then inject to \CANYTY{}.
  19651. \begin{figure}[tbp]
  19652. \begin{tcolorbox}[colback=white]
  19653. % gradual_test_11.rkt
  19654. {\if\edition\racketEd
  19655. \begin{lstlisting}
  19656. (define (map_inplace [f : (Any -> Any)]
  19657. [v : (Vector Any Any)]) : Void
  19658. (begin
  19659. (vector-set! v 0 (f (vector-ref v 0)))
  19660. (vector-set! v 1 (f (vector-ref v 1)))))
  19661. (define (inc x) (+ x 1))
  19662. (let ([v (vector 0 41)])
  19663. (begin (map_inplace inc v) (vector-ref v 1)))
  19664. \end{lstlisting}
  19665. \fi}
  19666. {\if\edition\pythonEd\pythonColor
  19667. \begin{lstlisting}
  19668. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19669. i = 0
  19670. while i != len(v):
  19671. v[i] = f(v[i])
  19672. i = i + 1
  19673. def inc(x : int) -> int:
  19674. return x + 1
  19675. v = [0, 41]
  19676. map_inplace(inc, v)
  19677. print(v[1])
  19678. \end{lstlisting}
  19679. \fi}
  19680. \end{tcolorbox}
  19681. \caption{An example involving casts on arrays.}
  19682. \label{fig:map-bang}
  19683. \end{figure}
  19684. \begin{figure}[btp]
  19685. \begin{tcolorbox}[colback=white]
  19686. {\if\edition\racketEd
  19687. \begin{lstlisting}
  19688. (define (map_inplace [f : (Any -> Any)] v) : Void
  19689. (begin
  19690. (vector-set! v 0 (f (vector-ref v 0)))
  19691. (vector-set! v 1 (f (vector-ref v 1)))))
  19692. (define (inc x) (+ x 1))
  19693. (let ([v (vector 0 41)])
  19694. (begin (map_inplace inc v) (vector-ref v 1)))
  19695. \end{lstlisting}
  19696. \fi}
  19697. {\if\edition\pythonEd\pythonColor
  19698. \begin{lstlisting}
  19699. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19700. i = 0
  19701. while i != len(v):
  19702. v[i] = f(v[i])
  19703. i = i + 1
  19704. def inc(x):
  19705. return x + 1
  19706. v = [0, 41]
  19707. map_inplace(inc, v)
  19708. print(v[1])
  19709. \end{lstlisting}
  19710. \fi}
  19711. \end{tcolorbox}
  19712. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19713. \label{fig:map-any}
  19714. \end{figure}
  19715. \begin{figure}[tbp]
  19716. \begin{tcolorbox}[colback=white]
  19717. {\if\edition\racketEd
  19718. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19719. (define/public (apply_cast v s t)
  19720. (match* (s t)
  19721. [(t1 t2) #:when (equal? t1 t2) v]
  19722. [('Any t2)
  19723. (match t2
  19724. [`(,ts ... -> ,rt)
  19725. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19726. (define v^ (apply-project v any->any))
  19727. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19728. [`(Vector ,ts ...)
  19729. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19730. (define v^ (apply-project v vec-any))
  19731. (apply_cast v^ vec-any `(Vector ,@ts))]
  19732. [else (apply-project v t2)])]
  19733. [(t1 'Any)
  19734. (match t1
  19735. [`(,ts ... -> ,rt)
  19736. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19737. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19738. (apply-inject v^ (any-tag any->any))]
  19739. [`(Vector ,ts ...)
  19740. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19741. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19742. (apply-inject v^ (any-tag vec-any))]
  19743. [else (apply-inject v (any-tag t1))])]
  19744. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19745. (define x (gensym 'x))
  19746. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19747. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19748. (define cast-writes
  19749. (for/list ([t1 ts1] [t2 ts2])
  19750. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19751. `(vector-proxy ,(vector v (apply vector cast-reads)
  19752. (apply vector cast-writes)))]
  19753. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19754. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19755. `(function ,xs ,(Cast
  19756. (Apply (Value v)
  19757. (for/list ([x xs][t1 ts1][t2 ts2])
  19758. (Cast (Var x) t2 t1)))
  19759. rt1 rt2) ())]
  19760. ))
  19761. \end{lstlisting}
  19762. \fi}
  19763. {\if\edition\pythonEd\pythonColor
  19764. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19765. def apply_cast(self, value, src, tgt):
  19766. match (src, tgt):
  19767. case (AnyType(), FunctionType(ps2, rt2)):
  19768. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19769. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19770. case (AnyType(), TupleType(ts2)):
  19771. anytup = TupleType([AnyType() for t1 in ts2])
  19772. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19773. case (AnyType(), ListType(t2)):
  19774. anylist = ListType([AnyType() for t1 in ts2])
  19775. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19776. case (AnyType(), AnyType()):
  19777. return value
  19778. case (AnyType(), _):
  19779. return self.apply_project(value, tgt)
  19780. case (FunctionType(ps1,rt1), AnyType()):
  19781. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19782. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19783. case (TupleType(ts1), AnyType()):
  19784. anytup = TupleType([AnyType() for t1 in ts1])
  19785. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19786. case (ListType(t1), AnyType()):
  19787. anylist = ListType(AnyType())
  19788. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19789. case (_, AnyType()):
  19790. return self.apply_inject(value, src)
  19791. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19792. params = [generate_name('x') for p in ps2]
  19793. args = [Cast(Name(x), t2, t1)
  19794. for (x,t1,t2) in zip(params, ps1, ps2)]
  19795. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19796. return Function('cast', params, [Return(body)], {})
  19797. case (TupleType(ts1), TupleType(ts2)):
  19798. x = generate_name('x')
  19799. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19800. for (t1,t2) in zip(ts1,ts2)]
  19801. return ProxiedTuple(value, reads)
  19802. case (ListType(t1), ListType(t2)):
  19803. x = generate_name('x')
  19804. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19805. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19806. return ProxiedList(value, read, write)
  19807. case (t1, t2) if t1 == t2:
  19808. return value
  19809. case (t1, t2):
  19810. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19811. def apply_inject(self, value, src):
  19812. return Tagged(value, self.type_to_tag(src))
  19813. def apply_project(self, value, tgt):
  19814. match value:
  19815. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19816. return val
  19817. case _:
  19818. raise Exception('apply_project, unexpected ' + repr(value))
  19819. \end{lstlisting}
  19820. \fi}
  19821. \end{tcolorbox}
  19822. \caption{The \code{apply\_cast} auxiliary method.}
  19823. \label{fig:apply_cast}
  19824. \end{figure}
  19825. The \LangCast{} interpreter uses an auxiliary function named
  19826. \code{apply\_cast} to cast a value from a source type to a target type,
  19827. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19828. the kinds of casts that we've discussed in this section.
  19829. %
  19830. The definition of the interpreter for \LangCast{} is shown in
  19831. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19832. dispatching to \code{apply\_cast}.
  19833. \racket{To handle the addition of tuple
  19834. proxies, we update the tuple primitives in \code{interp-op} using the
  19835. functions given in figure~\ref{fig:guarded-tuple}.}
  19836. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19837. \begin{figure}[tbp]
  19838. \begin{tcolorbox}[colback=white]
  19839. {\if\edition\racketEd
  19840. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19841. (define interp-Lcast-class
  19842. (class interp-Llambda-class
  19843. (super-new)
  19844. (inherit apply-fun apply-inject apply-project)
  19845. (define/override (interp-op op)
  19846. (match op
  19847. ['vector-length guarded-vector-length]
  19848. ['vector-ref guarded-vector-ref]
  19849. ['vector-set! guarded-vector-set!]
  19850. ['any-vector-ref (lambda (v i)
  19851. (match v [`(tagged ,v^ ,tg)
  19852. (guarded-vector-ref v^ i)]))]
  19853. ['any-vector-set! (lambda (v i a)
  19854. (match v [`(tagged ,v^ ,tg)
  19855. (guarded-vector-set! v^ i a)]))]
  19856. ['any-vector-length (lambda (v)
  19857. (match v [`(tagged ,v^ ,tg)
  19858. (guarded-vector-length v^)]))]
  19859. [else (super interp-op op)]
  19860. ))
  19861. (define/override ((interp-exp env) e)
  19862. (define (recur e) ((interp-exp env) e))
  19863. (match e
  19864. [(Value v) v]
  19865. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19866. [else ((super interp-exp env) e)]))
  19867. ))
  19868. (define (interp-Lcast p)
  19869. (send (new interp-Lcast-class) interp-program p))
  19870. \end{lstlisting}
  19871. \fi}
  19872. {\if\edition\pythonEd\pythonColor
  19873. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19874. class InterpLcast(InterpLany):
  19875. def interp_exp(self, e, env):
  19876. match e:
  19877. case Cast(value, src, tgt):
  19878. v = self.interp_exp(value, env)
  19879. return self.apply_cast(v, src, tgt)
  19880. case ValueExp(value):
  19881. return value
  19882. ...
  19883. case _:
  19884. return super().interp_exp(e, env)
  19885. \end{lstlisting}
  19886. \fi}
  19887. \end{tcolorbox}
  19888. \caption{The interpreter for \LangCast{}.}
  19889. \label{fig:interp-Lcast}
  19890. \end{figure}
  19891. {\if\edition\racketEd
  19892. \begin{figure}[tbp]
  19893. \begin{tcolorbox}[colback=white]
  19894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19895. (define (guarded-vector-ref vec i)
  19896. (match vec
  19897. [`(vector-proxy ,proxy)
  19898. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19899. (define rd (vector-ref (vector-ref proxy 1) i))
  19900. (apply-fun rd (list val) 'guarded-vector-ref)]
  19901. [else (vector-ref vec i)]))
  19902. (define (guarded-vector-set! vec i arg)
  19903. (match vec
  19904. [`(vector-proxy ,proxy)
  19905. (define wr (vector-ref (vector-ref proxy 2) i))
  19906. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19907. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19908. [else (vector-set! vec i arg)]))
  19909. (define (guarded-vector-length vec)
  19910. (match vec
  19911. [`(vector-proxy ,proxy)
  19912. (guarded-vector-length (vector-ref proxy 0))]
  19913. [else (vector-length vec)]))
  19914. \end{lstlisting}
  19915. %% {\if\edition\pythonEd\pythonColor
  19916. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19917. %% UNDER CONSTRUCTION
  19918. %% \end{lstlisting}
  19919. %% \fi}
  19920. \end{tcolorbox}
  19921. \caption{The \code{guarded-vector} auxiliary functions.}
  19922. \label{fig:guarded-tuple}
  19923. \end{figure}
  19924. \fi}
  19925. {\if\edition\pythonEd\pythonColor
  19926. \section{Overload Resolution }
  19927. \label{sec:gradual-resolution}
  19928. Recall that when we added support for arrays in
  19929. section~\ref{sec:arrays}, the syntax for the array operations were the
  19930. same as for tuple operations (for example, accessing an element and
  19931. getting the length). So we performed overload resolution, with a pass
  19932. named \code{resolve}, to separate the array and tuple operations. In
  19933. particular, we introduced the primitives \code{array\_load},
  19934. \code{array\_store}, and \code{array\_len}.
  19935. For gradual typing, we further overload these operators to work on
  19936. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19937. updated with new cases for the \CANYTY{} type, translating the element
  19938. access and length operations to the primitives \code{any\_load},
  19939. \code{any\_store}, and \code{any\_len}.
  19940. \fi}
  19941. \section{Cast Insertion }
  19942. \label{sec:gradual-insert-casts}
  19943. In our discussion of type checking of \LangGrad{}, we mentioned how
  19944. the runtime aspect of type checking is carried out by the \code{Cast}
  19945. AST node, which is added to the program by a new pass named
  19946. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19947. language. We now discuss the details of this pass.
  19948. The \code{cast\_insert} pass is closely related to the type checker
  19949. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19950. In particular, the type checker allows implicit casts between
  19951. consistent types. The job of the \code{cast\_insert} pass is to make
  19952. those casts explicit. It does so by inserting
  19953. \code{Cast} nodes into the AST.
  19954. %
  19955. For the most part, the implicit casts occur in places where the type
  19956. checker checks two types for consistency. Consider the case for
  19957. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19958. checker requires that the type of the left operand is consistent with
  19959. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19960. \code{Cast} around the left operand, converting from its type to
  19961. \INTTY{}. The story is similar for the right operand. It is not always
  19962. necessary to insert a cast, for example, if the left operand already has type
  19963. \INTTY{} then there is no need for a \code{Cast}.
  19964. Some of the implicit casts are not as straightforward. One such case
  19965. arises with the
  19966. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19967. see that the type checker requires that the two branches have
  19968. consistent types and that type of the conditional expression is the
  19969. meet of the branches' types. In the target language \LangCast{}, both
  19970. branches will need to have the same type, and that type
  19971. will be the type of the conditional expression. Thus, each branch requires
  19972. a \code{Cast} to convert from its type to the meet of the branches' types.
  19973. The case for the function call exhibits another interesting situation. If
  19974. the function expression is of type \CANYTY{}, then it needs to be cast
  19975. to a function type so that it can be used in a function call in
  19976. \LangCast{}. Which function type should it be cast to? The parameter
  19977. and return types are unknown, so we can simply use \CANYTY{} for all
  19978. of them. Furthermore, in \LangCast{} the argument types will need to
  19979. exactly match the parameter types, so we must cast all the arguments
  19980. to type \CANYTY{} (if they are not already of that type).
  19981. {\if\edition\racketEd
  19982. %
  19983. Likewise, the cases for the tuple operators \code{vector-length},
  19984. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19985. where the tuple expression is of type \CANYTY{}. Instead of
  19986. handling these situations with casts, we recommend translating
  19987. the special-purpose variants of the tuple operators that handle
  19988. tuples of type \CANYTY{}: \code{any-vector-length},
  19989. \code{any-vector-ref}, and \code{any-vector-set!}.
  19990. %
  19991. \fi}
  19992. \section{Lower Casts }
  19993. \label{sec:lower_casts}
  19994. The next step in the journey toward x86 is the \code{lower\_casts}
  19995. pass that translates the casts in \LangCast{} to the lower-level
  19996. \code{Inject} and \code{Project} operators and new operators for
  19997. proxies, extending the \LangLam{} language to \LangProxy{}.
  19998. The \LangProxy{} language can also be described as an extension of
  19999. \LangAny{}, with the addition of proxies. We recommend creating an
  20000. auxiliary function named \code{lower\_cast} that takes an expression
  20001. (in \LangCast{}), a source type, and a target type and translates it
  20002. to an expression in \LangProxy{}.
  20003. The \code{lower\_cast} function can follow a code structure similar to
  20004. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  20005. the interpreter for \LangCast{}, because it must handle the same cases
  20006. as \code{apply\_cast} and it needs to mimic the behavior of
  20007. \code{apply\_cast}. The most interesting cases concern
  20008. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  20009. {\if\edition\racketEd
  20010. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  20011. type to another tuple type is accomplished by creating a proxy that
  20012. intercepts the operations on the underlying tuple. Here we make the
  20013. creation of the proxy explicit with the \code{vector-proxy} AST
  20014. node. It takes three arguments: the first is an expression for the
  20015. tuple, the second is a tuple of functions for casting an element that is
  20016. being read from the tuple, and the third is a tuple of functions for
  20017. casting an element that is being written to the array. You can create
  20018. the functions for reading and writing using lambda expressions. Also,
  20019. as we show in the next section, we need to differentiate these tuples
  20020. of functions from the user-created ones, so we recommend using a new
  20021. AST node named \code{raw-vector} instead of \code{vector}.
  20022. %
  20023. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20024. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20025. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  20026. \fi}
  20027. {\if\edition\pythonEd\pythonColor
  20028. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  20029. type to another array type is accomplished by creating a proxy that
  20030. intercepts the operations on the underlying array. Here we make the
  20031. creation of the proxy explicit with the \code{ListProxy} AST node. It
  20032. takes fives arguments: the first is an expression for the array, the
  20033. second is a function for casting an element that is being read from
  20034. the array, the third is a function for casting an element that is
  20035. being written to the array, the fourth is the type of the underlying
  20036. array, and the fifth is the type of the proxied array. You can create
  20037. the functions for reading and writing using lambda expressions.
  20038. A cast between two tuple types can be handled in a similar manner. We
  20039. create a proxy with the \code{TupleProxy} AST node. Tuples are
  20040. immutable, so there is no need for a function to cast the value during
  20041. a write. Because there is a separate element type for each slot in
  20042. the tuple, we need more than one function for casting during a read:
  20043. we need a tuple of functions.
  20044. %
  20045. Also, as we show in the next section, we need to differentiate these
  20046. tuples from the user-created ones, so we recommend using a new AST
  20047. node named \code{RawTuple} instead of \code{Tuple} to create the
  20048. tuples of functions.
  20049. %
  20050. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20051. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20052. that involves casting an array of integers to an array of \CANYTY{}.
  20053. \fi}
  20054. \begin{figure}[tbp]
  20055. \begin{tcolorbox}[colback=white]
  20056. {\if\edition\racketEd
  20057. \begin{lstlisting}
  20058. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  20059. (begin
  20060. (vector-set! v 0 (f (vector-ref v 0)))
  20061. (vector-set! v 1 (f (vector-ref v 1)))))
  20062. (define (inc [x : Any]) : Any
  20063. (inject (+ (project x Integer) 1) Integer))
  20064. (let ([v (vector 0 41)])
  20065. (begin
  20066. (map_inplace inc (vector-proxy v
  20067. (raw-vector (lambda: ([x9 : Integer]) : Any
  20068. (inject x9 Integer))
  20069. (lambda: ([x9 : Integer]) : Any
  20070. (inject x9 Integer)))
  20071. (raw-vector (lambda: ([x9 : Any]) : Integer
  20072. (project x9 Integer))
  20073. (lambda: ([x9 : Any]) : Integer
  20074. (project x9 Integer)))))
  20075. (vector-ref v 1)))
  20076. \end{lstlisting}
  20077. \fi}
  20078. {\if\edition\pythonEd\pythonColor
  20079. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20080. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  20081. i = 0
  20082. while i != array_len(v):
  20083. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  20084. i = (i + 1)
  20085. def inc(x : int) -> int:
  20086. return (x + 1)
  20087. def main() -> int:
  20088. v = [0, 41]
  20089. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  20090. print(array_load(v, 1))
  20091. return 0
  20092. \end{lstlisting}
  20093. \fi}
  20094. \end{tcolorbox}
  20095. \caption{Output of \code{lower\_casts} on the example shown in
  20096. figure~\ref{fig:map-bang}.}
  20097. \label{fig:map-bang-lower-cast}
  20098. \end{figure}
  20099. A cast from one function type to another function type is accomplished
  20100. by generating a \code{lambda} whose parameter and return types match
  20101. the target function type. The body of the \code{lambda} should cast
  20102. the parameters from the target type to the source type. (Yes,
  20103. backward! Functions are contravariant\index{subject}{contravariant}
  20104. in the parameters.) Afterward, call the underlying function and then
  20105. cast the result from the source return type to the target return type.
  20106. Figure~\ref{fig:map-lower-cast} shows the output of the
  20107. \code{lower\_casts} pass on the \code{map} example given in
  20108. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  20109. call to \code{map} is wrapped in a \code{lambda}.
  20110. \begin{figure}[tbp]
  20111. \begin{tcolorbox}[colback=white]
  20112. {\if\edition\racketEd
  20113. \begin{lstlisting}
  20114. (define (map [f : (Integer -> Integer)]
  20115. [v : (Vector Integer Integer)])
  20116. : (Vector Integer Integer)
  20117. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20118. (define (inc [x : Any]) : Any
  20119. (inject (+ (project x Integer) 1) Integer))
  20120. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  20121. (project (inc (inject x9 Integer)) Integer))
  20122. (vector 0 41)) 1)
  20123. \end{lstlisting}
  20124. \fi}
  20125. {\if\edition\pythonEd\pythonColor
  20126. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20127. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  20128. return (f(v[0]), f(v[1]),)
  20129. def inc(x : any) -> any:
  20130. return inject((project(x, int) + 1), int)
  20131. def main() -> int:
  20132. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  20133. print(t[1])
  20134. return 0
  20135. \end{lstlisting}
  20136. \fi}
  20137. \end{tcolorbox}
  20138. \caption{Output of \code{lower\_casts} on the example shown in
  20139. figure~\ref{fig:gradual-map}.}
  20140. \label{fig:map-lower-cast}
  20141. \end{figure}
  20142. %\pagebreak
  20143. \section{Differentiate Proxies }
  20144. \label{sec:differentiate-proxies}
  20145. So far, the responsibility of differentiating tuples and tuple proxies
  20146. has been the job of the interpreter.
  20147. %
  20148. \racket{For example, the interpreter for \LangCast{} implements
  20149. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20150. figure~\ref{fig:guarded-tuple}.}
  20151. %
  20152. In the \code{differentiate\_proxies} pass we shift this responsibility
  20153. to the generated code.
  20154. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20155. we used the type \TUPLETYPENAME{} for both
  20156. real tuples and tuple proxies.
  20157. \python{Similarly, we use the type \code{list} for both arrays and
  20158. array proxies.}
  20159. In \LangPVec{} we return the
  20160. \TUPLETYPENAME{} type to its original
  20161. meaning, as the type of just tuples, and we introduce a new type,
  20162. \PTUPLETYNAME{}, whose values
  20163. can be either real tuples or tuple
  20164. proxies.
  20165. %
  20166. {\if\edition\pythonEd\pythonColor
  20167. Likewise, we return the
  20168. \ARRAYTYPENAME{} type to its original
  20169. meaning, as the type of arrays, and we introduce a new type,
  20170. \PARRAYTYNAME{}, whose values
  20171. can be either arrays or array proxies.
  20172. These new types come with a suite of new primitive operations.
  20173. \fi}
  20174. {\if\edition\racketEd
  20175. A tuple proxy is represented by a tuple containing three things: (1) the
  20176. underlying tuple, (2) a tuple of functions for casting elements that
  20177. are read from the tuple, and (3) a tuple of functions for casting
  20178. values to be written to the tuple. So, we define the following
  20179. abbreviation for the type of a tuple proxy:
  20180. \[
  20181. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20182. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20183. \]
  20184. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20185. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20186. %
  20187. Next we describe each of the new primitive operations.
  20188. \begin{description}
  20189. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20190. (\key{PVector} $T \ldots$)]\ \\
  20191. %
  20192. This operation brands a vector as a value of the \code{PVector} type.
  20193. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20194. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20195. %
  20196. This operation brands a vector proxy as value of the \code{PVector} type.
  20197. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20198. \BOOLTY{}] \ \\
  20199. %
  20200. This returns true if the value is a tuple proxy and false if it is a
  20201. real tuple.
  20202. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20203. (\key{Vector} $T \ldots$)]\ \\
  20204. %
  20205. Assuming that the input is a tuple, this operation returns the
  20206. tuple.
  20207. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20208. $\to$ \INTTY{}]\ \\
  20209. %
  20210. Given a tuple proxy, this operation returns the length of the tuple.
  20211. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20212. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20213. %
  20214. Given a tuple proxy, this operation returns the $i$th element of the
  20215. tuple.
  20216. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20217. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20218. Given a tuple proxy, this operation writes a value to the $i$th element
  20219. of the tuple.
  20220. \end{description}
  20221. \fi}
  20222. {\if\edition\pythonEd\pythonColor
  20223. %
  20224. A tuple proxy is represented by a tuple containing (1) the underlying
  20225. tuple and (2) a tuple of functions for casting elements that are read
  20226. from the tuple. The \LangPVec{} language includes the following AST
  20227. classes and primitive functions.
  20228. \begin{description}
  20229. \item[\code{InjectTuple}] \ \\
  20230. %
  20231. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20232. \item[\code{InjectTupleProxy}]\ \\
  20233. %
  20234. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20235. \item[\code{is\_tuple\_proxy}]\ \\
  20236. %
  20237. This primitive returns true if the value is a tuple proxy and false
  20238. if it is a tuple.
  20239. \item[\code{project\_tuple}]\ \\
  20240. %
  20241. Converts a tuple that is branded as \PTUPLETYNAME{}
  20242. back to a tuple.
  20243. \item[\code{proxy\_tuple\_len}]\ \\
  20244. %
  20245. Given a tuple proxy, returns the length of the underlying tuple.
  20246. \item[\code{proxy\_tuple\_load}]\ \\
  20247. %
  20248. Given a tuple proxy, returns the $i$th element of the underlying
  20249. tuple.
  20250. \end{description}
  20251. An array proxy is represented by a tuple containing (1) the underlying
  20252. array, (2) a function for casting elements that are read from the
  20253. array, and (3) a function for casting elements that are written to the
  20254. array. The \LangPVec{} language includes the following AST classes
  20255. and primitive functions.
  20256. \begin{description}
  20257. \item[\code{InjectList}]\ \\
  20258. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20259. \item[\code{InjectListProxy}]\ \\
  20260. %
  20261. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20262. \item[\code{is\_array\_proxy}]\ \\
  20263. %
  20264. Returns true if the value is an array proxy and false if it is an
  20265. array.
  20266. \item[\code{project\_array}]\ \\
  20267. %
  20268. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20269. array.
  20270. \item[\code{proxy\_array\_len}]\ \\
  20271. %
  20272. Given an array proxy, returns the length of the underlying array.
  20273. \item[\code{proxy\_array\_load}]\ \\
  20274. %
  20275. Given an array proxy, returns the $i$th element of the underlying
  20276. array.
  20277. \item[\code{proxy\_array\_store}]\ \\
  20278. %
  20279. Given an array proxy, writes a value to the $i$th element of the
  20280. underlying array.
  20281. \end{description}
  20282. \fi}
  20283. Now we discuss the translation that differentiates tuples and arrays
  20284. from proxies. First, every type annotation in the program is
  20285. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20286. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20287. places. For example, we wrap every tuple creation with an
  20288. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20289. %
  20290. {\if\edition\racketEd
  20291. \begin{minipage}{0.96\textwidth}
  20292. \begin{lstlisting}
  20293. (vector |$e_1 \ldots e_n$|)
  20294. |$\Rightarrow$|
  20295. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20296. \end{lstlisting}
  20297. \end{minipage}
  20298. \fi}
  20299. {\if\edition\pythonEd\pythonColor
  20300. \begin{lstlisting}
  20301. Tuple(|$e_1, \ldots, e_n$|)
  20302. |$\Rightarrow$|
  20303. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20304. \end{lstlisting}
  20305. \fi}
  20306. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20307. AST node that we introduced in the previous
  20308. section does not get injected.
  20309. {\if\edition\racketEd
  20310. \begin{lstlisting}
  20311. (raw-vector |$e_1 \ldots e_n$|)
  20312. |$\Rightarrow$|
  20313. (vector |$e'_1 \ldots e'_n$|)
  20314. \end{lstlisting}
  20315. \fi}
  20316. {\if\edition\pythonEd\pythonColor
  20317. \begin{lstlisting}
  20318. RawTuple(|$e_1, \ldots, e_n$|)
  20319. |$\Rightarrow$|
  20320. Tuple(|$e'_1, \ldots, e'_n$|)
  20321. \end{lstlisting}
  20322. \fi}
  20323. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20324. translates as follows:
  20325. %
  20326. {\if\edition\racketEd
  20327. \begin{lstlisting}
  20328. (vector-proxy |$e_1~e_2~e_3$|)
  20329. |$\Rightarrow$|
  20330. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20331. \end{lstlisting}
  20332. \fi}
  20333. {\if\edition\pythonEd\pythonColor
  20334. \begin{lstlisting}
  20335. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20336. |$\Rightarrow$|
  20337. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20338. \end{lstlisting}
  20339. \fi}
  20340. We translate the element access operations into conditional
  20341. expressions that check whether the value is a proxy and then dispatch
  20342. to either the appropriate proxy tuple operation or the regular tuple
  20343. operation.
  20344. {\if\edition\racketEd
  20345. \begin{lstlisting}
  20346. (vector-ref |$e_1$| |$i$|)
  20347. |$\Rightarrow$|
  20348. (let ([|$v~e_1$|])
  20349. (if (proxy? |$v$|)
  20350. (proxy-vector-ref |$v$| |$i$|)
  20351. (vector-ref (project-vector |$v$|) |$i$|)
  20352. \end{lstlisting}
  20353. \fi}
  20354. %
  20355. Note that in the branch for a tuple, we must apply
  20356. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20357. from the tuple.
  20358. The translation of array operations is similar to the ones for tuples.
  20359. \section{Reveal Casts }
  20360. \label{sec:reveal-casts-gradual}
  20361. {\if\edition\racketEd
  20362. Recall that the \code{reveal\_casts} pass
  20363. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20364. \code{Inject} and \code{Project} into lower-level operations.
  20365. %
  20366. In particular, \code{Project} turns into a conditional expression that
  20367. inspects the tag and retrieves the underlying value. Here we need to
  20368. augment the translation of \code{Project} to handle the situation in which
  20369. the target type is \code{PVector}. Instead of using
  20370. \code{vector-length} we need to use \code{proxy-vector-length}.
  20371. \begin{lstlisting}
  20372. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20373. |$\Rightarrow$|
  20374. (let |$\itm{tmp}$| |$e'$|
  20375. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20376. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20377. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20378. (exit)))
  20379. \end{lstlisting}
  20380. \fi}
  20381. %
  20382. {\if\edition\pythonEd\pythonColor
  20383. Recall that the $\itm{tagof}$ function determines the bits used to
  20384. identify values of different types, and it is used in the \code{reveal\_casts}
  20385. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20386. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20387. decimal), just like the tuple and array types.
  20388. \fi}
  20389. %
  20390. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20391. \pagebreak
  20392. \section{Closure Conversion }
  20393. \label{sec:closure-conversion-gradual}
  20394. The auxiliary function that translates type annotations needs to be
  20395. updated to handle the \PTUPLETYNAME{}
  20396. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20397. %
  20398. Otherwise, the only other changes are adding cases that copy the new
  20399. AST nodes.
  20400. \section{Select Instructions }
  20401. \label{sec:select-instructions-gradual}
  20402. \index{subject}{select instructions}
  20403. Recall that the \code{select\_instructions} pass is responsible for
  20404. lowering the primitive operations into x86 instructions. So, we need
  20405. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20406. to x86. To do so, the first question we need to answer is how to
  20407. differentiate between tuple and tuple proxies\python{, and likewise for
  20408. arrays and array proxies}. We need just one bit to accomplish this;
  20409. we use the bit in position $63$ of the 64-bit tag at the front of
  20410. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20411. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20412. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20413. it that way.
  20414. {\if\edition\racketEd
  20415. \begin{lstlisting}
  20416. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20417. |$\Rightarrow$|
  20418. movq |$e'_1$|, |$\itm{lhs'}$|
  20419. \end{lstlisting}
  20420. \fi}
  20421. {\if\edition\pythonEd\pythonColor
  20422. \begin{lstlisting}
  20423. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20424. |$\Rightarrow$|
  20425. movq |$e'_1$|, |$\itm{lhs'}$|
  20426. \end{lstlisting}
  20427. \fi}
  20428. \python{The translation for \code{InjectList} is also a move instruction.}
  20429. \noindent On the other hand,
  20430. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20431. $63$ to $1$.
  20432. %
  20433. {\if\edition\racketEd
  20434. \begin{lstlisting}
  20435. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20436. |$\Rightarrow$|
  20437. movq |$e'_1$|, %r11
  20438. movq |$(1 << 63)$|, %rax
  20439. orq 0(%r11), %rax
  20440. movq %rax, 0(%r11)
  20441. movq %r11, |$\itm{lhs'}$|
  20442. \end{lstlisting}
  20443. \fi}
  20444. {\if\edition\pythonEd\pythonColor
  20445. \begin{lstlisting}
  20446. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20447. |$\Rightarrow$|
  20448. movq |$e'_1$|, %r11
  20449. movq |$(1 << 63)$|, %rax
  20450. orq 0(%r11), %rax
  20451. movq %rax, 0(%r11)
  20452. movq %r11, |$\itm{lhs'}$|
  20453. \end{lstlisting}
  20454. \fi}
  20455. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20456. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20457. The \racket{\code{proxy?} operation consumes}%
  20458. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20459. consume}
  20460. the information so carefully stashed away by the injections. It
  20461. isolates bit $63$ to tell whether the value is a proxy.
  20462. %
  20463. {\if\edition\racketEd
  20464. \begin{lstlisting}
  20465. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20466. |$\Rightarrow$|
  20467. movq |$e_1'$|, %r11
  20468. movq 0(%r11), %rax
  20469. sarq $63, %rax
  20470. andq $1, %rax
  20471. movq %rax, |$\itm{lhs'}$|
  20472. \end{lstlisting}
  20473. \fi}%
  20474. %
  20475. {\if\edition\pythonEd\pythonColor
  20476. \begin{lstlisting}
  20477. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20478. |$\Rightarrow$|
  20479. movq |$e_1'$|, %r11
  20480. movq 0(%r11), %rax
  20481. sarq $63, %rax
  20482. andq $1, %rax
  20483. movq %rax, |$\itm{lhs'}$|
  20484. \end{lstlisting}
  20485. \fi}%
  20486. %
  20487. The \racket{\code{project-vector} operation is}
  20488. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20489. straightforward to translate, so we leave that to the reader.
  20490. Regarding the element access operations for tuples\python{ and arrays}, the
  20491. runtime provides procedures that implement them (they are recursive
  20492. functions!), so here we simply need to translate these tuple
  20493. operations into the appropriate function call. For example, here is
  20494. the translation for
  20495. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20496. {\if\edition\racketEd
  20497. \begin{minipage}{0.96\textwidth}
  20498. \begin{lstlisting}
  20499. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20500. |$\Rightarrow$|
  20501. movq |$e_1'$|, %rdi
  20502. movq |$e_2'$|, %rsi
  20503. callq proxy_vector_ref
  20504. movq %rax, |$\itm{lhs'}$|
  20505. \end{lstlisting}
  20506. \end{minipage}
  20507. \fi}
  20508. {\if\edition\pythonEd\pythonColor
  20509. \begin{lstlisting}
  20510. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20511. |$\Rightarrow$|
  20512. movq |$e_1'$|, %rdi
  20513. movq |$e_2'$|, %rsi
  20514. callq proxy_vector_ref
  20515. movq %rax, |$\itm{lhs'}$|
  20516. \end{lstlisting}
  20517. \fi}
  20518. {\if\edition\pythonEd\pythonColor
  20519. % TODO: revisit the names vecof for python -Jeremy
  20520. We translate
  20521. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20522. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20523. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20524. \fi}
  20525. We have another batch of operations to deal with: those for the
  20526. \CANYTY{} type. Recall that we generate an
  20527. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20528. there is a element access on something of type \CANYTY{}, and
  20529. similarly for
  20530. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20531. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20532. section~\ref{sec:select-Lany} we selected instructions for these
  20533. operations on the basis of the idea that the underlying value was a tuple or
  20534. array. But in the current setting, the underlying value is of type
  20535. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20536. functions to deal with this:
  20537. \code{proxy\_vector\_ref},
  20538. \code{proxy\_vector\_set}, and
  20539. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20540. to determine whether the value is a proxy, and then
  20541. dispatches to the the appropriate code.
  20542. %
  20543. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20544. can be translated as follows.
  20545. We begin by projecting the underlying value out of the tagged value and
  20546. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20547. {\if\edition\racketEd
  20548. \begin{lstlisting}
  20549. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20550. |$\Rightarrow$|
  20551. movq |$\neg 111$|, %rdi
  20552. andq |$e_1'$|, %rdi
  20553. movq |$e_2'$|, %rsi
  20554. callq proxy_vector_ref
  20555. movq %rax, |$\itm{lhs'}$|
  20556. \end{lstlisting}
  20557. \fi}
  20558. {\if\edition\pythonEd\pythonColor
  20559. \begin{lstlisting}
  20560. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20561. |$\Rightarrow$|
  20562. movq |$\neg 111$|, %rdi
  20563. andq |$e_1'$|, %rdi
  20564. movq |$e_2'$|, %rsi
  20565. callq proxy_vector_ref
  20566. movq %rax, |$\itm{lhs'}$|
  20567. \end{lstlisting}
  20568. \fi}
  20569. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20570. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20571. are translated in a similar way. Alternatively, you could generate
  20572. instructions to open-code
  20573. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20574. and \code{proxy\_vector\_length} functions.
  20575. \begin{exercise}\normalfont\normalsize
  20576. Implement a compiler for the gradually typed \LangGrad{} language by
  20577. extending and adapting your compiler for \LangLam{}. Create ten new
  20578. partially typed test programs. In addition to testing with these
  20579. new programs, test your compiler on all the tests for \LangLam{}
  20580. and for \LangDyn{}.
  20581. %
  20582. \racket{Sometimes you may get a type-checking error on the
  20583. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20584. the \CANYTY{} type around each subexpression that has caused a type
  20585. error. Although \LangDyn{} does not have explicit casts, you can
  20586. induce one by wrapping the subexpression \code{e} with a call to
  20587. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20588. %
  20589. \python{Sometimes you may get a type-checking error on the
  20590. \LangDyn{} programs, but you can adapt them by inserting a
  20591. temporary variable of type \CANYTY{} that is initialized with the
  20592. troublesome expression.}
  20593. \end{exercise}
  20594. \begin{figure}[t]
  20595. \begin{tcolorbox}[colback=white]
  20596. {\if\edition\racketEd
  20597. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20598. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20599. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20600. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20601. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20602. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20603. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20604. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20605. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20606. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20607. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20608. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20609. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20610. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20611. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20612. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20613. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20614. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20615. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20616. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20617. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20618. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20619. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20620. \path[->,bend left=15] (Lgradual) edge [above] node
  20621. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20622. \path[->,bend left=15] (Lgradual2) edge [above] node
  20623. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20624. \path[->,bend left=15] (Lgradual3) edge [above] node
  20625. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20626. \path[->,bend left=15] (Lgradual4) edge [left] node
  20627. {\ttfamily\footnotesize shrink} (Lgradualr);
  20628. \path[->,bend left=15] (Lgradualr) edge [above] node
  20629. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20630. \path[->,bend right=15] (Lgradualp) edge [above] node
  20631. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20632. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20633. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20634. \path[->,bend right=15] (Llambdapp) edge [above] node
  20635. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20636. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20637. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20638. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20639. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20640. \path[->,bend left=15] (F1-2) edge [above] node
  20641. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20642. \path[->,bend left=15] (F1-3) edge [left] node
  20643. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20644. \path[->,bend left=15] (F1-4) edge [below] node
  20645. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20646. \path[->,bend right=15] (F1-5) edge [above] node
  20647. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20648. \path[->,bend right=15] (F1-6) edge [above] node
  20649. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20650. \path[->,bend right=15] (C3-2) edge [right] node
  20651. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20652. \path[->,bend right=15] (x86-2) edge [right] node
  20653. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20654. \path[->,bend right=15] (x86-2-1) edge [below] node
  20655. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20656. \path[->,bend right=15] (x86-2-2) edge [right] node
  20657. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20658. \path[->,bend left=15] (x86-3) edge [above] node
  20659. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20660. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20661. \end{tikzpicture}
  20662. \fi}
  20663. {\if\edition\pythonEd\pythonColor
  20664. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20665. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20666. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20667. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20668. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20669. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20670. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20671. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20672. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20673. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20674. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20675. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20676. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20677. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20678. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20679. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20680. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20681. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20682. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20683. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20684. \path[->,bend left=15] (Lgradual) edge [above] node
  20685. {\ttfamily\footnotesize shrink} (Lgradual2);
  20686. \path[->,bend left=15] (Lgradual2) edge [above] node
  20687. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20688. \path[->,bend left=15] (Lgradual3) edge [above] node
  20689. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20690. \path[->,bend left=15] (Lgradual4) edge [left] node
  20691. {\ttfamily\footnotesize resolve} (Lgradualr);
  20692. \path[->,bend left=15] (Lgradualr) edge [below] node
  20693. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20694. \path[->,bend right=15] (Lgradualp) edge [above] node
  20695. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20696. \path[->,bend right=15] (Llambdapp) edge [above] node
  20697. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20698. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20699. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20700. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20701. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20702. \path[->,bend left=15] (F1-1) edge [above] node
  20703. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20704. \path[->,bend left=15] (F1-2) edge [above] node
  20705. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20706. \path[->,bend left=15] (F1-3) edge [right] node
  20707. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20708. \path[->,bend right=15] (F1-5) edge [above] node
  20709. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20710. \path[->,bend right=15] (F1-6) edge [above] node
  20711. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20712. \path[->,bend right=15] (C3-2) edge [right] node
  20713. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20714. \path[->,bend right=15] (x86-2) edge [below] node
  20715. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20716. \path[->,bend right=15] (x86-3) edge [below] node
  20717. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20718. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20719. \end{tikzpicture}
  20720. \fi}
  20721. \end{tcolorbox}
  20722. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20723. \label{fig:Lgradual-passes}
  20724. \end{figure}
  20725. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20726. needed for the compilation of \LangGrad{}.
  20727. \section{Further Reading}
  20728. This chapter just scratches the surface of gradual typing. The basic
  20729. approach described here is missing two key ingredients that one would
  20730. want in an implementation of gradual typing: blame
  20731. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20732. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20733. problem addressed by blame tracking is that when a cast on a
  20734. higher-order value fails, it often does so at a point in the program
  20735. that is far removed from the original cast. Blame tracking is a
  20736. technique for propagating extra information through casts and proxies
  20737. so that when a cast fails, the error message can point back to the
  20738. original location of the cast in the source program.
  20739. The problem addressed by space-efficient casts also relates to
  20740. higher-order casts. It turns out that in partially typed programs, a
  20741. function or tuple can flow through a great many casts at runtime. With
  20742. the approach described in this chapter, each cast adds another
  20743. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20744. considerable space, but it also makes the function calls and tuple
  20745. operations slow. For example, a partially typed version of quicksort
  20746. could, in the worst case, build a chain of proxies of length $O(n)$
  20747. around the tuple, changing the overall time complexity of the
  20748. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20749. solution to this problem by representing casts using the coercion
  20750. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20751. long chains of proxies by compressing them into a concise normal
  20752. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20753. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20754. the Grift compiler:
  20755. \begin{center}
  20756. \url{https://github.com/Gradual-Typing/Grift}
  20757. \end{center}
  20758. There are also interesting interactions between gradual typing and
  20759. other language features, such as generics, information-flow types, and
  20760. type inference, to name a few. We recommend to the reader the
  20761. online gradual typing bibliography for more material:
  20762. \begin{center}
  20763. \url{http://samth.github.io/gradual-typing-bib/}
  20764. \end{center}
  20765. % TODO: challenge problem:
  20766. % type analysis and type specialization?
  20767. % coercions?
  20768. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20769. \chapter{Generics}
  20770. \label{ch:Lpoly}
  20771. \setcounter{footnote}{0}
  20772. This chapter studies the compilation of
  20773. generics\index{subject}{generics} (aka parametric
  20774. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20775. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20776. enable programmers to make code more reusable by parameterizing
  20777. functions and data structures with respect to the types on which they
  20778. operate. For example, figure~\ref{fig:map-poly} revisits the
  20779. \code{map} example and this time gives it a more fitting type. This
  20780. \code{map} function is parameterized with respect to the element type
  20781. of the tuple. The type of \code{map} is the following generic type
  20782. specified by the \code{All} type with parameter \code{T}:
  20783. {\if\edition\racketEd
  20784. \begin{lstlisting}
  20785. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20786. \end{lstlisting}
  20787. \fi}
  20788. {\if\edition\pythonEd\pythonColor
  20789. \begin{lstlisting}
  20790. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20791. \end{lstlisting}
  20792. \fi}
  20793. %
  20794. The idea is that \code{map} can be used at \emph{all} choices of a
  20795. type for parameter \code{T}. In the example shown in
  20796. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20797. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20798. \code{T}, but we could have just as well applied \code{map} to a tuple
  20799. of Booleans.
  20800. %
  20801. A \emph{monomorphic} function is simply one that is not generic.
  20802. %
  20803. We use the term \emph{instantiation} for the process (within the
  20804. language implementation) of turning a generic function into a
  20805. monomorphic one, where the type parameters have been replaced by
  20806. types.
  20807. {\if\edition\pythonEd\pythonColor
  20808. %
  20809. In Python, when writing a generic function such as \code{map}, one
  20810. does not explicitly write its generic type (using \code{All}).
  20811. Instead, that the function is generic is implied by the use of type
  20812. variables (such as \code{T}) in the type annotations of its
  20813. parameters.
  20814. %
  20815. \fi}
  20816. \begin{figure}[tbp]
  20817. % poly_test_2.rkt
  20818. \begin{tcolorbox}[colback=white]
  20819. {\if\edition\racketEd
  20820. \begin{lstlisting}
  20821. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20822. (define (map f v)
  20823. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20824. (define (inc [x : Integer]) : Integer (+ x 1))
  20825. (vector-ref (map inc (vector 0 41)) 1)
  20826. \end{lstlisting}
  20827. \fi}
  20828. {\if\edition\pythonEd\pythonColor
  20829. \begin{lstlisting}
  20830. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20831. return (f(tup[0]), f(tup[1]))
  20832. def add1(x : int) -> int:
  20833. return x + 1
  20834. t = map(add1, (0, 41))
  20835. print(t[1])
  20836. \end{lstlisting}
  20837. \fi}
  20838. \end{tcolorbox}
  20839. \caption{A generic version of the \code{map} function.}
  20840. \label{fig:map-poly}
  20841. \end{figure}
  20842. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20843. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20844. shows the definition of the abstract syntax.
  20845. %
  20846. {\if\edition\racketEd
  20847. We add a second form for function definitions in which a type
  20848. declaration comes before the \code{define}. In the abstract syntax,
  20849. the return type in the \code{Def} is \CANYTY{}, but that should be
  20850. ignored in favor of the return type in the type declaration. (The
  20851. \CANYTY{} comes from using the same parser as discussed in
  20852. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20853. enables the use of an \code{All} type for a function, thereby making
  20854. it generic.
  20855. \fi}
  20856. %
  20857. The grammar for types is extended to include the type of a generic
  20858. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20859. abstract syntax)}.
  20860. \newcommand{\LpolyGrammarRacket}{
  20861. \begin{array}{lcl}
  20862. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20863. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20864. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20865. \end{array}
  20866. }
  20867. \newcommand{\LpolyASTRacket}{
  20868. \begin{array}{lcl}
  20869. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20870. \Def &::=& \DECL{\Var}{\Type} \\
  20871. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20872. \end{array}
  20873. }
  20874. \newcommand{\LpolyGrammarPython}{
  20875. \begin{array}{lcl}
  20876. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20877. \end{array}
  20878. }
  20879. \newcommand{\LpolyASTPython}{
  20880. \begin{array}{lcl}
  20881. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20882. \MID \key{GenericVar}\LP\Var\RP
  20883. \end{array}
  20884. }
  20885. \begin{figure}[tp]
  20886. \centering
  20887. \begin{tcolorbox}[colback=white]
  20888. \footnotesize
  20889. {\if\edition\racketEd
  20890. \[
  20891. \begin{array}{l}
  20892. \gray{\LintGrammarRacket{}} \\ \hline
  20893. \gray{\LvarGrammarRacket{}} \\ \hline
  20894. \gray{\LifGrammarRacket{}} \\ \hline
  20895. \gray{\LwhileGrammarRacket} \\ \hline
  20896. \gray{\LtupGrammarRacket} \\ \hline
  20897. \gray{\LfunGrammarRacket} \\ \hline
  20898. \gray{\LlambdaGrammarRacket} \\ \hline
  20899. \LpolyGrammarRacket \\
  20900. \begin{array}{lcl}
  20901. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20902. \end{array}
  20903. \end{array}
  20904. \]
  20905. \fi}
  20906. {\if\edition\pythonEd\pythonColor
  20907. \[
  20908. \begin{array}{l}
  20909. \gray{\LintGrammarPython{}} \\ \hline
  20910. \gray{\LvarGrammarPython{}} \\ \hline
  20911. \gray{\LifGrammarPython{}} \\ \hline
  20912. \gray{\LwhileGrammarPython} \\ \hline
  20913. \gray{\LtupGrammarPython} \\ \hline
  20914. \gray{\LfunGrammarPython} \\ \hline
  20915. \gray{\LlambdaGrammarPython} \\\hline
  20916. \LpolyGrammarPython \\
  20917. \begin{array}{lcl}
  20918. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20919. \end{array}
  20920. \end{array}
  20921. \]
  20922. \fi}
  20923. \end{tcolorbox}
  20924. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20925. (figure~\ref{fig:Llam-concrete-syntax}).}
  20926. \label{fig:Lpoly-concrete-syntax}
  20927. \index{subject}{Lgen@\LangPoly{} concrete syntax}
  20928. \end{figure}
  20929. \begin{figure}[tp]
  20930. \centering
  20931. \begin{tcolorbox}[colback=white]
  20932. \footnotesize
  20933. {\if\edition\racketEd
  20934. \[
  20935. \begin{array}{l}
  20936. \gray{\LintOpAST} \\ \hline
  20937. \gray{\LvarASTRacket{}} \\ \hline
  20938. \gray{\LifASTRacket{}} \\ \hline
  20939. \gray{\LwhileASTRacket{}} \\ \hline
  20940. \gray{\LtupASTRacket{}} \\ \hline
  20941. \gray{\LfunASTRacket} \\ \hline
  20942. \gray{\LlambdaASTRacket} \\ \hline
  20943. \LpolyASTRacket \\
  20944. \begin{array}{lcl}
  20945. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20946. \end{array}
  20947. \end{array}
  20948. \]
  20949. \fi}
  20950. {\if\edition\pythonEd\pythonColor
  20951. \[
  20952. \begin{array}{l}
  20953. \gray{\LintASTPython} \\ \hline
  20954. \gray{\LvarASTPython{}} \\ \hline
  20955. \gray{\LifASTPython{}} \\ \hline
  20956. \gray{\LwhileASTPython{}} \\ \hline
  20957. \gray{\LtupASTPython{}} \\ \hline
  20958. \gray{\LfunASTPython} \\ \hline
  20959. \gray{\LlambdaASTPython} \\ \hline
  20960. \LpolyASTPython \\
  20961. \begin{array}{lcl}
  20962. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20963. \end{array}
  20964. \end{array}
  20965. \]
  20966. \fi}
  20967. \end{tcolorbox}
  20968. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20969. (figure~\ref{fig:Llam-syntax}).}
  20970. \label{fig:Lpoly-syntax}
  20971. \index{subject}{Lgen@\LangPoly{} abstract syntax}
  20972. \end{figure}
  20973. By including the \code{All} type in the $\Type$ nonterminal of the
  20974. grammar we choose to make generics first class, which has interesting
  20975. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20976. not include syntax for the \code{All} type. It is inferred for functions whose
  20977. type annotations contain type variables.} Many languages with generics, such as
  20978. C++~\citep{stroustrup88:_param_types} and Standard
  20979. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20980. may be helpful to see an example of first-class generics in action. In
  20981. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20982. whose parameter is a generic function. Indeed, because the grammar for
  20983. $\Type$ includes the \code{All} type, a generic function may also be
  20984. returned from a function or stored inside a tuple. The body of
  20985. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20986. and also to an integer, which would not be possible if \code{f} were
  20987. not generic.
  20988. \begin{figure}[tbp]
  20989. \begin{tcolorbox}[colback=white]
  20990. {\if\edition\racketEd
  20991. \begin{lstlisting}
  20992. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20993. (define (apply_twice f)
  20994. (if (f #t) (f 42) (f 777)))
  20995. (: id (All (T) (T -> T)))
  20996. (define (id x) x)
  20997. (apply_twice id)
  20998. \end{lstlisting}
  20999. \fi}
  21000. {\if\edition\pythonEd\pythonColor
  21001. \begin{lstlisting}
  21002. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  21003. if f(True):
  21004. return f(42)
  21005. else:
  21006. return f(777)
  21007. def id(x: T) -> T:
  21008. return x
  21009. print(apply_twice(id))
  21010. \end{lstlisting}
  21011. \fi}
  21012. \end{tcolorbox}
  21013. \caption{An example illustrating first-class generics.}
  21014. \label{fig:apply-twice}
  21015. \end{figure}
  21016. The type checker for \LangPoly{} shown in
  21017. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  21018. (compared to \LangLam{}) which we discuss in the following paragraphs.
  21019. {\if\edition\pythonEd\pythonColor
  21020. %
  21021. Regarding function definitions, if the type annotations on its
  21022. parameters contain generic variables, then the function is generic and
  21023. therefore its type is an \code{All} type wrapped around a function
  21024. type. Otherwise the function is monomorphic and its type is simply
  21025. a function type.
  21026. %
  21027. \fi}
  21028. The type checking of a function application is extended to handle the
  21029. case in which the operator expression is a generic function. In that case
  21030. the type arguments are deduced by matching the types of the parameters
  21031. with the types of the arguments.
  21032. %
  21033. The \code{match\_types} auxiliary function
  21034. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  21035. recursively descending through a parameter type \code{param\_ty} and
  21036. the corresponding argument type \code{arg\_ty}, making sure that they
  21037. are equal except when there is a type parameter in the parameter
  21038. type. Upon encountering a type parameter for the first time, the
  21039. algorithm deduces an association of the type parameter to the
  21040. corresponding part of the argument type. If it is not the first time
  21041. that the type parameter has been encountered, the algorithm looks up
  21042. its deduced type and makes sure that it is equal to the corresponding
  21043. part of the argument type. The return type of the application is the
  21044. return type of the generic function with the type parameters
  21045. replaced by the deduced type arguments, using the
  21046. \code{substitute\_type} auxiliary function, which is also listed in
  21047. figure~\ref{fig:type-check-Lpoly-aux}.
  21048. The type checker extends type equality to handle the \code{All} type.
  21049. This is not quite as simple as for other types, such as function and
  21050. tuple types, because two \code{All} types can be syntactically
  21051. different even though they are equivalent. For example,
  21052. \begin{center}
  21053. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  21054. \end{center}
  21055. is equivalent to
  21056. \begin{center}
  21057. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  21058. \end{center}
  21059. Two generic types are equal if they differ only in
  21060. the choice of the names of the type parameters. The definition of type
  21061. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  21062. parameters in one type to match the type parameters of the other type.
  21063. {\if\edition\racketEd
  21064. %
  21065. The type checker also ensures that only defined type variables appear
  21066. in type annotations. The \code{check\_well\_formed} function for which
  21067. the definition is shown in figure~\ref{fig:well-formed-types}
  21068. recursively inspects a type, making sure that each type variable has
  21069. been defined.
  21070. %
  21071. \fi}
  21072. \begin{figure}[tbp]
  21073. \begin{tcolorbox}[colback=white]
  21074. {\if\edition\racketEd
  21075. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21076. (define type-check-poly-class
  21077. (class type-check-Llambda-class
  21078. (super-new)
  21079. (inherit check-type-equal?)
  21080. (define/override (type-check-apply env e1 es)
  21081. (define-values (e^ ty) ((type-check-exp env) e1))
  21082. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  21083. ((type-check-exp env) e)))
  21084. (match ty
  21085. [`(,ty^* ... -> ,rt)
  21086. (for ([arg-ty ty*] [param-ty ty^*])
  21087. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  21088. (values e^ es^ rt)]
  21089. [`(All ,xs (,tys ... -> ,rt))
  21090. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21091. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  21092. (match_types env^^ param-ty arg-ty)))
  21093. (define targs
  21094. (for/list ([x xs])
  21095. (match (dict-ref env^^ x (lambda () #f))
  21096. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  21097. x (Apply e1 es))]
  21098. [ty ty])))
  21099. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  21100. [else (error 'type-check "expected a function, not ~a" ty)]))
  21101. (define/override ((type-check-exp env) e)
  21102. (match e
  21103. [(Lambda `([,xs : ,Ts] ...) rT body)
  21104. (for ([T Ts]) ((check_well_formed env) T))
  21105. ((check_well_formed env) rT)
  21106. ((super type-check-exp env) e)]
  21107. [(HasType e1 ty)
  21108. ((check_well_formed env) ty)
  21109. ((super type-check-exp env) e)]
  21110. [else ((super type-check-exp env) e)]))
  21111. (define/override ((type-check-def env) d)
  21112. (verbose 'type-check "poly/def" d)
  21113. (match d
  21114. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  21115. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  21116. (for ([p ps]) ((check_well_formed ts-env) p))
  21117. ((check_well_formed ts-env) rt)
  21118. (define new-env (append ts-env (map cons xs ps) env))
  21119. (define-values (body^ ty^) ((type-check-exp new-env) body))
  21120. (check-type-equal? ty^ rt body)
  21121. (Generic ts (Def f p:t* rt info body^))]
  21122. [else ((super type-check-def env) d)]))
  21123. (define/override (type-check-program p)
  21124. (match p
  21125. [(Program info body)
  21126. (type-check-program (ProgramDefsExp info '() body))]
  21127. [(ProgramDefsExp info ds body)
  21128. (define ds^ (combine-decls-defs ds))
  21129. (define new-env (for/list ([d ds^])
  21130. (cons (def-name d) (fun-def-type d))))
  21131. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  21132. (define-values (body^ ty) ((type-check-exp new-env) body))
  21133. (check-type-equal? ty 'Integer body)
  21134. (ProgramDefsExp info ds^^ body^)]))
  21135. ))
  21136. \end{lstlisting}
  21137. \fi}
  21138. {\if\edition\pythonEd\pythonColor
  21139. \begin{lstlisting}[basicstyle=\ttfamily\small]
  21140. def type_check_exp(self, e, env):
  21141. match e:
  21142. case Call(Name(f), args) if f in builtin_functions:
  21143. return super().type_check_exp(e, env)
  21144. case Call(func, args):
  21145. func_t = self.type_check_exp(func, env)
  21146. func.has_type = func_t
  21147. match func_t:
  21148. case AllType(ps, FunctionType(p_tys, rt)):
  21149. for arg in args:
  21150. arg.has_type = self.type_check_exp(arg, env)
  21151. arg_tys = [arg.has_type for arg in args]
  21152. deduced = {}
  21153. for (p, a) in zip(p_tys, arg_tys):
  21154. self.match_types(p, a, deduced, e)
  21155. return self.substitute_type(rt, deduced)
  21156. case _:
  21157. return super().type_check_exp(e, env)
  21158. case _:
  21159. return super().type_check_exp(e, env)
  21160. def type_check(self, p):
  21161. match p:
  21162. case Module(body):
  21163. env = {}
  21164. for s in body:
  21165. match s:
  21166. case FunctionDef(name, params, bod, dl, returns, comment):
  21167. params_t = [t for (x,t) in params]
  21168. ty_params = set()
  21169. for t in params_t:
  21170. ty_params |$\mid$|= self.generic_variables(t)
  21171. ty = FunctionType(params_t, returns)
  21172. if len(ty_params) > 0:
  21173. ty = AllType(list(ty_params), ty)
  21174. env[name] = ty
  21175. self.check_stmts(body, IntType(), env)
  21176. case _:
  21177. raise Exception('type_check: unexpected ' + repr(p))
  21178. \end{lstlisting}
  21179. \fi}
  21180. \end{tcolorbox}
  21181. \caption{Type checker for the \LangPoly{} language.}
  21182. \label{fig:type-check-Lpoly}
  21183. \end{figure}
  21184. \begin{figure}[tbp]
  21185. \begin{tcolorbox}[colback=white]
  21186. {\if\edition\racketEd
  21187. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21188. (define/override (type-equal? t1 t2)
  21189. (match* (t1 t2)
  21190. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21191. (define env (map cons xs ys))
  21192. (type-equal? (substitute_type env T1) T2)]
  21193. [(other wise)
  21194. (super type-equal? t1 t2)]))
  21195. (define/public (match_types env pt at)
  21196. (match* (pt at)
  21197. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21198. [('Void 'Void) env] [('Any 'Any) env]
  21199. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21200. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21201. (match_types env^ pt1 at1))]
  21202. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21203. (define env^ (match_types env prt art))
  21204. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21205. (match_types env^^ pt1 at1))]
  21206. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21207. (define env^ (append (map cons pxs axs) env))
  21208. (match_types env^ pt1 at1)]
  21209. [((? symbol? x) at)
  21210. (match (dict-ref env x (lambda () #f))
  21211. [#f (error 'type-check "undefined type variable ~a" x)]
  21212. ['Type (cons (cons x at) env)]
  21213. [t^ (check-type-equal? at t^ 'matching) env])]
  21214. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21215. (define/public (substitute_type env pt)
  21216. (match pt
  21217. ['Integer 'Integer] ['Boolean 'Boolean]
  21218. ['Void 'Void] ['Any 'Any]
  21219. [`(Vector ,ts ...)
  21220. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21221. [`(,ts ... -> ,rt)
  21222. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21223. [`(All ,xs ,t)
  21224. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21225. [(? symbol? x) (dict-ref env x)]
  21226. [else (error 'type-check "expected a type not ~a" pt)]))
  21227. (define/public (combine-decls-defs ds)
  21228. (match ds
  21229. ['() '()]
  21230. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21231. (unless (equal? name f)
  21232. (error 'type-check "name mismatch, ~a != ~a" name f))
  21233. (match type
  21234. [`(All ,xs (,ps ... -> ,rt))
  21235. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21236. (cons (Generic xs (Def name params^ rt info body))
  21237. (combine-decls-defs ds^))]
  21238. [`(,ps ... -> ,rt)
  21239. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21240. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21241. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21242. [`(,(Def f params rt info body) . ,ds^)
  21243. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21244. \end{lstlisting}
  21245. \fi}
  21246. {\if\edition\pythonEd\pythonColor
  21247. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21248. def match_types(self, param_ty, arg_ty, deduced, e):
  21249. match (param_ty, arg_ty):
  21250. case (GenericVar(id), _):
  21251. if id in deduced:
  21252. self.check_type_equal(arg_ty, deduced[id], e)
  21253. else:
  21254. deduced[id] = arg_ty
  21255. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21256. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21257. new_arg_ty = self.substitute_type(arg_ty, rename)
  21258. self.match_types(ty, new_arg_ty, deduced, e)
  21259. case (TupleType(ps), TupleType(ts)):
  21260. for (p, a) in zip(ps, ts):
  21261. self.match_types(p, a, deduced, e)
  21262. case (ListType(p), ListType(a)):
  21263. self.match_types(p, a, deduced, e)
  21264. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21265. for (pp, ap) in zip(pps, aps):
  21266. self.match_types(pp, ap, deduced, e)
  21267. self.match_types(prt, art, deduced, e)
  21268. case (IntType(), IntType()):
  21269. pass
  21270. case (BoolType(), BoolType()):
  21271. pass
  21272. case _:
  21273. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21274. def substitute_type(self, ty, var_map):
  21275. match ty:
  21276. case GenericVar(id):
  21277. return var_map[id]
  21278. case AllType(ps, ty):
  21279. new_map = copy.deepcopy(var_map)
  21280. for p in ps:
  21281. new_map[p] = GenericVar(p)
  21282. return AllType(ps, self.substitute_type(ty, new_map))
  21283. case TupleType(ts):
  21284. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21285. case ListType(ty):
  21286. return ListType(self.substitute_type(ty, var_map))
  21287. case FunctionType(pts, rt):
  21288. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21289. self.substitute_type(rt, var_map))
  21290. case IntType():
  21291. return IntType()
  21292. case BoolType():
  21293. return BoolType()
  21294. case _:
  21295. raise Exception('substitute_type: unexpected ' + repr(ty))
  21296. def check_type_equal(self, t1, t2, e):
  21297. match (t1, t2):
  21298. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21299. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21300. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21301. case (_, _):
  21302. return super().check_type_equal(t1, t2, e)
  21303. \end{lstlisting}
  21304. \fi}
  21305. \end{tcolorbox}
  21306. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21307. \label{fig:type-check-Lpoly-aux}
  21308. \end{figure}
  21309. {\if\edition\racketEd
  21310. \begin{figure}[tbp]
  21311. \begin{tcolorbox}[colback=white]
  21312. \begin{lstlisting}
  21313. (define/public ((check_well_formed env) ty)
  21314. (match ty
  21315. ['Integer (void)]
  21316. ['Boolean (void)]
  21317. ['Void (void)]
  21318. [(? symbol? a)
  21319. (match (dict-ref env a (lambda () #f))
  21320. ['Type (void)]
  21321. [else (error 'type-check "undefined type variable ~a" a)])]
  21322. [`(Vector ,ts ...)
  21323. (for ([t ts]) ((check_well_formed env) t))]
  21324. [`(,ts ... -> ,t)
  21325. (for ([t ts]) ((check_well_formed env) t))
  21326. ((check_well_formed env) t)]
  21327. [`(All ,xs ,t)
  21328. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21329. ((check_well_formed env^) t)]
  21330. [else (error 'type-check "unrecognized type ~a" ty)]))
  21331. \end{lstlisting}
  21332. \end{tcolorbox}
  21333. \caption{Well-formed types.}
  21334. \label{fig:well-formed-types}
  21335. \end{figure}
  21336. \fi}
  21337. % TODO: interpreter for R'_10
  21338. \clearpage
  21339. \section{Compiling Generics}
  21340. \label{sec:compiling-poly}
  21341. Broadly speaking, there are four approaches to compiling generics, as
  21342. follows:
  21343. \begin{description}
  21344. \item[Monomorphization] generates a different version of a generic
  21345. function for each set of type arguments with which it is used,
  21346. producing type-specialized code. This approach results in the most
  21347. efficient code but requires whole-program compilation (no separate
  21348. compilation) and may increase code size. Unfortunately,
  21349. monomorphization is incompatible with first-class generics because
  21350. it is not always possible to determine which generic functions are
  21351. used with which type arguments during compilation. (It can be done
  21352. at runtime with just-in-time compilation.) Monomorphization is
  21353. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21354. generic functions in NESL~\citep{Blelloch:1993aa} and
  21355. ML~\citep{Weeks:2006aa}.
  21356. \item[Uniform representation] generates one version of each generic
  21357. function and requires all values to have a common \emph{boxed} format,
  21358. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21359. generic and monomorphic code is compiled similarly to code in a
  21360. dynamically typed language (like \LangDyn{}), in which primitive
  21361. operators require their arguments to be projected from \CANYTY{} and
  21362. their results to be injected into \CANYTY{}. (In object-oriented
  21363. languages, the projection is accomplished via virtual method
  21364. dispatch.) The uniform representation approach is compatible with
  21365. separate compilation and with first-class generics. However, it
  21366. produces the least efficient code because it introduces overhead in
  21367. the entire program. This approach is used in
  21368. Java~\citep{Bracha:1998fk},
  21369. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21370. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21371. \item[Mixed representation] generates one version of each generic
  21372. function, using a boxed representation for type variables. However,
  21373. monomorphic code is compiled as usual (as in \LangLam{}), and
  21374. conversions are performed at the boundaries between monomorphic code
  21375. and polymorphic code (for example, when a generic function is instantiated
  21376. and called). This approach is compatible with separate compilation
  21377. and first-class generics and maintains efficiency in monomorphic
  21378. code. The trade-off is increased overhead at the boundary between
  21379. monomorphic and generic code. This approach is used in
  21380. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21381. Java 5 with the addition of autoboxing.
  21382. \item[Type passing] uses the unboxed representation in both
  21383. monomorphic and generic code. Each generic function is compiled to a
  21384. single function with extra parameters that describe the type
  21385. arguments. The type information is used by the generated code to
  21386. determine how to access the unboxed values at runtime. This approach is
  21387. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21388. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21389. compilation and first-class generics and maintains the
  21390. efficiency for monomorphic code. There is runtime overhead in
  21391. polymorphic code from dispatching on type information.
  21392. \end{description}
  21393. In this chapter we use the mixed representation approach, partly
  21394. because of its favorable attributes and partly because it is
  21395. straightforward to implement using the tools that we have already
  21396. built to support gradual typing. The work of compiling generic
  21397. functions is performed in two passes, \code{resolve} and
  21398. \code{erase\_types}, that we discuss next. The output of
  21399. \code{erase\_types} is \LangCast{}
  21400. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21401. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21402. \section{Resolve Instantiation}
  21403. \label{sec:generic-resolve}
  21404. Recall that the type checker for \LangPoly{} deduces the type
  21405. arguments at call sites to a generic function. The purpose of the
  21406. \code{resolve} pass is to turn this implicit instantiation into an
  21407. explicit one, by adding \code{inst} nodes to the syntax of the
  21408. intermediate language. An \code{inst} node records the mapping of
  21409. type parameters to type arguments. The semantics of the \code{inst}
  21410. node is to instantiate the result of its first argument, a generic
  21411. function, to produce a monomorphic function. However, because the
  21412. interpreter never analyzes type annotations, instantiation can be a
  21413. no-op and simply return the generic function.
  21414. %
  21415. The output language of the \code{resolve} pass is \LangInst{},
  21416. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21417. {\if\edition\racketEd
  21418. The \code{resolve} pass combines the type declaration and polymorphic
  21419. function into a single definition, using the \code{Poly} form, to make
  21420. polymorphic functions more convenient to process in the next pass of the
  21421. compiler.
  21422. \fi}
  21423. \newcommand{\LinstASTRacket}{
  21424. \begin{array}{lcl}
  21425. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21426. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21427. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21428. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21429. \end{array}
  21430. }
  21431. \newcommand{\LinstASTPython}{
  21432. \begin{array}{lcl}
  21433. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21434. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21435. \end{array}
  21436. }
  21437. \begin{figure}[tp]
  21438. \centering
  21439. \begin{tcolorbox}[colback=white]
  21440. \small
  21441. {\if\edition\racketEd
  21442. \[
  21443. \begin{array}{l}
  21444. \gray{\LintOpAST} \\ \hline
  21445. \gray{\LvarASTRacket{}} \\ \hline
  21446. \gray{\LifASTRacket{}} \\ \hline
  21447. \gray{\LwhileASTRacket{}} \\ \hline
  21448. \gray{\LtupASTRacket{}} \\ \hline
  21449. \gray{\LfunASTRacket} \\ \hline
  21450. \gray{\LlambdaASTRacket} \\ \hline
  21451. \LinstASTRacket \\
  21452. \begin{array}{lcl}
  21453. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21454. \end{array}
  21455. \end{array}
  21456. \]
  21457. \fi}
  21458. {\if\edition\pythonEd\pythonColor
  21459. \[
  21460. \begin{array}{l}
  21461. \gray{\LintASTPython} \\ \hline
  21462. \gray{\LvarASTPython{}} \\ \hline
  21463. \gray{\LifASTPython{}} \\ \hline
  21464. \gray{\LwhileASTPython{}} \\ \hline
  21465. \gray{\LtupASTPython{}} \\ \hline
  21466. \gray{\LfunASTPython} \\ \hline
  21467. \gray{\LlambdaASTPython} \\ \hline
  21468. \LinstASTPython \\
  21469. \begin{array}{lcl}
  21470. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21471. \end{array}
  21472. \end{array}
  21473. \]
  21474. \fi}
  21475. \end{tcolorbox}
  21476. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21477. (figure~\ref{fig:Llam-syntax}).}
  21478. \label{fig:Lpoly-prime-syntax}
  21479. \index{subject}{Linst@\LangInst{} abstract syntax}
  21480. \end{figure}
  21481. The output of the \code{resolve} pass on the generic \code{map}
  21482. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21483. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21484. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21485. \begin{figure}[tbp]
  21486. % poly_test_2.rkt
  21487. \begin{tcolorbox}[colback=white]
  21488. {\if\edition\racketEd
  21489. \begin{lstlisting}
  21490. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21491. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21492. (define (inc [x : Integer]) : Integer (+ x 1))
  21493. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21494. (Integer))
  21495. inc (vector 0 41)) 1)
  21496. \end{lstlisting}
  21497. \fi}
  21498. {\if\edition\pythonEd\pythonColor
  21499. \begin{lstlisting}
  21500. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21501. return (f(tup[0]), f(tup[1]))
  21502. def add1(x : int) -> int:
  21503. return x + 1
  21504. t = inst(map, {T: int})(add1, (0, 41))
  21505. print(t[1])
  21506. \end{lstlisting}
  21507. \fi}
  21508. \end{tcolorbox}
  21509. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21510. \label{fig:map-resolve}
  21511. \end{figure}
  21512. \section{Erase Generic Types}
  21513. \label{sec:erase_types}
  21514. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21515. represent type variables. For example, figure~\ref{fig:map-erase}
  21516. shows the output of the \code{erase\_types} pass on the generic
  21517. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21518. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21519. \code{All} types are removed from the type of \code{map}.
  21520. \begin{figure}[tbp]
  21521. \begin{tcolorbox}[colback=white]
  21522. {\if\edition\racketEd
  21523. \begin{lstlisting}
  21524. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21525. : (Vector Any Any)
  21526. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21527. (define (inc [x : Integer]) : Integer (+ x 1))
  21528. (vector-ref ((cast map
  21529. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21530. ((Integer -> Integer) (Vector Integer Integer)
  21531. -> (Vector Integer Integer)))
  21532. inc (vector 0 41)) 1)
  21533. \end{lstlisting}
  21534. \fi}
  21535. {\if\edition\pythonEd\pythonColor
  21536. \begin{lstlisting}
  21537. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21538. return (f(tup[0]), f(tup[1]))
  21539. def add1(x : int) -> int:
  21540. return (x + 1)
  21541. def main() -> int:
  21542. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21543. print(t[1])
  21544. return 0
  21545. \end{lstlisting}
  21546. {\small
  21547. where\\
  21548. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21549. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21550. }
  21551. \fi}
  21552. \end{tcolorbox}
  21553. \caption{The generic \code{map} example after type erasure.}
  21554. \label{fig:map-erase}
  21555. \end{figure}
  21556. This process of type erasure creates a challenge at points of
  21557. instantiation. For example, consider the instantiation of
  21558. \code{map} shown in figure~\ref{fig:map-resolve}.
  21559. The type of \code{map} is
  21560. %
  21561. {\if\edition\racketEd
  21562. \begin{lstlisting}
  21563. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21564. \end{lstlisting}
  21565. \fi}
  21566. {\if\edition\pythonEd\pythonColor
  21567. \begin{lstlisting}
  21568. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21569. \end{lstlisting}
  21570. \fi}
  21571. %
  21572. \noindent and it is instantiated to
  21573. %
  21574. {\if\edition\racketEd
  21575. \begin{lstlisting}
  21576. ((Integer -> Integer) (Vector Integer Integer)
  21577. -> (Vector Integer Integer))
  21578. \end{lstlisting}
  21579. \fi}
  21580. {\if\edition\pythonEd\pythonColor
  21581. \begin{lstlisting}
  21582. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21583. \end{lstlisting}
  21584. \fi}
  21585. %
  21586. \noindent After erasure, the type of \code{map} is
  21587. %
  21588. {\if\edition\racketEd
  21589. \begin{lstlisting}
  21590. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21591. \end{lstlisting}
  21592. \fi}
  21593. {\if\edition\pythonEd\pythonColor
  21594. \begin{lstlisting}
  21595. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21596. \end{lstlisting}
  21597. \fi}
  21598. %
  21599. \noindent but we need to convert it to the instantiated type. This is
  21600. easy to do in the language \LangCast{} with a single \code{cast}. In
  21601. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21602. \code{map} has been compiled to a \code{cast} from the type of
  21603. \code{map} to the instantiated type. The source and the target type of
  21604. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21605. is the case because both the source and target are obtained from the
  21606. same generic type of \code{map}, replacing the type parameters with
  21607. \CANYTY{} in the former and with the deduced type arguments in the
  21608. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21609. To implement the \code{erase\_types} pass, we first recommend defining
  21610. a recursive function that translates types, named
  21611. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21612. follows.
  21613. %
  21614. {\if\edition\racketEd
  21615. \begin{lstlisting}
  21616. |$T$|
  21617. |$\Rightarrow$|
  21618. Any
  21619. \end{lstlisting}
  21620. \fi}
  21621. {\if\edition\pythonEd\pythonColor
  21622. \begin{lstlisting}
  21623. GenericVar(|$T$|)
  21624. |$\Rightarrow$|
  21625. Any
  21626. \end{lstlisting}
  21627. \fi}
  21628. %
  21629. \noindent The \code{erase\_type} function also removes the generic
  21630. \code{All} types.
  21631. %
  21632. {\if\edition\racketEd
  21633. \begin{lstlisting}
  21634. (All |$xs$| |$T_1$|)
  21635. |$\Rightarrow$|
  21636. |$T'_1$|
  21637. \end{lstlisting}
  21638. \fi}
  21639. {\if\edition\pythonEd\pythonColor
  21640. \begin{lstlisting}
  21641. AllType(|$xs$|, |$T_1$|)
  21642. |$\Rightarrow$|
  21643. |$T'_1$|
  21644. \end{lstlisting}
  21645. \fi}
  21646. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21647. $T_1$.
  21648. %
  21649. In this compiler pass, apply the \code{erase\_type} function to all
  21650. the type annotations in the program.
  21651. Regarding the translation of expressions, the case for \code{Inst} is
  21652. the interesting one. We translate it into a \code{Cast}, as shown
  21653. next.
  21654. The type of the subexpression $e$ is a generic type of the form
  21655. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21656. The source type of the cast is the erasure of $T$, the type $T_s$.
  21657. %
  21658. {\if\edition\racketEd
  21659. %
  21660. The target type $T_t$ is the result of substituting the argument types
  21661. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21662. erasure.
  21663. %
  21664. \begin{lstlisting}
  21665. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21666. |$\Rightarrow$|
  21667. (Cast |$e'$| |$T_s$| |$T_t$|)
  21668. \end{lstlisting}
  21669. %
  21670. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21671. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21672. \fi}
  21673. {\if\edition\pythonEd\pythonColor
  21674. %
  21675. The target type $T_t$ is the result of substituting the deduced
  21676. argument types $d$ in $T$ and then performing type erasure.
  21677. %
  21678. \begin{lstlisting}
  21679. Inst(|$e$|, |$d$|)
  21680. |$\Rightarrow$|
  21681. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21682. \end{lstlisting}
  21683. %
  21684. where
  21685. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21686. \fi}
  21687. Finally, each generic function is translated to a regular
  21688. function in which type erasure has been applied to all the type
  21689. annotations and the body.
  21690. %% \begin{lstlisting}
  21691. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21692. %% |$\Rightarrow$|
  21693. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21694. %% \end{lstlisting}
  21695. \begin{exercise}\normalfont\normalsize
  21696. Implement a compiler for the polymorphic language \LangPoly{} by
  21697. extending and adapting your compiler for \LangGrad{}. Create six new
  21698. test programs that use polymorphic functions. Some of them should
  21699. make use of first-class generics.
  21700. \end{exercise}
  21701. \begin{figure}[tbp]
  21702. \begin{tcolorbox}[colback=white]
  21703. {\if\edition\racketEd
  21704. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21705. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21706. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21707. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21708. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21709. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21710. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21711. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21712. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21713. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21714. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21715. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21716. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21717. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21718. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21719. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21720. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21721. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21722. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21723. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21724. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21725. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21726. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21727. \path[->,bend left=15] (Lpoly) edge [above] node
  21728. {\ttfamily\footnotesize resolve} (Lpolyp);
  21729. \path[->,bend left=15] (Lpolyp) edge [above] node
  21730. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21731. \path[->,bend left=15] (Lgradualp) edge [above] node
  21732. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21733. \path[->,bend left=15] (Llambdapp) edge [left] node
  21734. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21735. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21736. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21737. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21738. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21739. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21740. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21741. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21742. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21743. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21744. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21745. \path[->,bend left=15] (F1-1) edge [above] node
  21746. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21747. \path[->,bend left=15] (F1-2) edge [above] node
  21748. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21749. \path[->,bend left=15] (F1-3) edge [left] node
  21750. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21751. \path[->,bend left=15] (F1-4) edge [below] node
  21752. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21753. \path[->,bend right=15] (F1-5) edge [above] node
  21754. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21755. \path[->,bend right=15] (F1-6) edge [above] node
  21756. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21757. \path[->,bend right=15] (C3-2) edge [right] node
  21758. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21759. \path[->,bend right=15] (x86-2) edge [right] node
  21760. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21761. \path[->,bend right=15] (x86-2-1) edge [below] node
  21762. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21763. \path[->,bend right=15] (x86-2-2) edge [right] node
  21764. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21765. \path[->,bend left=15] (x86-3) edge [above] node
  21766. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21767. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21768. \end{tikzpicture}
  21769. \fi}
  21770. {\if\edition\pythonEd\pythonColor
  21771. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21772. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21773. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21774. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21775. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21776. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21777. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21778. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21779. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21780. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21781. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21782. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21783. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21784. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21785. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21786. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21787. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21788. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21789. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21790. \path[->,bend left=15] (Lgradual) edge [above] node
  21791. {\ttfamily\footnotesize shrink} (Lgradual2);
  21792. \path[->,bend left=15] (Lgradual2) edge [above] node
  21793. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21794. \path[->,bend left=15] (Lgradual3) edge [above] node
  21795. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21796. \path[->,bend left=15] (Lgradual4) edge [left] node
  21797. {\ttfamily\footnotesize resolve} (Lgradualr);
  21798. \path[->,bend left=15] (Lgradualr) edge [below] node
  21799. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21800. \path[->,bend right=15] (Llambdapp) edge [above] node
  21801. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21802. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21803. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21804. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21805. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21806. \path[->,bend right=15] (F1-1) edge [below] node
  21807. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21808. \path[->,bend right=15] (F1-2) edge [below] node
  21809. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21810. \path[->,bend left=15] (F1-3) edge [above] node
  21811. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21812. \path[->,bend left=15] (F1-5) edge [left] node
  21813. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21814. \path[->,bend left=5] (F1-6) edge [below] node
  21815. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21816. \path[->,bend right=15] (C3-2) edge [right] node
  21817. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21818. \path[->,bend right=15] (x86-2) edge [below] node
  21819. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21820. \path[->,bend right=15] (x86-3) edge [below] node
  21821. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21822. \path[->,bend left=15] (x86-4) edge [above] node
  21823. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21824. \end{tikzpicture}
  21825. \fi}
  21826. \end{tcolorbox}
  21827. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21828. \label{fig:Lpoly-passes}
  21829. \end{figure}
  21830. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21831. needed to compile \LangPoly{}.
  21832. % TODO: challenge problem: specialization of instantiations
  21833. % Further Reading
  21834. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21835. \clearpage
  21836. \appendix
  21837. \chapter{Appendix}
  21838. \setcounter{footnote}{0}
  21839. {\if\edition\racketEd
  21840. \section{Interpreters}
  21841. \label{appendix:interp}
  21842. \index{subject}{interpreter}
  21843. We provide interpreters for each of the source languages \LangInt{},
  21844. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21845. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21846. intermediate languages \LangCVar{} and \LangCIf{} are in
  21847. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21848. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21849. \key{interp.rkt} file.
  21850. \section{Utility Functions}
  21851. \label{appendix:utilities}
  21852. The utility functions described in this section are in the
  21853. \key{utilities.rkt} file of the support code.
  21854. \paragraph{\code{interp-tests}}
  21855. This function runs the compiler passes and the interpreters on each of
  21856. the specified tests to check whether each pass is correct. The
  21857. \key{interp-tests} function has the following parameters:
  21858. \begin{description}
  21859. \item[name (a string)] A name to identify the compiler.
  21860. \item[typechecker] A function of exactly one argument that either
  21861. raises an error using the \code{error} function when it encounters a
  21862. type error, or returns \code{\#f} when it encounters a type
  21863. error. If there is no type error, the type checker returns the
  21864. program.
  21865. \item[passes] A list with one entry per pass. An entry is a list
  21866. consisting of four things:
  21867. \begin{enumerate}
  21868. \item a string giving the name of the pass;
  21869. \item the function that implements the pass (a translator from AST
  21870. to AST);
  21871. \item a function that implements the interpreter (a function from
  21872. AST to result value) for the output language; and,
  21873. \item a type checker for the output language. Type checkers for
  21874. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21875. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21876. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21877. type checker entry is optional. The support code does not provide
  21878. type checkers for the x86 languages.
  21879. \end{enumerate}
  21880. \item[source-interp] An interpreter for the source language. The
  21881. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21882. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21883. \item[tests] A list of test numbers that specifies which tests to
  21884. run (explained next).
  21885. \end{description}
  21886. %
  21887. The \key{interp-tests} function assumes that the subdirectory
  21888. \key{tests} has a collection of Racket programs whose names all start
  21889. with the family name, followed by an underscore and then the test
  21890. number, and ending with the file extension \key{.rkt}. Also, for each test
  21891. program that calls \code{read} one or more times, there is a file with
  21892. the same name except that the file extension is \key{.in}, which
  21893. provides the input for the Racket program. If the test program is
  21894. expected to fail type checking, then there should be an empty file of
  21895. the same name with extension \key{.tyerr}.
  21896. \paragraph{\code{compiler-tests}}
  21897. This function runs the compiler passes to generate x86 (a \key{.s}
  21898. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21899. It runs the machine code and checks that the output is $42$. The
  21900. parameters to the \code{compiler-tests} function are similar to those
  21901. of the \code{interp-tests} function, and they consist of
  21902. \begin{itemize}
  21903. \item a compiler name (a string),
  21904. \item a type checker,
  21905. \item description of the passes,
  21906. \item name of a test-family, and
  21907. \item a list of test numbers.
  21908. \end{itemize}
  21909. \paragraph{\code{compile-file}}
  21910. This function takes a description of the compiler passes (see the
  21911. comment for \key{interp-tests}) and returns a function that, given a
  21912. program file name (a string ending in \key{.rkt}), applies all the
  21913. passes and writes the output to a file whose name is the same as the
  21914. program file name with extension \key{.rkt} replaced by \key{.s}.
  21915. \paragraph{\code{read-program}}
  21916. This function takes a file path and parses that file (it must be a
  21917. Racket program) into an abstract syntax tree.
  21918. \paragraph{\code{parse-program}}
  21919. This function takes an S-expression representation of an abstract
  21920. syntax tree and converts it into the struct-based representation.
  21921. \paragraph{\code{assert}}
  21922. This function takes two parameters, a string (\code{msg}) and Boolean
  21923. (\code{bool}), and displays the message \key{msg} if the Boolean
  21924. \key{bool} is false.
  21925. \paragraph{\code{lookup}}
  21926. % remove discussion of lookup? -Jeremy
  21927. This function takes a key and an alist and returns the first value that is
  21928. associated with the given key, if there is one. If not, an error is
  21929. triggered. The alist may contain both immutable pairs (built with
  21930. \key{cons}) and mutable pairs (built with \key{mcons}).
  21931. %The \key{map2} function ...
  21932. \fi} %\racketEd
  21933. \section{x86 Instruction Set Quick Reference}
  21934. \label{sec:x86-quick-reference}
  21935. \index{subject}{x86}
  21936. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21937. do. We write $A \to B$ to mean that the value of $A$ is written into
  21938. location $B$. Address offsets are given in bytes. The instruction
  21939. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21940. registers (such as \code{\%rax}), or memory references (such as
  21941. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21942. reference per instruction. Other operands must be immediates or
  21943. registers.
  21944. \begin{table}[tbp]
  21945. \captionabove{Quick reference for the x86 instructions used in this book.}
  21946. \label{tab:x86-instr}
  21947. \centering
  21948. \begin{tabular}{l|l}
  21949. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21950. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21951. \texttt{negq} $A$ & $- A \to A$ \\
  21952. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21953. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21954. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21955. \texttt{callq} \texttt{*}$A$ & Pushes the return address and jumps to the address in $A$. \\
  21956. \texttt{retq} & Pops the return address and jumps to it. \\
  21957. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21958. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21959. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21960. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21961. & \\
  21962. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21963. matches the condition code of the instruction; otherwise go to the
  21964. next instructions. The condition codes are \key{e} for \emph{equal},
  21965. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21966. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21967. \texttt{jl} $L$ & \\
  21968. \texttt{jle} $L$ & \\
  21969. \texttt{jg} $L$ & \\
  21970. \texttt{jge} $L$ & \\
  21971. \texttt{jmp} $L$ & Jump to label $L$. \\
  21972. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21973. \texttt{movzbq} $A$, $B$ &
  21974. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21975. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21976. and the extra bytes of $B$ are set to zero.} \\
  21977. & \\
  21978. & \\
  21979. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21980. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21981. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21982. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21983. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21984. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21985. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21986. description of the condition codes. $A$ must be a single byte register
  21987. (e.g., \texttt{al} or \texttt{cl}).} \\
  21988. \texttt{setl} $A$ & \\
  21989. \texttt{setle} $A$ & \\
  21990. \texttt{setg} $A$ & \\
  21991. \texttt{setge} $A$ &
  21992. \end{tabular}
  21993. \end{table}
  21994. \backmatter
  21995. \addtocontents{toc}{\vspace{11pt}}
  21996. \cleardoublepage % needed for right page number in TOC for References
  21997. %% \nocite{*} is a way to get all the entries in the .bib file to
  21998. %% print in the bibliography:
  21999. \nocite{*}\let\bibname\refname
  22000. \addcontentsline{toc}{fmbm}{\refname}
  22001. \printbibliography
  22002. %\printindex{authors}{Author Index}
  22003. \printindex{subject}{Index}
  22004. \end{document}
  22005. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  22006. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  22007. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  22008. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  22009. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  22010. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  22011. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  22012. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  22013. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  22014. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  22015. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  22016. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  22017. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  22018. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  22019. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  22020. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  22021. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  22022. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  22023. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  22024. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  22025. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  22026. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  22027. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  22028. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  22029. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  22030. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  22031. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  22032. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  22033. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  22034. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  22035. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  22036. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  22037. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  22038. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  22039. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  22040. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  22041. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  22042. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  22043. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  22044. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  22045. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  22046. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  22047. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  22048. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  22049. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  22050. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  22051. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  22052. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  22053. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  22054. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  22055. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  22056. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  22057. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  22058. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  22059. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  22060. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  22061. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  22062. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  22063. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  22064. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  22065. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  22066. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  22067. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  22068. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  22069. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  22070. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  22071. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  22072. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  22073. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  22074. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  22075. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  22076. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  22077. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  22078. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  22079. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  22080. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  22081. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  22082. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  22083. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  22084. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  22085. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  22086. % LocalWords: pseudocode underapproximation underapproximations LALR
  22087. % LocalWords: semilattices overapproximate incrementing Earley docs
  22088. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  22089. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  22090. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  22091. % LocalWords: LC partialevaluation pythonEd TOC TrappedError