book.tex 824 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. %% For multiple indices:
  35. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  36. \makeindex{subject}
  37. %\makeindex{authors}
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. \if\edition\racketEd
  40. \lstset{%
  41. language=Lisp,
  42. basicstyle=\ttfamily\small,
  43. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  44. deletekeywords={read,mapping,vector},
  45. escapechar=|,
  46. columns=flexible,
  47. %moredelim=[is][\color{red}]{~}{~},
  48. showstringspaces=false
  49. }
  50. \fi
  51. \if\edition\pythonEd
  52. \lstset{%
  53. language=Python,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={match,case,bool,int,let},
  56. deletekeywords={},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. %%% Any shortcut own defined macros place here
  64. %% sample of author macro:
  65. \input{defs}
  66. \newtheorem{exercise}[theorem]{Exercise}
  67. \numberwithin{theorem}{chapter}
  68. \numberwithin{definition}{chapter}
  69. \numberwithin{equation}{chapter}
  70. % Adjusted settings
  71. \setlength{\columnsep}{4pt}
  72. %% \begingroup
  73. %% \setlength{\intextsep}{0pt}%
  74. %% \setlength{\columnsep}{0pt}%
  75. %% \begin{wrapfigure}{r}{0.5\textwidth}
  76. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  77. %% \caption{Basic layout}
  78. %% \end{wrapfigure}
  79. %% \lipsum[1]
  80. %% \endgroup
  81. \newbox\oiintbox
  82. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  83. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  84. \def\oiint{\copy\oiintbox}
  85. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  86. %\usepackage{showframe}
  87. \def\ShowFrameLinethickness{0.125pt}
  88. \addbibresource{book.bib}
  89. \if\edition\pythonEd
  90. \addbibresource{python.bib}
  91. \fi
  92. \begin{document}
  93. \frontmatter
  94. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  95. \HalfTitle{Essentials of Compilation}
  96. \halftitlepage
  97. \clearemptydoublepage
  98. \Title{Essentials of Compilation}
  99. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  100. %\edition{First Edition}
  101. \BookAuthor{Jeremy G. Siek}
  102. \imprint{The MIT Press\\
  103. Cambridge, Massachusetts\\
  104. London, England}
  105. \begin{copyrightpage}
  106. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  107. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  108. Subject to such license, all rights are reserved. \\[2ex]
  109. \includegraphics{CCBY-logo}
  110. The MIT Press would like to thank the anonymous peer reviewers who
  111. provided comments on drafts of this book. The generous work of
  112. academic experts is essential for establishing the authority and
  113. quality of our publications. We acknowledge with gratitude the
  114. contributions of these otherwise uncredited readers.
  115. This book was set in Times LT Std Roman by the author. Printed and
  116. bound in the United States of America.
  117. Library of Congress Cataloging-in-Publication Data is available.
  118. ISBN:
  119. 10 9 8 7 6 5 4 3 2 1
  120. %% Jeremy G. Siek. Available for free viewing
  121. %% or personal downloading under the
  122. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  123. %% license.
  124. %% Copyright in this monograph has been licensed exclusively to The MIT
  125. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  126. %% version to the public in 2022. All inquiries regarding rights should
  127. %% be addressed to The MIT Press, Rights and Permissions Department.
  128. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  129. %% All rights reserved. No part of this book may be reproduced in any
  130. %% form by any electronic or mechanical means (including photocopying,
  131. %% recording, or information storage and retrieval) without permission in
  132. %% writing from the publisher.
  133. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  134. %% United States of America.
  135. %% Library of Congress Cataloging-in-Publication Data is available.
  136. %% ISBN:
  137. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  138. \end{copyrightpage}
  139. \dedication{This book is dedicated to Katie, my partner in everything,
  140. my children, who grew up during the writing of this book, and the
  141. programming language students at Indiana University, whose
  142. thoughtful questions made this a better book.}
  143. %% \begin{epigraphpage}
  144. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  145. %% \textit{Book Name if any}}
  146. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  147. %% \end{epigraphpage}
  148. \tableofcontents
  149. %\listoffigures
  150. %\listoftables
  151. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  152. \chapter*{Preface}
  153. \addcontentsline{toc}{fmbm}{Preface}
  154. There is a magical moment when a programmer presses the run button
  155. and the software begins to execute. Somehow a program written in a
  156. high-level language is running on a computer that is capable only of
  157. shuffling bits. Here we reveal the wizardry that makes that moment
  158. possible. Beginning with the groundbreaking work of Backus and
  159. colleagues in the 1950s, computer scientists developed techniques for
  160. constructing programs called \emph{compilers} that automatically
  161. translate high-level programs into machine code.
  162. We take you on a journey through constructing your own compiler for a
  163. small but powerful language. Along the way we explain the essential
  164. concepts, algorithms, and data structures that underlie compilers. We
  165. develop your understanding of how programs are mapped onto computer
  166. hardware, which is helpful in reasoning about properties at the
  167. junction of hardware and software, such as execution time, software
  168. errors, and security vulnerabilities. For those interested in
  169. pursuing compiler construction as a career, our goal is to provide a
  170. stepping-stone to advanced topics such as just-in-time compilation,
  171. program analysis, and program optimization. For those interested in
  172. designing and implementing programming languages, we connect language
  173. design choices to their impact on the compiler and the generated code.
  174. A compiler is typically organized as a sequence of stages that
  175. progressively translate a program to the code that runs on
  176. hardware. We take this approach to the extreme by partitioning our
  177. compiler into a large number of \emph{nanopasses}, each of which
  178. performs a single task. This enables the testing of each pass in
  179. isolation and focuses our attention, making the compiler far easier to
  180. understand.
  181. The most familiar approach to describing compilers is to dedicate each
  182. chapter to one pass. The problem with that approach is that it
  183. obfuscates how language features motivate design choices in a
  184. compiler. We instead take an \emph{incremental} approach in which we
  185. build a complete compiler in each chapter, starting with a small input
  186. language that includes only arithmetic and variables. We add new
  187. language features in subsequent chapters, extending the compiler as
  188. necessary.
  189. Our choice of language features is designed to elicit fundamental
  190. concepts and algorithms used in compilers.
  191. \begin{itemize}
  192. \item We begin with integer arithmetic and local variables in
  193. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  194. the fundamental tools of compiler construction: \emph{abstract
  195. syntax trees} and \emph{recursive functions}.
  196. {\if\edition\pythonEd\pythonColor
  197. \item In Chapter~\ref{ch:parsing} we learn how to use the Lark
  198. parser framework to create a parser for the language of integer
  199. arithmetic and local variables. We learn about the parsing
  200. algorithms inside Lark, including Earley and LALR(1).
  201. %
  202. \fi}
  203. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  204. \emph{graph coloring} to assign variables to machine registers.
  205. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  206. motivates an elegant recursive algorithm for translating them into
  207. conditional \code{goto} statements.
  208. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  209. variables}. This elicits the need for \emph{dataflow
  210. analysis} in the register allocator.
  211. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  212. \emph{garbage collection}.
  213. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  214. without lexical scoping, similar to functions in the C programming
  215. language~\citep{Kernighan:1988nx}. The reader learns about the
  216. procedure call stack and \emph{calling conventions} and how they interact
  217. with register allocation and garbage collection. The chapter also
  218. describes how to generate efficient tail calls.
  219. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  220. scoping, that is, \emph{lambda} expressions. The reader learns about
  221. \emph{closure conversion}, in which lambdas are translated into a
  222. combination of functions and tuples.
  223. % Chapter about classes and objects?
  224. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  225. point the input languages are statically typed. The reader extends
  226. the statically typed language with an \code{Any} type that serves
  227. as a target for compiling the dynamically typed language.
  228. %% {\if\edition\pythonEd\pythonColor
  229. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  230. %% \emph{classes}.
  231. %% \fi}
  232. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  233. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  234. in which different regions of a program may be static or dynamically
  235. typed. The reader implements runtime support for \emph{proxies} that
  236. allow values to safely move between regions.
  237. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  238. leveraging the \code{Any} type and type casts developed in chapters
  239. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  240. \end{itemize}
  241. There are many language features that we do not include. Our choices
  242. balance the incidental complexity of a feature versus the fundamental
  243. concepts that it exposes. For example, we include tuples and not
  244. records because although they both elicit the study of heap allocation and
  245. garbage collection, records come with more incidental complexity.
  246. Since 2009, drafts of this book have served as the textbook for
  247. sixteen week compiler courses for upper-level undergraduates and
  248. first-year graduate students at the University of Colorado and Indiana
  249. University.
  250. %
  251. Students come into the course having learned the basics of
  252. programming, data structures and algorithms, and discrete
  253. mathematics.
  254. %
  255. At the beginning of the course, students form groups of two to four
  256. people. The groups complete approximately one chapter every two
  257. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  258. according to the students interests while respecting the dependencies
  259. between chapters shown in
  260. Figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  261. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  262. implementation of efficient tail calls.
  263. %
  264. The last two weeks of the course involve a final project in which
  265. students design and implement a compiler extension of their choosing.
  266. The last few chapters can be used in support of these projects. Many
  267. chapters include a challenge problem that we assign to the graduate
  268. students. For compiler courses at universities on the quarter system
  269. (about ten weeks in length), we recommend completing the course
  270. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  271. some scaffolding code to the students for each compiler pass.
  272. %
  273. The course can be adapted to emphasize functional languages by
  274. skipping chapter~\ref{ch:Lwhile} (loops) and including
  275. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  276. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  277. %
  278. %% \python{A course that emphasizes object-oriented languages would
  279. %% include Chapter~\ref{ch:Lobject}.}
  280. This book has been used in compiler courses at California Polytechnic
  281. State University, Portland State University, Rose–Hulman Institute of
  282. Technology, University of Freiburg, University of Massachusetts
  283. Lowell, and the University of Vermont.
  284. \begin{figure}[tp]
  285. \begin{tcolorbox}[colback=white]
  286. {\if\edition\racketEd
  287. \begin{tikzpicture}[baseline=(current bounding box.center)]
  288. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  289. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  290. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  291. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  292. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  293. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  294. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  295. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  296. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  297. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  298. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  299. \path[->] (C1) edge [above] node {} (C2);
  300. \path[->] (C2) edge [above] node {} (C3);
  301. \path[->] (C3) edge [above] node {} (C4);
  302. \path[->] (C4) edge [above] node {} (C5);
  303. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  304. \path[->] (C5) edge [above] node {} (C7);
  305. \path[->] (C6) edge [above] node {} (C7);
  306. \path[->] (C4) edge [above] node {} (C8);
  307. \path[->] (C4) edge [above] node {} (C9);
  308. \path[->] (C7) edge [above] node {} (C10);
  309. \path[->] (C8) edge [above] node {} (C10);
  310. \path[->] (C10) edge [above] node {} (C11);
  311. \end{tikzpicture}
  312. \fi}
  313. {\if\edition\pythonEd\pythonColor
  314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  315. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  316. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  317. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  318. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  319. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  320. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  321. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  322. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  323. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  324. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  325. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  326. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  327. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  328. \path[->] (Prelim) edge [above] node {} (Var);
  329. \path[->] (Var) edge [above] node {} (Reg);
  330. \path[->] (Var) edge [above] node {} (Parse);
  331. \path[->] (Reg) edge [above] node {} (Cond);
  332. \path[->] (Cond) edge [above] node {} (Tuple);
  333. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  334. \path[->] (Cond) edge [above] node {} (Fun);
  335. \path[->] (Tuple) edge [above] node {} (Lam);
  336. \path[->] (Fun) edge [above] node {} (Lam);
  337. \path[->] (Cond) edge [above] node {} (Dyn);
  338. \path[->] (Cond) edge [above] node {} (Loop);
  339. \path[->] (Lam) edge [above] node {} (Gradual);
  340. \path[->] (Dyn) edge [above] node {} (Gradual);
  341. % \path[->] (Dyn) edge [above] node {} (CO);
  342. \path[->] (Gradual) edge [above] node {} (Generic);
  343. \end{tikzpicture}
  344. \fi}
  345. \end{tcolorbox}
  346. \caption{Diagram of chapter dependencies.}
  347. \label{fig:chapter-dependences}
  348. \end{figure}
  349. \racket{
  350. We use the \href{https://racket-lang.org/}{Racket} language both for
  351. the implementation of the compiler and for the input language, so the
  352. reader should be proficient with Racket or Scheme. There are many
  353. excellent resources for learning Scheme and
  354. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  355. }
  356. \python{
  357. This edition of the book uses \href{https://www.python.org/}{Python}
  358. both for the implementation of the compiler and for the input language, so the
  359. reader should be proficient with Python. There are many
  360. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  361. }
  362. The support code for this book is in the GitHub repository at
  363. the following location:
  364. \begin{center}\small\texttt
  365. https://github.com/IUCompilerCourse/
  366. \end{center}
  367. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  368. is helpful but not necessary for the reader to have taken a computer
  369. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  370. assembly language that are needed in the compiler.
  371. %
  372. We follow the System V calling
  373. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  374. that we generate works with the runtime system (written in C) when it
  375. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  376. operating systems on Intel hardware.
  377. %
  378. On the Windows operating system, \code{gcc} uses the Microsoft x64
  379. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  380. assembly code that we generate does \emph{not} work with the runtime
  381. system on Windows. One workaround is to use a virtual machine with
  382. Linux as the guest operating system.
  383. \section*{Acknowledgments}
  384. The tradition of compiler construction at Indiana University goes back
  385. to research and courses on programming languages by Daniel Friedman in
  386. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  387. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  388. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  389. the compiler course and continued the development of Chez Scheme.
  390. %
  391. The compiler course evolved to incorporate novel pedagogical ideas
  392. while also including elements of real-world compilers. One of
  393. Friedman's ideas was to split the compiler into many small
  394. passes. Another idea, called ``the game,'' was to test the code
  395. generated by each pass using interpreters.
  396. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  397. developed infrastructure to support this approach and evolved the
  398. course to use even smaller
  399. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  400. design decisions in this book are inspired by the assignment
  401. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  402. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  403. organization of the course made it difficult for students to
  404. understand the rationale for the compiler design. Ghuloum proposed the
  405. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  406. based.
  407. We thank the many students who served as teaching assistants for the
  408. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  409. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  410. garbage collector and x86 interpreter, Michael Vollmer for work on
  411. efficient tail calls, and Michael Vitousek for help with the first
  412. offering of the incremental compiler course at IU.
  413. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  414. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  415. Michael Wollowski for teaching courses based on drafts of this book
  416. and for their feedback. We thank the National Science Foundation for
  417. the grants that helped to support this work: Grant Numbers 1518844,
  418. 1763922, and 1814460.
  419. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  420. course in the early 2000s and especially for finding the bug that
  421. sent our garbage collector on a wild goose chase!
  422. \mbox{}\\
  423. \noindent Jeremy G. Siek \\
  424. Bloomington, Indiana
  425. \mainmatter
  426. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  427. \chapter{Preliminaries}
  428. \label{ch:trees-recur}
  429. \setcounter{footnote}{0}
  430. In this chapter we review the basic tools needed to implement a
  431. compiler. Programs are typically input by a programmer as text, that
  432. is, a sequence of characters. The program-as-text representation is
  433. called \emph{concrete syntax}. We use concrete syntax to concisely
  434. write down and talk about programs. Inside the compiler, we use
  435. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  436. that efficiently supports the operations that the compiler needs to
  437. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  438. syntax}\index{subject}{abstract syntax
  439. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  440. The process of translating from concrete syntax to abstract syntax is
  441. called \emph{parsing}\python{\ and is studied in
  442. chapter~\ref{ch:parsing}}.
  443. \racket{This book does not cover the theory and implementation of parsing.
  444. We refer the readers interested in parsing to the thorough treatment
  445. of parsing by \citet{Aho:2006wb}.}%
  446. %
  447. \racket{A parser is provided in the support code for translating from
  448. concrete to abstract syntax.}%
  449. %
  450. \python{For now we use Python's \code{ast} module to translate from concrete
  451. to abstract syntax.}
  452. ASTs can be represented inside the compiler in many different ways,
  453. depending on the programming language used to write the compiler.
  454. %
  455. \racket{We use Racket's
  456. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  457. feature to represent ASTs (section~\ref{sec:ast}).}
  458. %
  459. \python{We use Python classes and objects to represent ASTs, especially the
  460. classes defined in the standard \code{ast} module for the Python
  461. source language.}
  462. %
  463. We use grammars to define the abstract syntax of programming languages
  464. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  465. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  466. recursive functions to construct and deconstruct ASTs
  467. (section~\ref{sec:recursion}). This chapter provides a brief
  468. introduction to these components.
  469. \racket{\index{subject}{struct}}
  470. \python{\index{subject}{class}\index{subject}{object}}
  471. \section{Abstract Syntax Trees}
  472. \label{sec:ast}
  473. Compilers use abstract syntax trees to represent programs because they
  474. often need to ask questions such as, for a given part of a program,
  475. what kind of language feature is it? What are its subparts? Consider
  476. the program on the left and the diagram of its AST on the
  477. right~\eqref{eq:arith-prog}. This program is an addition operation
  478. that has two subparts, a \racket{read}\python{input} operation and a
  479. negation. The negation has another subpart, the integer constant
  480. \code{8}. By using a tree to represent the program, we can easily
  481. follow the links to go from one part of a program to its subparts.
  482. \begin{center}
  483. \begin{minipage}{0.4\textwidth}
  484. {\if\edition\racketEd
  485. \begin{lstlisting}
  486. (+ (read) (- 8))
  487. \end{lstlisting}
  488. \fi}
  489. {\if\edition\pythonEd\pythonColor
  490. \begin{lstlisting}
  491. input_int() + -8
  492. \end{lstlisting}
  493. \fi}
  494. \end{minipage}
  495. \begin{minipage}{0.4\textwidth}
  496. \begin{equation}
  497. \begin{tikzpicture}
  498. \node[draw] (plus) at (0 , 0) {\key{+}};
  499. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  500. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  501. \node[draw] (8) at (1 , -2) {\key{8}};
  502. \draw[->] (plus) to (read);
  503. \draw[->] (plus) to (minus);
  504. \draw[->] (minus) to (8);
  505. \end{tikzpicture}
  506. \label{eq:arith-prog}
  507. \end{equation}
  508. \end{minipage}
  509. \end{center}
  510. We use the standard terminology for trees to describe ASTs: each
  511. rectangle above is called a \emph{node}. The arrows connect a node to its
  512. \emph{children}, which are also nodes. The top-most node is the
  513. \emph{root}. Every node except for the root has a \emph{parent} (the
  514. node of which it is the child). If a node has no children, it is a
  515. \emph{leaf} node; otherwise it is an \emph{internal} node.
  516. \index{subject}{node}
  517. \index{subject}{children}
  518. \index{subject}{root}
  519. \index{subject}{parent}
  520. \index{subject}{leaf}
  521. \index{subject}{internal node}
  522. %% Recall that an \emph{symbolic expression} (S-expression) is either
  523. %% \begin{enumerate}
  524. %% \item an atom, or
  525. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  526. %% where $e_1$ and $e_2$ are each an S-expression.
  527. %% \end{enumerate}
  528. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  529. %% null value \code{'()}, etc. We can create an S-expression in Racket
  530. %% simply by writing a backquote (called a quasi-quote in Racket)
  531. %% followed by the textual representation of the S-expression. It is
  532. %% quite common to use S-expressions to represent a list, such as $a, b
  533. %% ,c$ in the following way:
  534. %% \begin{lstlisting}
  535. %% `(a . (b . (c . ())))
  536. %% \end{lstlisting}
  537. %% Each element of the list is in the first slot of a pair, and the
  538. %% second slot is either the rest of the list or the null value, to mark
  539. %% the end of the list. Such lists are so common that Racket provides
  540. %% special notation for them that removes the need for the periods
  541. %% and so many parenthesis:
  542. %% \begin{lstlisting}
  543. %% `(a b c)
  544. %% \end{lstlisting}
  545. %% The following expression creates an S-expression that represents AST
  546. %% \eqref{eq:arith-prog}.
  547. %% \begin{lstlisting}
  548. %% `(+ (read) (- 8))
  549. %% \end{lstlisting}
  550. %% When using S-expressions to represent ASTs, the convention is to
  551. %% represent each AST node as a list and to put the operation symbol at
  552. %% the front of the list. The rest of the list contains the children. So
  553. %% in the above case, the root AST node has operation \code{`+} and its
  554. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  555. %% diagram \eqref{eq:arith-prog}.
  556. %% To build larger S-expressions one often needs to splice together
  557. %% several smaller S-expressions. Racket provides the comma operator to
  558. %% splice an S-expression into a larger one. For example, instead of
  559. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  560. %% we could have first created an S-expression for AST
  561. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  562. %% S-expression.
  563. %% \begin{lstlisting}
  564. %% (define ast1.4 `(- 8))
  565. %% (define ast1_1 `(+ (read) ,ast1.4))
  566. %% \end{lstlisting}
  567. %% In general, the Racket expression that follows the comma (splice)
  568. %% can be any expression that produces an S-expression.
  569. {\if\edition\racketEd
  570. We define a Racket \code{struct} for each kind of node. For this
  571. chapter we require just two kinds of nodes: one for integer constants
  572. and one for primitive operations. The following is the \code{struct}
  573. definition for integer constants.\footnote{All the AST structures are
  574. defined in the file \code{utilities.rkt} in the support code.}
  575. \begin{lstlisting}
  576. (struct Int (value))
  577. \end{lstlisting}
  578. An integer node contains just one thing: the integer value.
  579. We establish the convention that \code{struct} names, such
  580. as \code{Int}, are capitalized.
  581. To create an AST node for the integer $8$, we write \INT{8}.
  582. \begin{lstlisting}
  583. (define eight (Int 8))
  584. \end{lstlisting}
  585. We say that the value created by \INT{8} is an
  586. \emph{instance} of the
  587. \code{Int} structure.
  588. The following is the \code{struct} definition for primitive operations.
  589. \begin{lstlisting}
  590. (struct Prim (op args))
  591. \end{lstlisting}
  592. A primitive operation node includes an operator symbol \code{op} and a
  593. list of child arguments called \code{args}. For example, to create an
  594. AST that negates the number $8$, we write the following.
  595. \begin{lstlisting}
  596. (define neg-eight (Prim '- (list eight)))
  597. \end{lstlisting}
  598. Primitive operations may have zero or more children. The \code{read}
  599. operator has zero:
  600. \begin{lstlisting}
  601. (define rd (Prim 'read '()))
  602. \end{lstlisting}
  603. The addition operator has two children:
  604. \begin{lstlisting}
  605. (define ast1_1 (Prim '+ (list rd neg-eight)))
  606. \end{lstlisting}
  607. We have made a design choice regarding the \code{Prim} structure.
  608. Instead of using one structure for many different operations
  609. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  610. structure for each operation, as follows:
  611. \begin{lstlisting}
  612. (struct Read ())
  613. (struct Add (left right))
  614. (struct Neg (value))
  615. \end{lstlisting}
  616. The reason that we choose to use just one structure is that many parts
  617. of the compiler can use the same code for the different primitive
  618. operators, so we might as well just write that code once by using a
  619. single structure.
  620. %
  621. \fi}
  622. {\if\edition\pythonEd\pythonColor
  623. We use a Python \code{class} for each kind of node.
  624. The following is the class definition for
  625. constants from the Python \code{ast} module.
  626. \begin{lstlisting}
  627. class Constant:
  628. def __init__(self, value):
  629. self.value = value
  630. \end{lstlisting}
  631. An integer constant node includes just one thing: the integer value.
  632. To create an AST node for the integer $8$, we write \INT{8}.
  633. \begin{lstlisting}
  634. eight = Constant(8)
  635. \end{lstlisting}
  636. We say that the value created by \INT{8} is an
  637. \emph{instance} of the \code{Constant} class.
  638. The following is the class definition for unary operators.
  639. \begin{lstlisting}
  640. class UnaryOp:
  641. def __init__(self, op, operand):
  642. self.op = op
  643. self.operand = operand
  644. \end{lstlisting}
  645. The specific operation is specified by the \code{op} parameter. For
  646. example, the class \code{USub} is for unary subtraction.
  647. (More unary operators are introduced in later chapters.) To create an AST that
  648. negates the number $8$, we write the following.
  649. \begin{lstlisting}
  650. neg_eight = UnaryOp(USub(), eight)
  651. \end{lstlisting}
  652. The call to the \code{input\_int} function is represented by the
  653. \code{Call} and \code{Name} classes.
  654. \begin{lstlisting}
  655. class Call:
  656. def __init__(self, func, args):
  657. self.func = func
  658. self.args = args
  659. class Name:
  660. def __init__(self, id):
  661. self.id = id
  662. \end{lstlisting}
  663. To create an AST node that calls \code{input\_int}, we write
  664. \begin{lstlisting}
  665. read = Call(Name('input_int'), [])
  666. \end{lstlisting}
  667. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  668. the \code{BinOp} class for binary operators.
  669. \begin{lstlisting}
  670. class BinOp:
  671. def __init__(self, left, op, right):
  672. self.op = op
  673. self.left = left
  674. self.right = right
  675. \end{lstlisting}
  676. Similar to \code{UnaryOp}, the specific operation is specified by the
  677. \code{op} parameter, which for now is just an instance of the
  678. \code{Add} class. So to create the AST
  679. node that adds negative eight to some user input, we write the following.
  680. \begin{lstlisting}
  681. ast1_1 = BinOp(read, Add(), neg_eight)
  682. \end{lstlisting}
  683. \fi}
  684. To compile a program such as \eqref{eq:arith-prog}, we need to know
  685. that the operation associated with the root node is addition and we
  686. need to be able to access its two
  687. children. \racket{Racket}\python{Python} provides pattern matching to
  688. support these kinds of queries, as we see in
  689. section~\ref{sec:pattern-matching}.
  690. We often write down the concrete syntax of a program even when we
  691. actually have in mind the AST, because the concrete syntax is more
  692. concise. We recommend that you always think of programs as abstract
  693. syntax trees.
  694. \section{Grammars}
  695. \label{sec:grammar}
  696. \index{subject}{integer}
  697. \index{subject}{literal}
  698. %\index{subject}{constant}
  699. A programming language can be thought of as a \emph{set} of programs.
  700. The set is infinite (that is, one can always create larger programs),
  701. so one cannot simply describe a language by listing all the
  702. programs in the language. Instead we write down a set of rules, a
  703. \emph{context-free grammar}, for building programs. Grammars are often used to
  704. define the concrete syntax of a language, but they can also be used to
  705. describe the abstract syntax. We write our rules in a variant of
  706. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  707. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  708. we describe a small language, named \LangInt{}, that consists of
  709. integers and arithmetic operations.\index{subject}{grammar}
  710. \index{subject}{context-free grammar}
  711. The first grammar rule for the abstract syntax of \LangInt{} says that an
  712. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  713. \begin{equation}
  714. \Exp ::= \INT{\Int} \label{eq:arith-int}
  715. \end{equation}
  716. %
  717. Each rule has a left-hand side and a right-hand side.
  718. If you have an AST node that matches the
  719. right-hand side, then you can categorize it according to the
  720. left-hand side.
  721. %
  722. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  723. are \emph{terminal} symbols and must literally appear in the program for the
  724. rule to be applicable.\index{subject}{terminal}
  725. %
  726. Our grammars do not mention \emph{white space}, that is, delimiter
  727. characters like spaces, tabs, and new lines. White space may be
  728. inserted between symbols for disambiguation and to improve
  729. readability. \index{subject}{white space}
  730. %
  731. A name such as $\Exp$ that is defined by the grammar rules is a
  732. \emph{nonterminal}. \index{subject}{nonterminal}
  733. %
  734. The name $\Int$ is also a nonterminal, but instead of defining it with
  735. a grammar rule, we define it with the following explanation. An
  736. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  737. $-$ (for negative integers), such that the sequence of decimals
  738. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  739. enables the representation of integers using 63 bits, which simplifies
  740. several aspects of compilation.
  741. %
  742. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  743. datatype on a 64-bit machine.}
  744. %
  745. \python{In contrast, integers in Python have unlimited precision, but
  746. the techniques needed to handle unlimited precision fall outside the
  747. scope of this book.}
  748. The second grammar rule is the \READOP{} operation, which receives an
  749. input integer from the user of the program.
  750. \begin{equation}
  751. \Exp ::= \READ{} \label{eq:arith-read}
  752. \end{equation}
  753. The third rule categorizes the negation of an $\Exp$ node as an
  754. $\Exp$.
  755. \begin{equation}
  756. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  757. \end{equation}
  758. We can apply these rules to categorize the ASTs that are in the
  759. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  760. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  761. following AST is an $\Exp$.
  762. \begin{center}
  763. \begin{minipage}{0.5\textwidth}
  764. \NEG{\INT{\code{8}}}
  765. \end{minipage}
  766. \begin{minipage}{0.25\textwidth}
  767. \begin{equation}
  768. \begin{tikzpicture}
  769. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  770. \node[draw, circle] (8) at (0, -1.2) {$8$};
  771. \draw[->] (minus) to (8);
  772. \end{tikzpicture}
  773. \label{eq:arith-neg8}
  774. \end{equation}
  775. \end{minipage}
  776. \end{center}
  777. The next two grammar rules are for addition and subtraction expressions:
  778. \begin{align}
  779. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  780. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  781. \end{align}
  782. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  783. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  784. \eqref{eq:arith-read}, and we have already categorized
  785. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  786. to show that
  787. \[
  788. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  789. \]
  790. is an $\Exp$ in the \LangInt{} language.
  791. If you have an AST for which these rules do not apply, then the
  792. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  793. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  794. because there is no rule for the \key{*} operator. Whenever we
  795. define a language with a grammar, the language includes only those
  796. programs that are justified by the grammar rules.
  797. {\if\edition\pythonEd\pythonColor
  798. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  799. There is a statement for printing the value of an expression
  800. \[
  801. \Stmt{} ::= \PRINT{\Exp}
  802. \]
  803. and a statement that evaluates an expression but ignores the result.
  804. \[
  805. \Stmt{} ::= \EXPR{\Exp}
  806. \]
  807. \fi}
  808. {\if\edition\racketEd
  809. The last grammar rule for \LangInt{} states that there is a
  810. \code{Program} node to mark the top of the whole program:
  811. \[
  812. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  813. \]
  814. The \code{Program} structure is defined as follows:
  815. \begin{lstlisting}
  816. (struct Program (info body))
  817. \end{lstlisting}
  818. where \code{body} is an expression. In further chapters, the \code{info}
  819. part is used to store auxiliary information, but for now it is
  820. just the empty list.
  821. \fi}
  822. {\if\edition\pythonEd\pythonColor
  823. The last grammar rule for \LangInt{} states that there is a
  824. \code{Module} node to mark the top of the whole program:
  825. \[
  826. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  827. \]
  828. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  829. this case, a list of statements.
  830. %
  831. The \code{Module} class is defined as follows
  832. \begin{lstlisting}
  833. class Module:
  834. def __init__(self, body):
  835. self.body = body
  836. \end{lstlisting}
  837. where \code{body} is a list of statements.
  838. \fi}
  839. It is common to have many grammar rules with the same left-hand side
  840. but different right-hand sides, such as the rules for $\Exp$ in the
  841. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  842. combine several right-hand sides into a single rule.
  843. The concrete syntax for \LangInt{} is shown in
  844. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  845. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  846. %
  847. \racket{The \code{read-program} function provided in
  848. \code{utilities.rkt} of the support code reads a program from a file
  849. (the sequence of characters in the concrete syntax of Racket) and
  850. parses it into an abstract syntax tree. Refer to the description of
  851. \code{read-program} in appendix~\ref{appendix:utilities} for more
  852. details.}
  853. %
  854. \python{The \code{parse} function in Python's \code{ast} module
  855. converts the concrete syntax (represented as a string) into an
  856. abstract syntax tree.}
  857. \newcommand{\LintGrammarRacket}{
  858. \begin{array}{rcl}
  859. \Type &::=& \key{Integer} \\
  860. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  861. \MID \CSUB{\Exp}{\Exp}
  862. \end{array}
  863. }
  864. \newcommand{\LintASTRacket}{
  865. \begin{array}{rcl}
  866. \Type &::=& \key{Integer} \\
  867. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  868. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  869. \end{array}
  870. }
  871. \newcommand{\LintGrammarPython}{
  872. \begin{array}{rcl}
  873. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  874. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  875. \end{array}
  876. }
  877. \newcommand{\LintASTPython}{
  878. \begin{array}{rcl}
  879. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  880. \itm{unaryop} &::= & \code{USub()} \\
  881. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  882. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  883. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  884. \end{array}
  885. }
  886. \begin{figure}[tp]
  887. \begin{tcolorbox}[colback=white]
  888. {\if\edition\racketEd
  889. \[
  890. \begin{array}{l}
  891. \LintGrammarRacket \\
  892. \begin{array}{rcl}
  893. \LangInt{} &::=& \Exp
  894. \end{array}
  895. \end{array}
  896. \]
  897. \fi}
  898. {\if\edition\pythonEd\pythonColor
  899. \[
  900. \begin{array}{l}
  901. \LintGrammarPython \\
  902. \begin{array}{rcl}
  903. \LangInt{} &::=& \Stmt^{*}
  904. \end{array}
  905. \end{array}
  906. \]
  907. \fi}
  908. \end{tcolorbox}
  909. \caption{The concrete syntax of \LangInt{}.}
  910. \label{fig:r0-concrete-syntax}
  911. \end{figure}
  912. \begin{figure}[tp]
  913. \begin{tcolorbox}[colback=white]
  914. {\if\edition\racketEd
  915. \[
  916. \begin{array}{l}
  917. \LintASTRacket{} \\
  918. \begin{array}{rcl}
  919. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  920. \end{array}
  921. \end{array}
  922. \]
  923. \fi}
  924. {\if\edition\pythonEd\pythonColor
  925. \[
  926. \begin{array}{l}
  927. \LintASTPython\\
  928. \begin{array}{rcl}
  929. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  930. \end{array}
  931. \end{array}
  932. \]
  933. \fi}
  934. \end{tcolorbox}
  935. \python{
  936. \index{subject}{Constant@\texttt{Constant}}
  937. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  938. \index{subject}{USub@\texttt{USub}}
  939. \index{subject}{inputint@\texttt{input\_int}}
  940. \index{subject}{Call@\texttt{Call}}
  941. \index{subject}{Name@\texttt{Name}}
  942. \index{subject}{BinOp@\texttt{BinOp}}
  943. \index{subject}{Add@\texttt{Add}}
  944. \index{subject}{Sub@\texttt{Sub}}
  945. \index{subject}{print@\texttt{print}}
  946. \index{subject}{Expr@\texttt{Expr}}
  947. \index{subject}{Module@\texttt{Module}}
  948. }
  949. \caption{The abstract syntax of \LangInt{}.}
  950. \label{fig:r0-syntax}
  951. \end{figure}
  952. \section{Pattern Matching}
  953. \label{sec:pattern-matching}
  954. As mentioned in section~\ref{sec:ast}, compilers often need to access
  955. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  956. provides the \texttt{match} feature to access the parts of a value.
  957. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  958. \begin{center}
  959. \begin{minipage}{0.5\textwidth}
  960. {\if\edition\racketEd
  961. \begin{lstlisting}
  962. (match ast1_1
  963. [(Prim op (list child1 child2))
  964. (print op)])
  965. \end{lstlisting}
  966. \fi}
  967. {\if\edition\pythonEd\pythonColor
  968. \begin{lstlisting}
  969. match ast1_1:
  970. case BinOp(child1, op, child2):
  971. print(op)
  972. \end{lstlisting}
  973. \fi}
  974. \end{minipage}
  975. \end{center}
  976. {\if\edition\racketEd
  977. %
  978. In this example, the \texttt{match} form checks whether the AST
  979. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  980. three pattern variables \texttt{op}, \texttt{child1}, and
  981. \texttt{child2}. In general, a match clause consists of a
  982. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  983. recursively defined to be a pattern variable, a structure name
  984. followed by a pattern for each of the structure's arguments, or an
  985. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  986. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  987. and chapter 9 of The Racket
  988. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  989. for complete descriptions of \code{match}.)
  990. %
  991. The body of a match clause may contain arbitrary Racket code. The
  992. pattern variables can be used in the scope of the body, such as
  993. \code{op} in \code{(print op)}.
  994. %
  995. \fi}
  996. %
  997. %
  998. {\if\edition\pythonEd\pythonColor
  999. %
  1000. In the above example, the \texttt{match} form checks whether the AST
  1001. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1002. three pattern variables \texttt{child1}, \texttt{op}, and
  1003. \texttt{child2}, and then prints out the operator. In general, each
  1004. \code{case} consists of a \emph{pattern} and a
  1005. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  1006. to be either a pattern variable, a class name followed by a pattern
  1007. for each of its constructor's arguments, or other literals such as
  1008. strings, lists, etc.
  1009. %
  1010. The body of each \code{case} may contain arbitrary Python code. The
  1011. pattern variables can be used in the body, such as \code{op} in
  1012. \code{print(op)}.
  1013. %
  1014. \fi}
  1015. A \code{match} form may contain several clauses, as in the following
  1016. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1017. the AST. The \code{match} proceeds through the clauses in order,
  1018. checking whether the pattern can match the input AST. The body of the
  1019. first clause that matches is executed. The output of \code{leaf} for
  1020. several ASTs is shown on the right side of the following:
  1021. \begin{center}
  1022. \begin{minipage}{0.6\textwidth}
  1023. {\if\edition\racketEd
  1024. \begin{lstlisting}
  1025. (define (leaf arith)
  1026. (match arith
  1027. [(Int n) #t]
  1028. [(Prim 'read '()) #t]
  1029. [(Prim '- (list e1)) #f]
  1030. [(Prim '+ (list e1 e2)) #f]
  1031. [(Prim '- (list e1 e2)) #f]))
  1032. (leaf (Prim 'read '()))
  1033. (leaf (Prim '- (list (Int 8))))
  1034. (leaf (Int 8))
  1035. \end{lstlisting}
  1036. \fi}
  1037. {\if\edition\pythonEd\pythonColor
  1038. \begin{lstlisting}
  1039. def leaf(arith):
  1040. match arith:
  1041. case Constant(n):
  1042. return True
  1043. case Call(Name('input_int'), []):
  1044. return True
  1045. case UnaryOp(USub(), e1):
  1046. return False
  1047. case BinOp(e1, Add(), e2):
  1048. return False
  1049. case BinOp(e1, Sub(), e2):
  1050. return False
  1051. print(leaf(Call(Name('input_int'), [])))
  1052. print(leaf(UnaryOp(USub(), eight)))
  1053. print(leaf(Constant(8)))
  1054. \end{lstlisting}
  1055. \fi}
  1056. \end{minipage}
  1057. \vrule
  1058. \begin{minipage}{0.25\textwidth}
  1059. {\if\edition\racketEd
  1060. \begin{lstlisting}
  1061. #t
  1062. #f
  1063. #t
  1064. \end{lstlisting}
  1065. \fi}
  1066. {\if\edition\pythonEd\pythonColor
  1067. \begin{lstlisting}
  1068. True
  1069. False
  1070. True
  1071. \end{lstlisting}
  1072. \fi}
  1073. \end{minipage}
  1074. \end{center}
  1075. When constructing a \code{match} expression, we refer to the grammar
  1076. definition to identify which nonterminal we are expecting to match
  1077. against, and then we make sure that (1) we have one
  1078. \racket{clause}\python{case} for each alternative of that nonterminal
  1079. and (2) the pattern in each \racket{clause}\python{case}
  1080. corresponds to the corresponding right-hand side of a grammar
  1081. rule. For the \code{match} in the \code{leaf} function, we refer to
  1082. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1083. nonterminal has four alternatives, so the \code{match} has four
  1084. \racket{clauses}\python{cases}. The pattern in each
  1085. \racket{clause}\python{case} corresponds to the right-hand side of a
  1086. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1087. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1088. translating from grammars to patterns, replace nonterminals such as
  1089. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1090. \code{e2}).
  1091. \section{Recursive Functions}
  1092. \label{sec:recursion}
  1093. \index{subject}{recursive function}
  1094. Programs are inherently recursive. For example, an expression is often
  1095. made of smaller expressions. Thus, the natural way to process an
  1096. entire program is to use a recursive function. As a first example of
  1097. such a recursive function, we define the function \code{is\_exp} as
  1098. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1099. value and determine whether or not it is an expression in \LangInt{}.
  1100. %
  1101. We say that a function is defined by \emph{structural recursion} if
  1102. it is defined using a sequence of match \racket{clauses}\python{cases}
  1103. that correspond to a grammar and the body of each
  1104. \racket{clause}\python{case} makes a recursive call on each child
  1105. node.\footnote{This principle of structuring code according to the
  1106. data definition is advocated in the book \emph{How to Design
  1107. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1108. second function, named \code{stmt}, that recognizes whether a value
  1109. is a \LangInt{} statement.} \python{Finally, }
  1110. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1111. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1112. In general, we can write one recursive function to handle each
  1113. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1114. two examples at the bottom of the figure, the first is in
  1115. \LangInt{} and the second is not.
  1116. \begin{figure}[tp]
  1117. \begin{tcolorbox}[colback=white]
  1118. {\if\edition\racketEd
  1119. \begin{lstlisting}
  1120. (define (is_exp ast)
  1121. (match ast
  1122. [(Int n) #t]
  1123. [(Prim 'read '()) #t]
  1124. [(Prim '- (list e)) (is_exp e)]
  1125. [(Prim '+ (list e1 e2))
  1126. (and (is_exp e1) (is_exp e2))]
  1127. [(Prim '- (list e1 e2))
  1128. (and (is_exp e1) (is_exp e2))]
  1129. [else #f]))
  1130. (define (is_Lint ast)
  1131. (match ast
  1132. [(Program '() e) (is_exp e)]
  1133. [else #f]))
  1134. (is_Lint (Program '() ast1_1)
  1135. (is_Lint (Program '()
  1136. (Prim '* (list (Prim 'read '())
  1137. (Prim '+ (list (Int 8)))))))
  1138. \end{lstlisting}
  1139. \fi}
  1140. {\if\edition\pythonEd\pythonColor
  1141. \begin{lstlisting}
  1142. def is_exp(e):
  1143. match e:
  1144. case Constant(n):
  1145. return True
  1146. case Call(Name('input_int'), []):
  1147. return True
  1148. case UnaryOp(USub(), e1):
  1149. return is_exp(e1)
  1150. case BinOp(e1, Add(), e2):
  1151. return is_exp(e1) and is_exp(e2)
  1152. case BinOp(e1, Sub(), e2):
  1153. return is_exp(e1) and is_exp(e2)
  1154. case _:
  1155. return False
  1156. def stmt(s):
  1157. match s:
  1158. case Expr(Call(Name('print'), [e])):
  1159. return is_exp(e)
  1160. case Expr(e):
  1161. return is_exp(e)
  1162. case _:
  1163. return False
  1164. def is_Lint(p):
  1165. match p:
  1166. case Module(body):
  1167. return all([stmt(s) for s in body])
  1168. case _:
  1169. return False
  1170. print(is_Lint(Module([Expr(ast1_1)])))
  1171. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1172. UnaryOp(Add(), Constant(8))))])))
  1173. \end{lstlisting}
  1174. \fi}
  1175. \end{tcolorbox}
  1176. \caption{Example of recursive functions for \LangInt{}. These functions
  1177. recognize whether an AST is in \LangInt{}.}
  1178. \label{fig:exp-predicate}
  1179. \end{figure}
  1180. %% You may be tempted to merge the two functions into one, like this:
  1181. %% \begin{center}
  1182. %% \begin{minipage}{0.5\textwidth}
  1183. %% \begin{lstlisting}
  1184. %% (define (Lint ast)
  1185. %% (match ast
  1186. %% [(Int n) #t]
  1187. %% [(Prim 'read '()) #t]
  1188. %% [(Prim '- (list e)) (Lint e)]
  1189. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1190. %% [(Program '() e) (Lint e)]
  1191. %% [else #f]))
  1192. %% \end{lstlisting}
  1193. %% \end{minipage}
  1194. %% \end{center}
  1195. %% %
  1196. %% Sometimes such a trick will save a few lines of code, especially when
  1197. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1198. %% \emph{not} recommended because it can get you into trouble.
  1199. %% %
  1200. %% For example, the above function is subtly wrong:
  1201. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1202. %% returns true when it should return false.
  1203. \section{Interpreters}
  1204. \label{sec:interp_Lint}
  1205. \index{subject}{interpreter}
  1206. The behavior of a program is defined by the specification of the
  1207. programming language.
  1208. %
  1209. \racket{For example, the Scheme language is defined in the report by
  1210. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1211. reference manual~\citep{plt-tr}.}
  1212. %
  1213. \python{For example, the Python language is defined in the Python
  1214. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1215. %
  1216. In this book we use interpreters to specify each language that we
  1217. consider. An interpreter that is designated as the definition of a
  1218. language is called a \emph{definitional
  1219. interpreter}~\citep{reynolds72:_def_interp}.
  1220. \index{subject}{definitional interpreter} We warm up by creating a
  1221. definitional interpreter for the \LangInt{} language. This interpreter
  1222. serves as a second example of structural recursion. The definition of the
  1223. \code{interp\_Lint} function is shown in
  1224. figure~\ref{fig:interp_Lint}.
  1225. %
  1226. \racket{The body of the function is a match on the input program
  1227. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1228. which in turn has one match clause per grammar rule for \LangInt{}
  1229. expressions.}
  1230. %
  1231. \python{The body of the function matches on the \code{Module} AST node
  1232. and then invokes \code{interp\_stmt} on each statement in the
  1233. module. The \code{interp\_stmt} function includes a case for each
  1234. grammar rule of the \Stmt{} nonterminal and it calls
  1235. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1236. function includes a case for each grammar rule of the \Exp{}
  1237. nonterminal.}
  1238. \begin{figure}[tp]
  1239. \begin{tcolorbox}[colback=white]
  1240. {\if\edition\racketEd
  1241. \begin{lstlisting}
  1242. (define (interp_exp e)
  1243. (match e
  1244. [(Int n) n]
  1245. [(Prim 'read '())
  1246. (define r (read))
  1247. (cond [(fixnum? r) r]
  1248. [else (error 'interp_exp "read expected an integer" r)])]
  1249. [(Prim '- (list e))
  1250. (define v (interp_exp e))
  1251. (fx- 0 v)]
  1252. [(Prim '+ (list e1 e2))
  1253. (define v1 (interp_exp e1))
  1254. (define v2 (interp_exp e2))
  1255. (fx+ v1 v2)]
  1256. [(Prim '- (list e1 e2))
  1257. (define v1 ((interp-exp env) e1))
  1258. (define v2 ((interp-exp env) e2))
  1259. (fx- v1 v2)]))
  1260. (define (interp_Lint p)
  1261. (match p
  1262. [(Program '() e) (interp_exp e)]))
  1263. \end{lstlisting}
  1264. \fi}
  1265. {\if\edition\pythonEd\pythonColor
  1266. \begin{lstlisting}
  1267. def interp_exp(e):
  1268. match e:
  1269. case BinOp(left, Add(), right):
  1270. l = interp_exp(left); r = interp_exp(right)
  1271. return l + r
  1272. case BinOp(left, Sub(), right):
  1273. l = interp_exp(left); r = interp_exp(right)
  1274. return l - r
  1275. case UnaryOp(USub(), v):
  1276. return - interp_exp(v)
  1277. case Constant(value):
  1278. return value
  1279. case Call(Name('input_int'), []):
  1280. return int(input())
  1281. def interp_stmt(s):
  1282. match s:
  1283. case Expr(Call(Name('print'), [arg])):
  1284. print(interp_exp(arg))
  1285. case Expr(value):
  1286. interp_exp(value)
  1287. def interp_Lint(p):
  1288. match p:
  1289. case Module(body):
  1290. for s in body:
  1291. interp_stmt(s)
  1292. \end{lstlisting}
  1293. \fi}
  1294. \end{tcolorbox}
  1295. \caption{Interpreter for the \LangInt{} language.}
  1296. \label{fig:interp_Lint}
  1297. \end{figure}
  1298. Let us consider the result of interpreting a few \LangInt{} programs. The
  1299. following program adds two integers:
  1300. {\if\edition\racketEd
  1301. \begin{lstlisting}
  1302. (+ 10 32)
  1303. \end{lstlisting}
  1304. \fi}
  1305. {\if\edition\pythonEd\pythonColor
  1306. \begin{lstlisting}
  1307. print(10 + 32)
  1308. \end{lstlisting}
  1309. \fi}
  1310. %
  1311. \noindent The result is \key{42}, the answer to life, the universe,
  1312. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1313. the Galaxy} by Douglas Adams.}
  1314. %
  1315. We wrote this program in concrete syntax, whereas the parsed
  1316. abstract syntax is
  1317. {\if\edition\racketEd
  1318. \begin{lstlisting}
  1319. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1320. \end{lstlisting}
  1321. \fi}
  1322. {\if\edition\pythonEd\pythonColor
  1323. \begin{lstlisting}
  1324. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1325. \end{lstlisting}
  1326. \fi}
  1327. The following program demonstrates that expressions may be nested within
  1328. each other, in this case nesting several additions and negations.
  1329. {\if\edition\racketEd
  1330. \begin{lstlisting}
  1331. (+ 10 (- (+ 12 20)))
  1332. \end{lstlisting}
  1333. \fi}
  1334. {\if\edition\pythonEd\pythonColor
  1335. \begin{lstlisting}
  1336. print(10 + -(12 + 20))
  1337. \end{lstlisting}
  1338. \fi}
  1339. %
  1340. \noindent What is the result of this program?
  1341. {\if\edition\racketEd
  1342. As mentioned previously, the \LangInt{} language does not support
  1343. arbitrarily large integers but only $63$-bit integers, so we
  1344. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1345. in Racket.
  1346. Suppose that
  1347. \[
  1348. n = 999999999999999999
  1349. \]
  1350. which indeed fits in $63$ bits. What happens when we run the
  1351. following program in our interpreter?
  1352. \begin{lstlisting}
  1353. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1354. \end{lstlisting}
  1355. It produces the following error:
  1356. \begin{lstlisting}
  1357. fx+: result is not a fixnum
  1358. \end{lstlisting}
  1359. We establish the convention that if running the definitional
  1360. interpreter on a program produces an error, then the meaning of that
  1361. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1362. error is a \code{trapped-error}. A compiler for the language is under
  1363. no obligation regarding programs with unspecified behavior; it does
  1364. not have to produce an executable, and if it does, that executable can
  1365. do anything. On the other hand, if the error is a
  1366. \code{trapped-error}, then the compiler must produce an executable and
  1367. it is required to report that an error occurred. To signal an error,
  1368. exit with a return code of \code{255}. The interpreters in chapters
  1369. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1370. \code{trapped-error}.
  1371. \fi}
  1372. % TODO: how to deal with too-large integers in the Python interpreter?
  1373. %% This convention applies to the languages defined in this
  1374. %% book, as a way to simplify the student's task of implementing them,
  1375. %% but this convention is not applicable to all programming languages.
  1376. %%
  1377. The last feature of the \LangInt{} language, the \READOP{} operation,
  1378. prompts the user of the program for an integer. Recall that program
  1379. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1380. \code{8}. So, if we run {\if\edition\racketEd
  1381. \begin{lstlisting}
  1382. (interp_Lint (Program '() ast1_1))
  1383. \end{lstlisting}
  1384. \fi}
  1385. {\if\edition\pythonEd\pythonColor
  1386. \begin{lstlisting}
  1387. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1388. \end{lstlisting}
  1389. \fi}
  1390. \noindent and if the input is \code{50}, the result is \code{42}.
  1391. We include the \READOP{} operation in \LangInt{} so that a clever
  1392. student cannot implement a compiler for \LangInt{} that simply runs
  1393. the interpreter during compilation to obtain the output and then
  1394. generates the trivial code to produce the output.\footnote{Yes, a
  1395. clever student did this in the first instance of this course!}
  1396. The job of a compiler is to translate a program in one language into a
  1397. program in another language so that the output program behaves the
  1398. same way as the input program. This idea is depicted in the
  1399. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1400. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1401. Given a compiler that translates from language $\mathcal{L}_1$ to
  1402. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1403. compiler must translate it into some program $P_2$ such that
  1404. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1405. same input $i$ yields the same output $o$.
  1406. \begin{equation} \label{eq:compile-correct}
  1407. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1408. \node (p1) at (0, 0) {$P_1$};
  1409. \node (p2) at (3, 0) {$P_2$};
  1410. \node (o) at (3, -2.5) {$o$};
  1411. \path[->] (p1) edge [above] node {compile} (p2);
  1412. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1413. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1414. \end{tikzpicture}
  1415. \end{equation}
  1416. In the next section we see our first example of a compiler.
  1417. \section{Example Compiler: A Partial Evaluator}
  1418. \label{sec:partial-evaluation}
  1419. In this section we consider a compiler that translates \LangInt{}
  1420. programs into \LangInt{} programs that may be more efficient. The
  1421. compiler eagerly computes the parts of the program that do not depend
  1422. on any inputs, a process known as \emph{partial
  1423. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1424. For example, given the following program
  1425. {\if\edition\racketEd
  1426. \begin{lstlisting}
  1427. (+ (read) (- (+ 5 3)))
  1428. \end{lstlisting}
  1429. \fi}
  1430. {\if\edition\pythonEd\pythonColor
  1431. \begin{lstlisting}
  1432. print(input_int() + -(5 + 3) )
  1433. \end{lstlisting}
  1434. \fi}
  1435. \noindent our compiler translates it into the program
  1436. {\if\edition\racketEd
  1437. \begin{lstlisting}
  1438. (+ (read) -8)
  1439. \end{lstlisting}
  1440. \fi}
  1441. {\if\edition\pythonEd\pythonColor
  1442. \begin{lstlisting}
  1443. print(input_int() + -8)
  1444. \end{lstlisting}
  1445. \fi}
  1446. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1447. evaluator for the \LangInt{} language. The output of the partial evaluator
  1448. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1449. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1450. whereas the code for partially evaluating the negation and addition
  1451. operations is factored into three auxiliary functions:
  1452. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1453. functions is the output of partially evaluating the children.
  1454. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1455. arguments are integers and if they are, perform the appropriate
  1456. arithmetic. Otherwise, they create an AST node for the arithmetic
  1457. operation.
  1458. \begin{figure}[tp]
  1459. \begin{tcolorbox}[colback=white]
  1460. {\if\edition\racketEd
  1461. \begin{lstlisting}
  1462. (define (pe_neg r)
  1463. (match r
  1464. [(Int n) (Int (fx- 0 n))]
  1465. [else (Prim '- (list r))]))
  1466. (define (pe_add r1 r2)
  1467. (match* (r1 r2)
  1468. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1469. [(_ _) (Prim '+ (list r1 r2))]))
  1470. (define (pe_sub r1 r2)
  1471. (match* (r1 r2)
  1472. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1473. [(_ _) (Prim '- (list r1 r2))]))
  1474. (define (pe_exp e)
  1475. (match e
  1476. [(Int n) (Int n)]
  1477. [(Prim 'read '()) (Prim 'read '())]
  1478. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1479. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1480. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1481. (define (pe_Lint p)
  1482. (match p
  1483. [(Program '() e) (Program '() (pe_exp e))]))
  1484. \end{lstlisting}
  1485. \fi}
  1486. {\if\edition\pythonEd\pythonColor
  1487. \begin{lstlisting}
  1488. def pe_neg(r):
  1489. match r:
  1490. case Constant(n):
  1491. return Constant(-n)
  1492. case _:
  1493. return UnaryOp(USub(), r)
  1494. def pe_add(r1, r2):
  1495. match (r1, r2):
  1496. case (Constant(n1), Constant(n2)):
  1497. return Constant(n1 + n2)
  1498. case _:
  1499. return BinOp(r1, Add(), r2)
  1500. def pe_sub(r1, r2):
  1501. match (r1, r2):
  1502. case (Constant(n1), Constant(n2)):
  1503. return Constant(n1 - n2)
  1504. case _:
  1505. return BinOp(r1, Sub(), r2)
  1506. def pe_exp(e):
  1507. match e:
  1508. case BinOp(left, Add(), right):
  1509. return pe_add(pe_exp(left), pe_exp(right))
  1510. case BinOp(left, Sub(), right):
  1511. return pe_sub(pe_exp(left), pe_exp(right))
  1512. case UnaryOp(USub(), v):
  1513. return pe_neg(pe_exp(v))
  1514. case Constant(value):
  1515. return e
  1516. case Call(Name('input_int'), []):
  1517. return e
  1518. def pe_stmt(s):
  1519. match s:
  1520. case Expr(Call(Name('print'), [arg])):
  1521. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1522. case Expr(value):
  1523. return Expr(pe_exp(value))
  1524. def pe_P_int(p):
  1525. match p:
  1526. case Module(body):
  1527. new_body = [pe_stmt(s) for s in body]
  1528. return Module(new_body)
  1529. \end{lstlisting}
  1530. \fi}
  1531. \end{tcolorbox}
  1532. \caption{A partial evaluator for \LangInt{}.}
  1533. \label{fig:pe-arith}
  1534. \end{figure}
  1535. To gain some confidence that the partial evaluator is correct, we can
  1536. test whether it produces programs that produce the same result as the
  1537. input programs. That is, we can test whether it satisfies the diagram
  1538. of \eqref{eq:compile-correct}.
  1539. %
  1540. {\if\edition\racketEd
  1541. The following code runs the partial evaluator on several examples and
  1542. tests the output program. The \texttt{parse-program} and
  1543. \texttt{assert} functions are defined in
  1544. appendix~\ref{appendix:utilities}.\\
  1545. \begin{minipage}{1.0\textwidth}
  1546. \begin{lstlisting}
  1547. (define (test_pe p)
  1548. (assert "testing pe_Lint"
  1549. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1550. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1551. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1552. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1553. \end{lstlisting}
  1554. \end{minipage}
  1555. \fi}
  1556. % TODO: python version of testing the PE
  1557. \begin{exercise}\normalfont\normalsize
  1558. Create three programs in the \LangInt{} language and test whether
  1559. partially evaluating them with \code{pe\_Lint} and then
  1560. interpreting them with \code{interp\_Lint} gives the same result
  1561. as directly interpreting them with \code{interp\_Lint}.
  1562. \end{exercise}
  1563. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1564. \chapter{Integers and Variables}
  1565. \label{ch:Lvar}
  1566. \setcounter{footnote}{0}
  1567. This chapter covers compiling a subset of
  1568. \racket{Racket}\python{Python} to x86-64 assembly
  1569. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1570. integer arithmetic and local variables. We often refer to x86-64
  1571. simply as x86. The chapter first describes the \LangVar{} language
  1572. (section~\ref{sec:s0}) and then introduces x86 assembly
  1573. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1574. discuss only the instructions needed for compiling \LangVar{}. We
  1575. introduce more x86 instructions in subsequent chapters. After
  1576. introducing \LangVar{} and x86, we reflect on their differences and
  1577. create a plan to break down the translation from \LangVar{} to x86
  1578. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1579. the chapter gives detailed hints regarding each step. We aim to give
  1580. enough hints that the well-prepared reader, together with a few
  1581. friends, can implement a compiler from \LangVar{} to x86 in a short
  1582. time. To suggest the scale of this first compiler, we note that the
  1583. instructor solution for the \LangVar{} compiler is approximately
  1584. \racket{500}\python{300} lines of code.
  1585. \section{The \LangVar{} Language}
  1586. \label{sec:s0}
  1587. \index{subject}{variable}
  1588. The \LangVar{} language extends the \LangInt{} language with
  1589. variables. The concrete syntax of the \LangVar{} language is defined
  1590. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1591. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1592. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1593. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1594. \key{-} is a unary operator, and \key{+} is a binary operator.
  1595. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1596. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1597. the top of the program.
  1598. %% The $\itm{info}$
  1599. %% field of the \key{Program} structure contains an \emph{association
  1600. %% list} (a list of key-value pairs) that is used to communicate
  1601. %% auxiliary data from one compiler pass the next.
  1602. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1603. exhibit several compilation techniques.
  1604. \newcommand{\LvarGrammarRacket}{
  1605. \begin{array}{rcl}
  1606. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1607. \end{array}
  1608. }
  1609. \newcommand{\LvarASTRacket}{
  1610. \begin{array}{rcl}
  1611. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1612. \end{array}
  1613. }
  1614. \newcommand{\LvarGrammarPython}{
  1615. \begin{array}{rcl}
  1616. \Exp &::=& \Var{} \\
  1617. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1618. \end{array}
  1619. }
  1620. \newcommand{\LvarASTPython}{
  1621. \begin{array}{rcl}
  1622. \Exp{} &::=& \VAR{\Var{}} \\
  1623. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1624. \end{array}
  1625. }
  1626. \begin{figure}[tp]
  1627. \centering
  1628. \begin{tcolorbox}[colback=white]
  1629. {\if\edition\racketEd
  1630. \[
  1631. \begin{array}{l}
  1632. \gray{\LintGrammarRacket{}} \\ \hline
  1633. \LvarGrammarRacket{} \\
  1634. \begin{array}{rcl}
  1635. \LangVarM{} &::=& \Exp
  1636. \end{array}
  1637. \end{array}
  1638. \]
  1639. \fi}
  1640. {\if\edition\pythonEd\pythonColor
  1641. \[
  1642. \begin{array}{l}
  1643. \gray{\LintGrammarPython} \\ \hline
  1644. \LvarGrammarPython \\
  1645. \begin{array}{rcl}
  1646. \LangVarM{} &::=& \Stmt^{*}
  1647. \end{array}
  1648. \end{array}
  1649. \]
  1650. \fi}
  1651. \end{tcolorbox}
  1652. \caption{The concrete syntax of \LangVar{}.}
  1653. \label{fig:Lvar-concrete-syntax}
  1654. \end{figure}
  1655. \begin{figure}[tp]
  1656. \centering
  1657. \begin{tcolorbox}[colback=white]
  1658. {\if\edition\racketEd
  1659. \[
  1660. \begin{array}{l}
  1661. \gray{\LintASTRacket{}} \\ \hline
  1662. \LvarASTRacket \\
  1663. \begin{array}{rcl}
  1664. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1665. \end{array}
  1666. \end{array}
  1667. \]
  1668. \fi}
  1669. {\if\edition\pythonEd\pythonColor
  1670. \[
  1671. \begin{array}{l}
  1672. \gray{\LintASTPython}\\ \hline
  1673. \LvarASTPython \\
  1674. \begin{array}{rcl}
  1675. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1676. \end{array}
  1677. \end{array}
  1678. \]
  1679. \fi}
  1680. \end{tcolorbox}
  1681. \caption{The abstract syntax of \LangVar{}.}
  1682. \label{fig:Lvar-syntax}
  1683. \end{figure}
  1684. {\if\edition\racketEd
  1685. Let us dive further into the syntax and semantics of the \LangVar{}
  1686. language. The \key{let} feature defines a variable for use within its
  1687. body and initializes the variable with the value of an expression.
  1688. The abstract syntax for \key{let} is shown in
  1689. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1690. \begin{lstlisting}
  1691. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1692. \end{lstlisting}
  1693. For example, the following program initializes \code{x} to $32$ and then
  1694. evaluates the body \code{(+ 10 x)}, producing $42$.
  1695. \begin{lstlisting}
  1696. (let ([x (+ 12 20)]) (+ 10 x))
  1697. \end{lstlisting}
  1698. \fi}
  1699. %
  1700. {\if\edition\pythonEd\pythonColor
  1701. %
  1702. The \LangVar{} language includes assignment statements, which define a
  1703. variable for use in later statements and initializes the variable with
  1704. the value of an expression. The abstract syntax for assignment is
  1705. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1706. assignment is \index{subject}{Assign@\texttt{Assign}}
  1707. \begin{lstlisting}
  1708. |$\itm{var}$| = |$\itm{exp}$|
  1709. \end{lstlisting}
  1710. For example, the following program initializes the variable \code{x}
  1711. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1712. \begin{lstlisting}
  1713. x = 12 + 20
  1714. print(10 + x)
  1715. \end{lstlisting}
  1716. \fi}
  1717. {\if\edition\racketEd
  1718. %
  1719. When there are multiple \key{let}s for the same variable, the closest
  1720. enclosing \key{let} is used. That is, variable definitions overshadow
  1721. prior definitions. Consider the following program with two \key{let}s
  1722. that define two variables named \code{x}. Can you figure out the
  1723. result?
  1724. \begin{lstlisting}
  1725. (let ([x 32]) (+ (let ([x 10]) x) x))
  1726. \end{lstlisting}
  1727. For the purposes of depicting which variable occurrences correspond to
  1728. which definitions, the following shows the \code{x}'s annotated with
  1729. subscripts to distinguish them. Double check that your answer for the
  1730. previous program is the same as your answer for this annotated version
  1731. of the program.
  1732. \begin{lstlisting}
  1733. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1734. \end{lstlisting}
  1735. The initializing expression is always evaluated before the body of the
  1736. \key{let}, so in the following, the \key{read} for \code{x} is
  1737. performed before the \key{read} for \code{y}. Given the input
  1738. $52$ then $10$, the following produces $42$ (not $-42$).
  1739. \begin{lstlisting}
  1740. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1741. \end{lstlisting}
  1742. \fi}
  1743. \subsection{Extensible Interpreters via Method Overriding}
  1744. \label{sec:extensible-interp}
  1745. To prepare for discussing the interpreter of \LangVar{}, we explain
  1746. why we implement it in an object-oriented style. Throughout this book
  1747. we define many interpreters, one for each language that we
  1748. study. Because each language builds on the prior one, there is a lot
  1749. of commonality between these interpreters. We want to write down the
  1750. common parts just once instead of many times. A naive interpreter for
  1751. \LangVar{} would handle the \racket{cases for variables and
  1752. \code{let}} \python{case for variables} but dispatch to an
  1753. interpreter for \LangInt{} in the rest of the cases. The following
  1754. code sketches this idea. (We explain the \code{env} parameter in
  1755. section~\ref{sec:interp-Lvar}.)
  1756. \begin{center}
  1757. {\if\edition\racketEd
  1758. \begin{minipage}{0.45\textwidth}
  1759. \begin{lstlisting}
  1760. (define ((interp_Lint env) e)
  1761. (match e
  1762. [(Prim '- (list e1))
  1763. (fx- 0 ((interp_Lint env) e1))]
  1764. ...))
  1765. \end{lstlisting}
  1766. \end{minipage}
  1767. \begin{minipage}{0.45\textwidth}
  1768. \begin{lstlisting}
  1769. (define ((interp_Lvar env) e)
  1770. (match e
  1771. [(Var x)
  1772. (dict-ref env x)]
  1773. [(Let x e body)
  1774. (define v ((interp_exp env) e))
  1775. (define env^ (dict-set env x v))
  1776. ((interp_exp env^) body)]
  1777. [else ((interp_Lint env) e)]))
  1778. \end{lstlisting}
  1779. \end{minipage}
  1780. \fi}
  1781. {\if\edition\pythonEd\pythonColor
  1782. \begin{minipage}{0.45\textwidth}
  1783. \begin{lstlisting}
  1784. def interp_Lint(e, env):
  1785. match e:
  1786. case UnaryOp(USub(), e1):
  1787. return - interp_Lint(e1, env)
  1788. ...
  1789. \end{lstlisting}
  1790. \end{minipage}
  1791. \begin{minipage}{0.45\textwidth}
  1792. \begin{lstlisting}
  1793. def interp_Lvar(e, env):
  1794. match e:
  1795. case Name(id):
  1796. return env[id]
  1797. case _:
  1798. return interp_Lint(e, env)
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \fi}
  1802. \end{center}
  1803. The problem with this naive approach is that it does not handle
  1804. situations in which an \LangVar{} feature, such as a variable, is
  1805. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1806. in the following program.
  1807. {\if\edition\racketEd
  1808. \begin{lstlisting}
  1809. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1810. \end{lstlisting}
  1811. \fi}
  1812. {\if\edition\pythonEd\pythonColor
  1813. \begin{minipage}{0.96\textwidth}
  1814. \begin{lstlisting}
  1815. y = 10
  1816. print(-y)
  1817. \end{lstlisting}
  1818. \end{minipage}
  1819. \fi}
  1820. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1821. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1822. then it recursively calls \code{interp\_Lint} again on its argument.
  1823. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1824. an error!
  1825. To make our interpreters extensible we need something called
  1826. \emph{open recursion}\index{subject}{open recursion}, in which the
  1827. tying of the recursive knot is delayed until the functions are
  1828. composed. Object-oriented languages provide open recursion via method
  1829. overriding\index{subject}{method overriding}. The following code uses
  1830. method overriding to interpret \LangInt{} and \LangVar{} using
  1831. %
  1832. \racket{the
  1833. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1834. \index{subject}{class} feature of Racket.}
  1835. %
  1836. \python{a Python \code{class} definition.}
  1837. %
  1838. We define one class for each language and define a method for
  1839. interpreting expressions inside each class. The class for \LangVar{}
  1840. inherits from the class for \LangInt{}, and the method
  1841. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1842. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1843. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1844. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1845. \code{interp\_exp} in \LangInt{}.
  1846. \begin{center}
  1847. \hspace{-20pt}
  1848. {\if\edition\racketEd
  1849. \begin{minipage}{0.45\textwidth}
  1850. \begin{lstlisting}
  1851. (define interp-Lint-class
  1852. (class object%
  1853. (define/public ((interp_exp env) e)
  1854. (match e
  1855. [(Prim '- (list e))
  1856. (fx- 0 ((interp_exp env) e))]
  1857. ...))
  1858. ...))
  1859. \end{lstlisting}
  1860. \end{minipage}
  1861. \begin{minipage}{0.45\textwidth}
  1862. \begin{lstlisting}
  1863. (define interp-Lvar-class
  1864. (class interp-Lint-class
  1865. (define/override ((interp_exp env) e)
  1866. (match e
  1867. [(Var x)
  1868. (dict-ref env x)]
  1869. [(Let x e body)
  1870. (define v ((interp_exp env) e))
  1871. (define env^ (dict-set env x v))
  1872. ((interp_exp env^) body)]
  1873. [else
  1874. (super (interp_exp env) e)]))
  1875. ...
  1876. ))
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. \fi}
  1880. {\if\edition\pythonEd\pythonColor
  1881. \begin{minipage}{0.45\textwidth}
  1882. \begin{lstlisting}
  1883. class InterpLint:
  1884. def interp_exp(e):
  1885. match e:
  1886. case UnaryOp(USub(), e1):
  1887. return -self.interp_exp(e1)
  1888. ...
  1889. ...
  1890. \end{lstlisting}
  1891. \end{minipage}
  1892. \begin{minipage}{0.45\textwidth}
  1893. \begin{lstlisting}
  1894. def InterpLvar(InterpLint):
  1895. def interp_exp(e):
  1896. match e:
  1897. case Name(id):
  1898. return env[id]
  1899. case _:
  1900. return super().interp_exp(e)
  1901. ...
  1902. \end{lstlisting}
  1903. \end{minipage}
  1904. \fi}
  1905. \end{center}
  1906. Getting back to the troublesome example, repeated here
  1907. {\if\edition\racketEd
  1908. \begin{lstlisting}
  1909. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1910. \end{lstlisting}
  1911. \fi}
  1912. {\if\edition\pythonEd\pythonColor
  1913. \begin{lstlisting}
  1914. y = 10
  1915. print(-y)
  1916. \end{lstlisting}
  1917. \fi}
  1918. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1919. \racket{on this expression,}
  1920. \python{on the \code{-y} expression,}
  1921. %
  1922. which we call \code{e0}, by creating an object of the \LangVar{} class
  1923. and calling the \code{interp\_exp} method
  1924. {\if\edition\racketEd
  1925. \begin{lstlisting}
  1926. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1927. \end{lstlisting}
  1928. \fi}
  1929. {\if\edition\pythonEd\pythonColor
  1930. \begin{lstlisting}
  1931. InterpLvar().interp_exp(e0)
  1932. \end{lstlisting}
  1933. \fi}
  1934. \noindent To process the \code{-} operator, the default case of
  1935. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1936. method in \LangInt{}. But then for the recursive method call, it
  1937. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1938. \code{Var} node is handled correctly. Thus, method overriding gives us
  1939. the open recursion that we need to implement our interpreters in an
  1940. extensible way.
  1941. \subsection{Definitional Interpreter for \LangVar{}}
  1942. \label{sec:interp-Lvar}
  1943. Having justified the use of classes and methods to implement
  1944. interpreters, we revisit the definitional interpreter for \LangInt{}
  1945. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1946. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1947. The interpreter for \LangVar{} adds two new \key{match} cases for
  1948. variables and \racket{\key{let}}\python{assignment}. For
  1949. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1950. value bound to a variable to all the uses of the variable. To
  1951. accomplish this, we maintain a mapping from variables to values called
  1952. an \emph{environment}\index{subject}{environment}.
  1953. %
  1954. We use
  1955. %
  1956. \racket{an association list (alist) }%
  1957. %
  1958. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1959. %
  1960. to represent the environment.
  1961. %
  1962. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1963. and the \code{racket/dict} package.}
  1964. %
  1965. The \code{interp\_exp} function takes the current environment,
  1966. \code{env}, as an extra parameter. When the interpreter encounters a
  1967. variable, it looks up the corresponding value in the dictionary.
  1968. %
  1969. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1970. initializing expression, extends the environment with the result
  1971. value bound to the variable, using \code{dict-set}, then evaluates
  1972. the body of the \key{Let}.}
  1973. %
  1974. \python{When the interpreter encounters an assignment, it evaluates
  1975. the initializing expression and then associates the resulting value
  1976. with the variable in the environment.}
  1977. \begin{figure}[tp]
  1978. \begin{tcolorbox}[colback=white]
  1979. {\if\edition\racketEd
  1980. \begin{lstlisting}
  1981. (define interp-Lint-class
  1982. (class object%
  1983. (super-new)
  1984. (define/public ((interp_exp env) e)
  1985. (match e
  1986. [(Int n) n]
  1987. [(Prim 'read '())
  1988. (define r (read))
  1989. (cond [(fixnum? r) r]
  1990. [else (error 'interp_exp "expected an integer" r)])]
  1991. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1992. [(Prim '+ (list e1 e2))
  1993. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1994. [(Prim '- (list e1 e2))
  1995. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1996. (define/public (interp_program p)
  1997. (match p
  1998. [(Program '() e) ((interp_exp '()) e)]))
  1999. ))
  2000. \end{lstlisting}
  2001. \fi}
  2002. {\if\edition\pythonEd\pythonColor
  2003. \begin{lstlisting}
  2004. class InterpLint:
  2005. def interp_exp(self, e, env):
  2006. match e:
  2007. case BinOp(left, Add(), right):
  2008. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2009. case BinOp(left, Sub(), right):
  2010. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2011. case UnaryOp(USub(), v):
  2012. return - self.interp_exp(v, env)
  2013. case Constant(value):
  2014. return value
  2015. case Call(Name('input_int'), []):
  2016. return int(input())
  2017. def interp_stmts(self, ss, env):
  2018. if len(ss) == 0:
  2019. return
  2020. match ss[0]:
  2021. case Expr(Call(Name('print'), [arg])):
  2022. print(self.interp_exp(arg, env), end='')
  2023. return self.interp_stmts(ss[1:], env)
  2024. case Expr(value):
  2025. self.interp_exp(value, env)
  2026. return self.interp_stmts(ss[1:], env)
  2027. def interp(self, p):
  2028. match p:
  2029. case Module(body):
  2030. self.interp_stmts(body, {})
  2031. def interp_Lint(p):
  2032. return InterpLint().interp(p)
  2033. \end{lstlisting}
  2034. \fi}
  2035. \end{tcolorbox}
  2036. \caption{Interpreter for \LangInt{} as a class.}
  2037. \label{fig:interp-Lint-class}
  2038. \end{figure}
  2039. \begin{figure}[tp]
  2040. \begin{tcolorbox}[colback=white]
  2041. {\if\edition\racketEd
  2042. \begin{lstlisting}
  2043. (define interp-Lvar-class
  2044. (class interp-Lint-class
  2045. (super-new)
  2046. (define/override ((interp_exp env) e)
  2047. (match e
  2048. [(Var x) (dict-ref env x)]
  2049. [(Let x e body)
  2050. (define new-env (dict-set env x ((interp_exp env) e)))
  2051. ((interp_exp new-env) body)]
  2052. [else ((super interp-exp env) e)]))
  2053. ))
  2054. (define (interp_Lvar p)
  2055. (send (new interp-Lvar-class) interp_program p))
  2056. \end{lstlisting}
  2057. \fi}
  2058. {\if\edition\pythonEd\pythonColor
  2059. \begin{lstlisting}
  2060. class InterpLvar(InterpLint):
  2061. def interp_exp(self, e, env):
  2062. match e:
  2063. case Name(id):
  2064. return env[id]
  2065. case _:
  2066. return super().interp_exp(e, env)
  2067. def interp_stmts(self, ss, env):
  2068. if len(ss) == 0:
  2069. return
  2070. match ss[0]:
  2071. case Assign([lhs], value):
  2072. env[lhs.id] = self.interp_exp(value, env)
  2073. return self.interp_stmts(ss[1:], env)
  2074. case _:
  2075. return super().interp_stmts(ss, env)
  2076. def interp_Lvar(p):
  2077. return InterpLvar().interp(p)
  2078. \end{lstlisting}
  2079. \fi}
  2080. \end{tcolorbox}
  2081. \caption{Interpreter for the \LangVar{} language.}
  2082. \label{fig:interp-Lvar}
  2083. \end{figure}
  2084. {\if\edition\racketEd
  2085. \begin{figure}[tp]
  2086. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2087. \small
  2088. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2089. An \emph{association list} (called an alist) is a list of key-value pairs.
  2090. For example, we can map people to their ages with an alist
  2091. \index{subject}{alist}\index{subject}{association list}
  2092. \begin{lstlisting}[basicstyle=\ttfamily]
  2093. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2094. \end{lstlisting}
  2095. The \emph{dictionary} interface is for mapping keys to values.
  2096. Every alist implements this interface. \index{subject}{dictionary}
  2097. The package
  2098. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2099. provides many functions for working with dictionaries, such as
  2100. \begin{description}
  2101. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2102. returns the value associated with the given $\itm{key}$.
  2103. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2104. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2105. and otherwise is the same as $\itm{dict}$.
  2106. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2107. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2108. of keys and values in $\itm{dict}$. For example, the following
  2109. creates a new alist in which the ages are incremented:
  2110. \end{description}
  2111. \vspace{-10pt}
  2112. \begin{lstlisting}[basicstyle=\ttfamily]
  2113. (for/list ([(k v) (in-dict ages)])
  2114. (cons k (add1 v)))
  2115. \end{lstlisting}
  2116. \end{tcolorbox}
  2117. %\end{wrapfigure}
  2118. \caption{Association lists implement the dictionary interface.}
  2119. \label{fig:alist}
  2120. \end{figure}
  2121. \fi}
  2122. The goal for this chapter is to implement a compiler that translates
  2123. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2124. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2125. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2126. That is, they output the same integer $n$. We depict this correctness
  2127. criteria in the following diagram:
  2128. \[
  2129. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2130. \node (p1) at (0, 0) {$P_1$};
  2131. \node (p2) at (4, 0) {$P_2$};
  2132. \node (o) at (4, -2) {$n$};
  2133. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2134. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2135. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2136. \end{tikzpicture}
  2137. \]
  2138. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2139. compiling \LangVar{}.
  2140. \section{The \LangXInt{} Assembly Language}
  2141. \label{sec:x86}
  2142. \index{subject}{x86}
  2143. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2144. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2145. assembler.
  2146. %
  2147. A program begins with a \code{main} label followed by a sequence of
  2148. instructions. The \key{globl} directive makes the \key{main} procedure
  2149. externally visible so that the operating system can call it.
  2150. %
  2151. An x86 program is stored in the computer's memory. For our purposes,
  2152. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2153. values. The computer has a \emph{program counter}
  2154. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2155. \code{rip} register that points to the address of the next instruction
  2156. to be executed. For most instructions, the program counter is
  2157. incremented after the instruction is executed so that it points to the
  2158. next instruction in memory. Most x86 instructions take two operands,
  2159. each of which is an integer constant (called an \emph{immediate
  2160. value}\index{subject}{immediate value}), a
  2161. \emph{register}\index{subject}{register}, or a memory location.
  2162. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2163. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2164. && \key{r8} \MID \key{r9} \MID \key{r10}
  2165. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2166. \MID \key{r14} \MID \key{r15}}
  2167. \newcommand{\GrammarXInt}{
  2168. \begin{array}{rcl}
  2169. \Reg &::=& \allregisters{} \\
  2170. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2171. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2172. \key{subq} \; \Arg\key{,} \Arg \MID
  2173. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2174. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2175. \key{callq} \; \mathit{label} \MID
  2176. \key{retq} \MID
  2177. \key{jmp}\,\itm{label} \MID \\
  2178. && \itm{label}\key{:}\; \Instr
  2179. \end{array}
  2180. }
  2181. \begin{figure}[tp]
  2182. \begin{tcolorbox}[colback=white]
  2183. {\if\edition\racketEd
  2184. \[
  2185. \begin{array}{l}
  2186. \GrammarXInt \\
  2187. \begin{array}{lcl}
  2188. \LangXIntM{} &::= & \key{.globl main}\\
  2189. & & \key{main:} \; \Instr\ldots
  2190. \end{array}
  2191. \end{array}
  2192. \]
  2193. \fi}
  2194. {\if\edition\pythonEd\pythonColor
  2195. \[
  2196. \begin{array}{lcl}
  2197. \Reg &::=& \allregisters{} \\
  2198. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2199. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2200. \key{subq} \; \Arg\key{,} \Arg \MID
  2201. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2202. && \key{callq} \; \mathit{label} \MID
  2203. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2204. \LangXIntM{} &::= & \key{.globl main}\\
  2205. & & \key{main:} \; \Instr^{*}
  2206. \end{array}
  2207. \]
  2208. \fi}
  2209. \end{tcolorbox}
  2210. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2211. \label{fig:x86-int-concrete}
  2212. \end{figure}
  2213. A register is a special kind of variable that holds a 64-bit
  2214. value. There are 16 general-purpose registers in the computer; their
  2215. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2216. written with a percent sign, \key{\%}, followed by the register name,
  2217. for example \key{\%rax}.
  2218. An immediate value is written using the notation \key{\$}$n$ where $n$
  2219. is an integer.
  2220. %
  2221. %
  2222. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2223. which obtains the address stored in register $r$ and then adds $n$
  2224. bytes to the address. The resulting address is used to load or to store
  2225. to memory depending on whether it occurs as a source or destination
  2226. argument of an instruction.
  2227. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2228. the source $s$ and destination $d$, applies the arithmetic operation,
  2229. and then writes the result to the destination $d$. \index{subject}{instruction}
  2230. %
  2231. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2232. stores the result in $d$.
  2233. %
  2234. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2235. specified by the label, and $\key{retq}$ returns from a procedure to
  2236. its caller.
  2237. %
  2238. We discuss procedure calls in more detail further in this chapter and
  2239. in chapter~\ref{ch:Lfun}.
  2240. %
  2241. The last letter \key{q} indicates that these instructions operate on
  2242. quadwords which are 64-bit values.
  2243. %
  2244. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2245. counter to the address of the instruction immediately after the
  2246. specified label.}
  2247. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2248. all the x86 instructions used in this book.
  2249. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2250. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2251. \lstinline{movq $10, %rax}
  2252. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2253. adds $32$ to the $10$ in \key{rax} and
  2254. puts the result, $42$, into \key{rax}.
  2255. %
  2256. The last instruction \key{retq} finishes the \key{main} function by
  2257. returning the integer in \key{rax} to the operating system. The
  2258. operating system interprets this integer as the program's exit
  2259. code. By convention, an exit code of 0 indicates that a program has
  2260. completed successfully, and all other exit codes indicate various
  2261. errors.
  2262. %
  2263. \racket{However, in this book we return the result of the program
  2264. as the exit code.}
  2265. \begin{figure}[tbp]
  2266. \begin{minipage}{0.45\textwidth}
  2267. \begin{tcolorbox}[colback=white]
  2268. \begin{lstlisting}
  2269. .globl main
  2270. main:
  2271. movq $10, %rax
  2272. addq $32, %rax
  2273. retq
  2274. \end{lstlisting}
  2275. \end{tcolorbox}
  2276. \end{minipage}
  2277. \caption{An x86 program that computes
  2278. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2279. \label{fig:p0-x86}
  2280. \end{figure}
  2281. We exhibit the use of memory for storing intermediate results in the
  2282. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2283. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2284. uses a region of memory called the \emph{procedure call stack}
  2285. (\emph{stack} for
  2286. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2287. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2288. for each procedure call. The memory layout for an individual frame is
  2289. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2290. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2291. address of the item at the top of the stack. In general, we use the
  2292. term \emph{pointer}\index{subject}{pointer} for something that
  2293. contains an address. The stack grows downward in memory, so we
  2294. increase the size of the stack by subtracting from the stack pointer.
  2295. In the context of a procedure call, the \emph{return
  2296. address}\index{subject}{return address} is the location of the
  2297. instruction that immediately follows the call instruction on the
  2298. caller side. The function call instruction, \code{callq}, pushes the
  2299. return address onto the stack prior to jumping to the procedure. The
  2300. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2301. pointer} and is used to access variables that are stored in the
  2302. frame of the current procedure call. The base pointer of the caller
  2303. is stored immediately after the return address.
  2304. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2305. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2306. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2307. $-16\key{(\%rbp)}$, and so on.
  2308. \begin{figure}[tbp]
  2309. \begin{minipage}{0.66\textwidth}
  2310. \begin{tcolorbox}[colback=white]
  2311. {\if\edition\racketEd
  2312. \begin{lstlisting}
  2313. start:
  2314. movq $10, -8(%rbp)
  2315. negq -8(%rbp)
  2316. movq -8(%rbp), %rax
  2317. addq $52, %rax
  2318. jmp conclusion
  2319. .globl main
  2320. main:
  2321. pushq %rbp
  2322. movq %rsp, %rbp
  2323. subq $16, %rsp
  2324. jmp start
  2325. conclusion:
  2326. addq $16, %rsp
  2327. popq %rbp
  2328. retq
  2329. \end{lstlisting}
  2330. \fi}
  2331. {\if\edition\pythonEd\pythonColor
  2332. \begin{lstlisting}
  2333. .globl main
  2334. main:
  2335. pushq %rbp
  2336. movq %rsp, %rbp
  2337. subq $16, %rsp
  2338. movq $10, -8(%rbp)
  2339. negq -8(%rbp)
  2340. movq -8(%rbp), %rax
  2341. addq $52, %rax
  2342. addq $16, %rsp
  2343. popq %rbp
  2344. retq
  2345. \end{lstlisting}
  2346. \fi}
  2347. \end{tcolorbox}
  2348. \end{minipage}
  2349. \caption{An x86 program that computes
  2350. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2351. \label{fig:p1-x86}
  2352. \end{figure}
  2353. \begin{figure}[tbp]
  2354. \begin{minipage}{0.66\textwidth}
  2355. \begin{tcolorbox}[colback=white]
  2356. \centering
  2357. \begin{tabular}{|r|l|} \hline
  2358. Position & Contents \\ \hline
  2359. $8$(\key{\%rbp}) & return address \\
  2360. $0$(\key{\%rbp}) & old \key{rbp} \\
  2361. $-8$(\key{\%rbp}) & variable $1$ \\
  2362. $-16$(\key{\%rbp}) & variable $2$ \\
  2363. \ldots & \ldots \\
  2364. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2365. \end{tabular}
  2366. \end{tcolorbox}
  2367. \end{minipage}
  2368. \caption{Memory layout of a frame.}
  2369. \label{fig:frame}
  2370. \end{figure}
  2371. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2372. is transferred from the operating system to the \code{main} function.
  2373. The operating system issues a \code{callq main} instruction that
  2374. pushes its return address on the stack and then jumps to
  2375. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2376. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2377. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2378. out of alignment (because the \code{callq} pushed the return address).
  2379. The first three instructions are the typical
  2380. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2381. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2382. pointer \code{rsp} and then saves the base pointer of the caller at
  2383. address \code{rsp} on the stack. The next instruction \code{movq
  2384. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2385. which is pointing to the location of the old base pointer. The
  2386. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2387. make enough room for storing variables. This program needs one
  2388. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2389. 16-byte-aligned, and then we are ready to make calls to other functions.
  2390. \racket{The last instruction of the prelude is \code{jmp start}, which
  2391. transfers control to the instructions that were generated from the
  2392. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2393. \racket{The first instruction under the \code{start} label is}
  2394. %
  2395. \python{The first instruction after the prelude is}
  2396. %
  2397. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2398. %
  2399. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2400. $1$ to $-10$.
  2401. %
  2402. The next instruction moves the $-10$ from variable $1$ into the
  2403. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2404. the value in \code{rax}, updating its contents to $42$.
  2405. \racket{The three instructions under the label \code{conclusion} are the
  2406. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2407. %
  2408. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2409. \code{main} function consists of the last three instructions.}
  2410. %
  2411. The first two restore the \code{rsp} and \code{rbp} registers to their
  2412. states at the beginning of the procedure. In particular,
  2413. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2414. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2415. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2416. \key{retq}, jumps back to the procedure that called this one and adds
  2417. $8$ to the stack pointer.
  2418. Our compiler needs a convenient representation for manipulating x86
  2419. programs, so we define an abstract syntax for x86, shown in
  2420. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2421. \LangXInt{}.
  2422. %
  2423. {\if\edition\pythonEd\pythonColor%
  2424. The main difference between this and the concrete syntax of \LangXInt{}
  2425. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2426. names, and register names are explicitly represented by strings.
  2427. \fi} %
  2428. {\if\edition\racketEd
  2429. The main difference between this and the concrete syntax of \LangXInt{}
  2430. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2431. front of every instruction. Instead instructions are grouped into
  2432. \emph{basic blocks}\index{subject}{basic block} with a
  2433. label associated with every basic block; this is why the \key{X86Program}
  2434. struct includes an alist mapping labels to basic blocks. The reason for this
  2435. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2436. introduce conditional branching. The \code{Block} structure includes
  2437. an $\itm{info}$ field that is not needed in this chapter but becomes
  2438. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2439. $\itm{info}$ field should contain an empty list.
  2440. \fi}
  2441. %
  2442. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2443. node includes an integer for representing the arity of the function,
  2444. that is, the number of arguments, which is helpful to know during
  2445. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2446. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2447. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2448. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2449. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2450. \MID \skey{r14} \MID \skey{r15}}
  2451. \newcommand{\ASTXIntRacket}{
  2452. \begin{array}{lcl}
  2453. \Reg &::=& \allregisters{} \\
  2454. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2455. \MID \DEREF{\Reg}{\Int} \\
  2456. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2457. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2458. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2459. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2460. &\MID& \PUSHQ{\Arg}
  2461. \MID \POPQ{\Arg} \\
  2462. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2463. \MID \RETQ{}
  2464. \MID \JMP{\itm{label}} \\
  2465. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2466. \end{array}
  2467. }
  2468. \begin{figure}[tp]
  2469. \begin{tcolorbox}[colback=white]
  2470. \small
  2471. {\if\edition\racketEd
  2472. \[\arraycolsep=3pt
  2473. \begin{array}{l}
  2474. \ASTXIntRacket \\
  2475. \begin{array}{lcl}
  2476. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2477. \end{array}
  2478. \end{array}
  2479. \]
  2480. \fi}
  2481. {\if\edition\pythonEd\pythonColor
  2482. \[
  2483. \begin{array}{lcl}
  2484. \Reg &::=& \allastregisters{} \\
  2485. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2486. \MID \DEREF{\Reg}{\Int} \\
  2487. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2488. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2489. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2490. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2491. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2492. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2493. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2494. \end{array}
  2495. \]
  2496. \fi}
  2497. \end{tcolorbox}
  2498. \caption{The abstract syntax of \LangXInt{} assembly.}
  2499. \label{fig:x86-int-ast}
  2500. \end{figure}
  2501. \section{Planning the Trip to x86}
  2502. \label{sec:plan-s0-x86}
  2503. To compile one language to another, it helps to focus on the
  2504. differences between the two languages because the compiler will need
  2505. to bridge those differences. What are the differences between \LangVar{}
  2506. and x86 assembly? Here are some of the most important ones:
  2507. \begin{enumerate}
  2508. \item x86 arithmetic instructions typically have two arguments and
  2509. update the second argument in place. In contrast, \LangVar{}
  2510. arithmetic operations take two arguments and produce a new value.
  2511. An x86 instruction may have at most one memory-accessing argument.
  2512. Furthermore, some x86 instructions place special restrictions on
  2513. their arguments.
  2514. \item An argument of an \LangVar{} operator can be a deeply nested
  2515. expression, whereas x86 instructions restrict their arguments to be
  2516. integer constants, registers, and memory locations.
  2517. {\if\edition\racketEd
  2518. \item The order of execution in x86 is explicit in the syntax, which
  2519. is a sequence of instructions and jumps to labeled positions,
  2520. whereas in \LangVar{} the order of evaluation is a left-to-right
  2521. depth-first traversal of the abstract syntax tree. \fi}
  2522. \item A program in \LangVar{} can have any number of variables,
  2523. whereas x86 has 16 registers and the procedure call stack.
  2524. {\if\edition\racketEd
  2525. \item Variables in \LangVar{} can shadow other variables with the
  2526. same name. In x86, registers have unique names, and memory locations
  2527. have unique addresses.
  2528. \fi}
  2529. \end{enumerate}
  2530. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2531. down the problem into several steps, which deal with these differences
  2532. one at a time. Each of these steps is called a \emph{pass} of the
  2533. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2534. %
  2535. This term indicates that each step passes over, or traverses, the AST
  2536. of the program.
  2537. %
  2538. Furthermore, we follow the nanopass approach, which means that we
  2539. strive for each pass to accomplish one clear objective rather than two
  2540. or three at the same time.
  2541. %
  2542. We begin by sketching how we might implement each pass and give each
  2543. pass a name. We then figure out an ordering of the passes and the
  2544. input/output language for each pass. The very first pass has
  2545. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2546. its output language. In between these two passes, we can choose
  2547. whichever language is most convenient for expressing the output of
  2548. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2549. \emph{intermediate languages} of our own design. Finally, to
  2550. implement each pass we write one recursive function per nonterminal in
  2551. the grammar of the input language of the pass.
  2552. \index{subject}{intermediate language}
  2553. Our compiler for \LangVar{} consists of the following passes:
  2554. %
  2555. \begin{description}
  2556. {\if\edition\racketEd
  2557. \item[\key{uniquify}] deals with the shadowing of variables by
  2558. renaming every variable to a unique name.
  2559. \fi}
  2560. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2561. of a primitive operation or function call is a variable or integer,
  2562. that is, an \emph{atomic} expression. We refer to nonatomic
  2563. expressions as \emph{complex}. This pass introduces temporary
  2564. variables to hold the results of complex
  2565. subexpressions.\index{subject}{atomic
  2566. expression}\index{subject}{complex expression}%
  2567. {\if\edition\racketEd
  2568. \item[\key{explicate\_control}] makes the execution order of the
  2569. program explicit. It converts the abstract syntax tree
  2570. representation into a graph in which each node is a labeled sequence
  2571. of statements and the edges are \code{goto} statements.
  2572. \fi}
  2573. \item[\key{select\_instructions}] handles the difference between
  2574. \LangVar{} operations and x86 instructions. This pass converts each
  2575. \LangVar{} operation to a short sequence of instructions that
  2576. accomplishes the same task.
  2577. \item[\key{assign\_homes}] replaces variables with registers or stack
  2578. locations.
  2579. \end{description}
  2580. %
  2581. {\if\edition\racketEd
  2582. %
  2583. Our treatment of \code{remove\_complex\_operands} and
  2584. \code{explicate\_control} as separate passes is an example of the
  2585. nanopass approach\footnote{For analogous decompositions of the
  2586. translation into continuation passing style, see the work of
  2587. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2588. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2589. %
  2590. \fi}
  2591. The next question is, in what order should we apply these passes? This
  2592. question can be challenging because it is difficult to know ahead of
  2593. time which orderings will be better (that is, will be easier to
  2594. implement, produce more efficient code, and so on), and therefore
  2595. ordering often involves trial and error. Nevertheless, we can plan
  2596. ahead and make educated choices regarding the ordering.
  2597. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2598. \key{uniquify}? The \key{uniquify} pass should come first because
  2599. \key{explicate\_control} changes all the \key{let}-bound variables to
  2600. become local variables whose scope is the entire program, which would
  2601. confuse variables with the same name.}
  2602. %
  2603. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2604. because the later removes the \key{let} form, but it is convenient to
  2605. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2606. %
  2607. \racket{The ordering of \key{uniquify} with respect to
  2608. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2609. \key{uniquify} to come first.}
  2610. The \key{select\_instructions} and \key{assign\_homes} passes are
  2611. intertwined.
  2612. %
  2613. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2614. passing arguments to functions and that it is preferable to assign
  2615. parameters to their corresponding registers. This suggests that it
  2616. would be better to start with the \key{select\_instructions} pass,
  2617. which generates the instructions for argument passing, before
  2618. performing register allocation.
  2619. %
  2620. On the other hand, by selecting instructions first we may run into a
  2621. dead end in \key{assign\_homes}. Recall that only one argument of an
  2622. x86 instruction may be a memory access, but \key{assign\_homes} might
  2623. be forced to assign both arguments to memory locations.
  2624. %
  2625. A sophisticated approach is to repeat the two passes until a solution
  2626. is found. However, to reduce implementation complexity we recommend
  2627. placing \key{select\_instructions} first, followed by the
  2628. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2629. that uses a reserved register to fix outstanding problems.
  2630. \begin{figure}[tbp]
  2631. \begin{tcolorbox}[colback=white]
  2632. {\if\edition\racketEd
  2633. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2634. \node (Lvar) at (0,2) {\large \LangVar{}};
  2635. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2636. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2637. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2638. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2639. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2640. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2641. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2642. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2643. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2644. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2645. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2646. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2647. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2648. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2649. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2650. \end{tikzpicture}
  2651. \fi}
  2652. {\if\edition\pythonEd\pythonColor
  2653. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2654. \node (Lvar) at (0,2) {\large \LangVar{}};
  2655. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2656. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2657. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2658. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2659. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2660. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2661. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2662. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2663. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2664. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2665. \end{tikzpicture}
  2666. \fi}
  2667. \end{tcolorbox}
  2668. \caption{Diagram of the passes for compiling \LangVar{}. }
  2669. \label{fig:Lvar-passes}
  2670. \end{figure}
  2671. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2672. passes and identifies the input and output language of each pass.
  2673. %
  2674. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2675. language, which extends \LangXInt{} with an unbounded number of
  2676. program-scope variables and removes the restrictions regarding
  2677. instruction arguments.
  2678. %
  2679. The last pass, \key{prelude\_and\_conclusion}, places the program
  2680. instructions inside a \code{main} function with instructions for the
  2681. prelude and conclusion.
  2682. %
  2683. \racket{In the next section we discuss the \LangCVar{} intermediate
  2684. language that serves as the output of \code{explicate\_control}.}
  2685. %
  2686. The remainder of this chapter provides guidance on the implementation
  2687. of each of the compiler passes represented in
  2688. figure~\ref{fig:Lvar-passes}.
  2689. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2690. %% are programs that are still in the \LangVar{} language, though the
  2691. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2692. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2693. %% %
  2694. %% The output of \code{explicate\_control} is in an intermediate language
  2695. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2696. %% syntax, which we introduce in the next section. The
  2697. %% \key{select-instruction} pass translates from \LangCVar{} to
  2698. %% \LangXVar{}. The \key{assign-homes} and
  2699. %% \key{patch-instructions}
  2700. %% passes input and output variants of x86 assembly.
  2701. \newcommand{\CvarGrammarRacket}{
  2702. \begin{array}{lcl}
  2703. \Atm &::=& \Int \MID \Var \\
  2704. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2705. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2706. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2707. \end{array}
  2708. }
  2709. \newcommand{\CvarASTRacket}{
  2710. \begin{array}{lcl}
  2711. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2712. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2713. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2714. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2715. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2716. \end{array}
  2717. }
  2718. {\if\edition\racketEd
  2719. \subsection{The \LangCVar{} Intermediate Language}
  2720. The output of \code{explicate\_control} is similar to the C
  2721. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2722. categories for expressions and statements, so we name it \LangCVar{}.
  2723. This style of intermediate language is also known as
  2724. \emph{three-address code}, to emphasize that the typical form of a
  2725. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2726. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2727. The concrete syntax for \LangCVar{} is shown in
  2728. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2729. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2730. %
  2731. The \LangCVar{} language supports the same operators as \LangVar{} but
  2732. the arguments of operators are restricted to atomic
  2733. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2734. assignment statements that can be executed in sequence using the
  2735. \key{Seq} form. A sequence of statements always ends with
  2736. \key{Return}, a guarantee that is baked into the grammar rules for
  2737. \itm{tail}. The naming of this nonterminal comes from the term
  2738. \emph{tail position}\index{subject}{tail position}, which refers to an
  2739. expression that is the last one to execute within a function or
  2740. program.
  2741. A \LangCVar{} program consists of an alist mapping labels to
  2742. tails. This is more general than necessary for the present chapter, as
  2743. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2744. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2745. there is just one label, \key{start}, and the whole program is
  2746. its tail.
  2747. %
  2748. The $\itm{info}$ field of the \key{CProgram} form, after the
  2749. \code{explicate\_control} pass, contains an alist that associates the
  2750. symbol \key{locals} with a list of all the variables used in the
  2751. program. At the start of the program, these variables are
  2752. uninitialized; they become initialized on their first assignment.
  2753. \begin{figure}[tbp]
  2754. \begin{tcolorbox}[colback=white]
  2755. \[
  2756. \begin{array}{l}
  2757. \CvarGrammarRacket \\
  2758. \begin{array}{lcl}
  2759. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2760. \end{array}
  2761. \end{array}
  2762. \]
  2763. \end{tcolorbox}
  2764. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2765. \label{fig:c0-concrete-syntax}
  2766. \end{figure}
  2767. \begin{figure}[tbp]
  2768. \begin{tcolorbox}[colback=white]
  2769. \[
  2770. \begin{array}{l}
  2771. \CvarASTRacket \\
  2772. \begin{array}{lcl}
  2773. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2774. \end{array}
  2775. \end{array}
  2776. \]
  2777. \end{tcolorbox}
  2778. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2779. \label{fig:c0-syntax}
  2780. \end{figure}
  2781. The definitional interpreter for \LangCVar{} is in the support code,
  2782. in the file \code{interp-Cvar.rkt}.
  2783. \fi}
  2784. {\if\edition\racketEd
  2785. \section{Uniquify Variables}
  2786. \label{sec:uniquify-Lvar}
  2787. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2788. programs in which every \key{let} binds a unique variable name. For
  2789. example, the \code{uniquify} pass should translate the program on the
  2790. left into the program on the right.
  2791. \begin{transformation}
  2792. \begin{lstlisting}
  2793. (let ([x 32])
  2794. (+ (let ([x 10]) x) x))
  2795. \end{lstlisting}
  2796. \compilesto
  2797. \begin{lstlisting}
  2798. (let ([x.1 32])
  2799. (+ (let ([x.2 10]) x.2) x.1))
  2800. \end{lstlisting}
  2801. \end{transformation}
  2802. The following is another example translation, this time of a program
  2803. with a \key{let} nested inside the initializing expression of another
  2804. \key{let}.
  2805. \begin{transformation}
  2806. \begin{lstlisting}
  2807. (let ([x (let ([x 4])
  2808. (+ x 1))])
  2809. (+ x 2))
  2810. \end{lstlisting}
  2811. \compilesto
  2812. \begin{lstlisting}
  2813. (let ([x.2 (let ([x.1 4])
  2814. (+ x.1 1))])
  2815. (+ x.2 2))
  2816. \end{lstlisting}
  2817. \end{transformation}
  2818. We recommend implementing \code{uniquify} by creating a structurally
  2819. recursive function named \code{uniquify\_exp} that does little other
  2820. than copy an expression. However, when encountering a \key{let}, it
  2821. should generate a unique name for the variable and associate the old
  2822. name with the new name in an alist.\footnote{The Racket function
  2823. \code{gensym} is handy for generating unique variable names.} The
  2824. \code{uniquify\_exp} function needs to access this alist when it gets
  2825. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2826. for the alist.
  2827. The skeleton of the \code{uniquify\_exp} function is shown in
  2828. figure~\ref{fig:uniquify-Lvar}.
  2829. %% The function is curried so that it is
  2830. %% convenient to partially apply it to an alist and then apply it to
  2831. %% different expressions, as in the last case for primitive operations in
  2832. %% figure~\ref{fig:uniquify-Lvar}.
  2833. The
  2834. %
  2835. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2836. %
  2837. form of Racket is useful for transforming the element of a list to
  2838. produce a new list.\index{subject}{for/list}
  2839. \begin{figure}[tbp]
  2840. \begin{tcolorbox}[colback=white]
  2841. \begin{lstlisting}
  2842. (define (uniquify_exp env)
  2843. (lambda (e)
  2844. (match e
  2845. [(Var x) ___]
  2846. [(Int n) (Int n)]
  2847. [(Let x e body) ___]
  2848. [(Prim op es)
  2849. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2850. (define (uniquify p)
  2851. (match p
  2852. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2853. \end{lstlisting}
  2854. \end{tcolorbox}
  2855. \caption{Skeleton for the \key{uniquify} pass.}
  2856. \label{fig:uniquify-Lvar}
  2857. \end{figure}
  2858. \begin{exercise}
  2859. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2860. Complete the \code{uniquify} pass by filling in the blanks in
  2861. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2862. variables and for the \key{let} form in the file \code{compiler.rkt}
  2863. in the support code.
  2864. \end{exercise}
  2865. \begin{exercise}
  2866. \normalfont\normalsize
  2867. \label{ex:Lvar}
  2868. Create five \LangVar{} programs that exercise the most interesting
  2869. parts of the \key{uniquify} pass; that is, the programs should include
  2870. \key{let} forms, variables, and variables that shadow each other.
  2871. The five programs should be placed in the subdirectory named
  2872. \key{tests}, and the file names should start with \code{var\_test\_}
  2873. followed by a unique integer and end with the file extension
  2874. \key{.rkt}.
  2875. %
  2876. The \key{run-tests.rkt} script in the support code checks whether the
  2877. output programs produce the same result as the input programs. The
  2878. script uses the \key{interp-tests} function
  2879. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2880. your \key{uniquify} pass on the example programs. The \code{passes}
  2881. parameter of \key{interp-tests} is a list that should have one entry
  2882. for each pass in your compiler. For now, define \code{passes} to
  2883. contain just one entry for \code{uniquify} as follows:
  2884. \begin{lstlisting}
  2885. (define passes
  2886. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2887. \end{lstlisting}
  2888. Run the \key{run-tests.rkt} script in the support code to check
  2889. whether the output programs produce the same result as the input
  2890. programs.
  2891. \end{exercise}
  2892. \fi}
  2893. \section{Remove Complex Operands}
  2894. \label{sec:remove-complex-opera-Lvar}
  2895. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2896. into a restricted form in which the arguments of operations are atomic
  2897. expressions. Put another way, this pass removes complex
  2898. operands\index{subject}{complex operand}, such as the expression
  2899. \racket{\code{(- 10)}}\python{\code{-10}}
  2900. in the following program. This is accomplished by introducing a new
  2901. temporary variable, assigning the complex operand to the new
  2902. variable, and then using the new variable in place of the complex
  2903. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2904. right.
  2905. {\if\edition\racketEd
  2906. \begin{transformation}
  2907. % var_test_19.rkt
  2908. \begin{lstlisting}
  2909. (let ([x (+ 42 (- 10))])
  2910. (+ x 10))
  2911. \end{lstlisting}
  2912. \compilesto
  2913. \begin{lstlisting}
  2914. (let ([x (let ([tmp.1 (- 10)])
  2915. (+ 42 tmp.1))])
  2916. (+ x 10))
  2917. \end{lstlisting}
  2918. \end{transformation}
  2919. \fi}
  2920. {\if\edition\pythonEd\pythonColor
  2921. \begin{transformation}
  2922. \begin{lstlisting}
  2923. x = 42 + -10
  2924. print(x + 10)
  2925. \end{lstlisting}
  2926. \compilesto
  2927. \begin{lstlisting}
  2928. tmp_0 = -10
  2929. x = 42 + tmp_0
  2930. tmp_1 = x + 10
  2931. print(tmp_1)
  2932. \end{lstlisting}
  2933. \end{transformation}
  2934. \fi}
  2935. \newcommand{\LvarMonadASTRacket}{
  2936. \begin{array}{rcl}
  2937. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2938. \Exp &::=& \Atm \MID \READ{} \\
  2939. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2940. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2941. \end{array}
  2942. }
  2943. \newcommand{\LvarMonadASTPython}{
  2944. \begin{array}{rcl}
  2945. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2946. \Exp{} &::=& \Atm \MID \READ{} \\
  2947. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2948. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2949. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2950. \end{array}
  2951. }
  2952. \begin{figure}[tp]
  2953. \centering
  2954. \begin{tcolorbox}[colback=white]
  2955. {\if\edition\racketEd
  2956. \[
  2957. \begin{array}{l}
  2958. \LvarMonadASTRacket \\
  2959. \begin{array}{rcl}
  2960. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2961. \end{array}
  2962. \end{array}
  2963. \]
  2964. \fi}
  2965. {\if\edition\pythonEd\pythonColor
  2966. \[
  2967. \begin{array}{l}
  2968. \LvarMonadASTPython \\
  2969. \begin{array}{rcl}
  2970. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2971. \end{array}
  2972. \end{array}
  2973. \]
  2974. \fi}
  2975. \end{tcolorbox}
  2976. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2977. atomic expressions.}
  2978. \label{fig:Lvar-anf-syntax}
  2979. \end{figure}
  2980. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2981. of this pass, the language \LangVarANF{}. The only difference is that
  2982. operator arguments are restricted to be atomic expressions that are
  2983. defined by the \Atm{} nonterminal. In particular, integer constants
  2984. and variables are atomic.
  2985. The atomic expressions are pure (they do not cause or depend on side
  2986. effects) whereas complex expressions may have side effects, such as
  2987. \READ{}. A language with this separation between pure expression
  2988. versus expressions with side effects is said to be in monadic normal
  2989. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2990. in the name \LangVarANF{}. An important invariant of the
  2991. \code{remove\_complex\_operands} pass is that the relative ordering
  2992. among complex expressions is not changed, but the relative ordering
  2993. between atomic expressions and complex expressions can change and
  2994. often does. The reason that these changes are behavior preserving is
  2995. that the atomic expressions are pure.
  2996. Another well-known form for intermediate languages is the
  2997. \emph{administrative normal form}
  2998. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2999. \index{subject}{administrative normal form} \index{subject}{ANF}
  3000. %
  3001. The \LangVarANF{} language is not quite in ANF because we allow the
  3002. right-hand side of a \code{let} to be a complex expression.
  3003. {\if\edition\racketEd
  3004. We recommend implementing this pass with two mutually recursive
  3005. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3006. \code{rco\_atom} to subexpressions that need to become atomic and to
  3007. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3008. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3009. returns an expression. The \code{rco\_atom} function returns two
  3010. things: an atomic expression and an alist mapping temporary variables to
  3011. complex subexpressions. You can return multiple things from a function
  3012. using Racket's \key{values} form, and you can receive multiple things
  3013. from a function call using the \key{define-values} form.
  3014. \fi}
  3015. %
  3016. {\if\edition\pythonEd\pythonColor
  3017. %
  3018. We recommend implementing this pass with an auxiliary method named
  3019. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3020. Boolean that specifies whether the expression needs to become atomic
  3021. or not. The \code{rco\_exp} method should return a pair consisting of
  3022. the new expression and a list of pairs, associating new temporary
  3023. variables with their initializing expressions.
  3024. %
  3025. \fi}
  3026. {\if\edition\racketEd
  3027. %
  3028. Returning to the example program with the expression \code{(+ 42 (-
  3029. 10))}, the subexpression \code{(- 10)} should be processed using the
  3030. \code{rco\_atom} function because it is an argument of the \code{+}
  3031. operator and therefore needs to become atomic. The output of
  3032. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3033. \begin{transformation}
  3034. \begin{lstlisting}
  3035. (- 10)
  3036. \end{lstlisting}
  3037. \compilesto
  3038. \begin{lstlisting}
  3039. tmp.1
  3040. ((tmp.1 . (- 10)))
  3041. \end{lstlisting}
  3042. \end{transformation}
  3043. \fi}
  3044. %
  3045. {\if\edition\pythonEd\pythonColor
  3046. %
  3047. Returning to the example program with the expression \code{42 + -10},
  3048. the subexpression \code{-10} should be processed using the
  3049. \code{rco\_exp} function with \code{True} as the second argument
  3050. because \code{-10} is an argument of the \code{+} operator and
  3051. therefore needs to become atomic. The output of \code{rco\_exp}
  3052. applied to \code{-10} is as follows.
  3053. \begin{transformation}
  3054. \begin{lstlisting}
  3055. -10
  3056. \end{lstlisting}
  3057. \compilesto
  3058. \begin{lstlisting}
  3059. tmp_1
  3060. [(tmp_1, -10)]
  3061. \end{lstlisting}
  3062. \end{transformation}
  3063. %
  3064. \fi}
  3065. Take special care of programs, such as the following, that
  3066. %
  3067. \racket{bind a variable to an atomic expression.}
  3068. %
  3069. \python{assign an atomic expression to a variable.}
  3070. %
  3071. You should leave such \racket{variable bindings}\python{assignments}
  3072. unchanged, as shown in the program on the right\\
  3073. %
  3074. {\if\edition\racketEd
  3075. \begin{transformation}
  3076. % var_test_20.rkt
  3077. \begin{lstlisting}
  3078. (let ([a 42])
  3079. (let ([b a])
  3080. b))
  3081. \end{lstlisting}
  3082. \compilesto
  3083. \begin{lstlisting}
  3084. (let ([a 42])
  3085. (let ([b a])
  3086. b))
  3087. \end{lstlisting}
  3088. \end{transformation}
  3089. \fi}
  3090. {\if\edition\pythonEd\pythonColor
  3091. \begin{transformation}
  3092. \begin{lstlisting}
  3093. a = 42
  3094. b = a
  3095. print(b)
  3096. \end{lstlisting}
  3097. \compilesto
  3098. \begin{lstlisting}
  3099. a = 42
  3100. b = a
  3101. print(b)
  3102. \end{lstlisting}
  3103. \end{transformation}
  3104. \fi}
  3105. %
  3106. \noindent A careless implementation might produce the following output with
  3107. unnecessary temporary variables.
  3108. \begin{center}
  3109. \begin{minipage}{0.4\textwidth}
  3110. {\if\edition\racketEd
  3111. \begin{lstlisting}
  3112. (let ([tmp.1 42])
  3113. (let ([a tmp.1])
  3114. (let ([tmp.2 a])
  3115. (let ([b tmp.2])
  3116. b))))
  3117. \end{lstlisting}
  3118. \fi}
  3119. {\if\edition\pythonEd\pythonColor
  3120. \begin{lstlisting}
  3121. tmp_1 = 42
  3122. a = tmp_1
  3123. tmp_2 = a
  3124. b = tmp_2
  3125. print(b)
  3126. \end{lstlisting}
  3127. \fi}
  3128. \end{minipage}
  3129. \end{center}
  3130. \begin{exercise}
  3131. \normalfont\normalsize
  3132. {\if\edition\racketEd
  3133. Implement the \code{remove\_complex\_operands} function in
  3134. \code{compiler.rkt}.
  3135. %
  3136. Create three new \LangVar{} programs that exercise the interesting
  3137. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3138. regarding file names described in exercise~\ref{ex:Lvar}.
  3139. %
  3140. In the \code{run-tests.rkt} script, add the following entry to the
  3141. list of \code{passes}, and then run the script to test your compiler.
  3142. \begin{lstlisting}
  3143. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3144. \end{lstlisting}
  3145. In debugging your compiler, it is often useful to see the intermediate
  3146. programs that are output from each pass. To print the intermediate
  3147. programs, place \lstinline{(debug-level 1)} before the call to
  3148. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3149. %
  3150. {\if\edition\pythonEd\pythonColor
  3151. Implement the \code{remove\_complex\_operands} pass in
  3152. \code{compiler.py}, creating auxiliary functions for each
  3153. nonterminal in the grammar, i.e., \code{rco\_exp}
  3154. and \code{rco\_stmt}. We recommend you use the function
  3155. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3156. \fi}
  3157. \end{exercise}
  3158. {\if\edition\pythonEd\pythonColor
  3159. \begin{exercise}
  3160. \normalfont\normalsize
  3161. \label{ex:Lvar}
  3162. Create five \LangVar{} programs that exercise the most interesting
  3163. parts of the \code{remove\_complex\_operands} pass. The five programs
  3164. should be placed in the subdirectory named \key{tests}, and the file
  3165. names should start with \code{var\_test\_} followed by a unique
  3166. integer and end with the file extension \key{.py}.
  3167. %% The \key{run-tests.rkt} script in the support code checks whether the
  3168. %% output programs produce the same result as the input programs. The
  3169. %% script uses the \key{interp-tests} function
  3170. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3171. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3172. %% parameter of \key{interp-tests} is a list that should have one entry
  3173. %% for each pass in your compiler. For now, define \code{passes} to
  3174. %% contain just one entry for \code{uniquify} as shown below.
  3175. %% \begin{lstlisting}
  3176. %% (define passes
  3177. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3178. %% \end{lstlisting}
  3179. Run the \key{run-tests.py} script in the support code to check
  3180. whether the output programs produce the same result as the input
  3181. programs.
  3182. \end{exercise}
  3183. \fi}
  3184. {\if\edition\racketEd
  3185. \section{Explicate Control}
  3186. \label{sec:explicate-control-Lvar}
  3187. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3188. programs that make the order of execution explicit in their
  3189. syntax. For now this amounts to flattening \key{let} constructs into a
  3190. sequence of assignment statements. For example, consider the following
  3191. \LangVar{} program:\\
  3192. % var_test_11.rkt
  3193. \begin{minipage}{0.96\textwidth}
  3194. \begin{lstlisting}
  3195. (let ([y (let ([x 20])
  3196. (+ x (let ([x 22]) x)))])
  3197. y)
  3198. \end{lstlisting}
  3199. \end{minipage}\\
  3200. %
  3201. The output of the previous pass is shown next, on the left, and the
  3202. output of \code{explicate\_control} is on the right. Recall that the
  3203. right-hand side of a \key{let} executes before its body, so that the order
  3204. of evaluation for this program is to assign \code{20} to \code{x.1},
  3205. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3206. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3207. this ordering explicit.
  3208. \begin{transformation}
  3209. \begin{lstlisting}
  3210. (let ([y (let ([x.1 20])
  3211. (let ([x.2 22])
  3212. (+ x.1 x.2)))])
  3213. y)
  3214. \end{lstlisting}
  3215. \compilesto
  3216. \begin{lstlisting}[language=C]
  3217. start:
  3218. x.1 = 20;
  3219. x.2 = 22;
  3220. y = (+ x.1 x.2);
  3221. return y;
  3222. \end{lstlisting}
  3223. \end{transformation}
  3224. \begin{figure}[tbp]
  3225. \begin{tcolorbox}[colback=white]
  3226. \begin{lstlisting}
  3227. (define (explicate_tail e)
  3228. (match e
  3229. [(Var x) ___]
  3230. [(Int n) (Return (Int n))]
  3231. [(Let x rhs body) ___]
  3232. [(Prim op es) ___]
  3233. [else (error "explicate_tail unhandled case" e)]))
  3234. (define (explicate_assign e x cont)
  3235. (match e
  3236. [(Var x) ___]
  3237. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3238. [(Let y rhs body) ___]
  3239. [(Prim op es) ___]
  3240. [else (error "explicate_assign unhandled case" e)]))
  3241. (define (explicate_control p)
  3242. (match p
  3243. [(Program info body) ___]))
  3244. \end{lstlisting}
  3245. \end{tcolorbox}
  3246. \caption{Skeleton for the \code{explicate\_control} pass.}
  3247. \label{fig:explicate-control-Lvar}
  3248. \end{figure}
  3249. The organization of this pass depends on the notion of tail position
  3250. to which we have alluded. Here is the definition.
  3251. \begin{definition}\normalfont
  3252. The following rules define when an expression is in \emph{tail
  3253. position}\index{subject}{tail position} for the language \LangVar{}.
  3254. \begin{enumerate}
  3255. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3256. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3257. \end{enumerate}
  3258. \end{definition}
  3259. We recommend implementing \code{explicate\_control} using two
  3260. recursive functions, \code{explicate\_tail} and
  3261. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3262. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3263. function should be applied to expressions in tail position, whereas the
  3264. \code{explicate\_assign} should be applied to expressions that occur on
  3265. the right-hand side of a \key{let}.
  3266. %
  3267. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3268. input and produces a \Tail{} in \LangCVar{} (see
  3269. figure~\ref{fig:c0-syntax}).
  3270. %
  3271. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3272. the variable to which it is to be assigned to, and a \Tail{} in
  3273. \LangCVar{} for the code that comes after the assignment. The
  3274. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3275. The \code{explicate\_assign} function is in accumulator-passing style:
  3276. the \code{cont} parameter is used for accumulating the output. This
  3277. accumulator-passing style plays an important role in the way that we
  3278. generate high-quality code for conditional expressions in
  3279. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3280. continuation because it contains the generated code that should come
  3281. after the current assignment. This code organization is also related
  3282. to continuation-passing style, except that \code{cont} is not what
  3283. happens next during compilation but is what happens next in the
  3284. generated code.
  3285. \begin{exercise}\normalfont\normalsize
  3286. %
  3287. Implement the \code{explicate\_control} function in
  3288. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3289. exercise the code in \code{explicate\_control}.
  3290. %
  3291. In the \code{run-tests.rkt} script, add the following entry to the
  3292. list of \code{passes} and then run the script to test your compiler.
  3293. \begin{lstlisting}
  3294. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3295. \end{lstlisting}
  3296. \end{exercise}
  3297. \fi}
  3298. \section{Select Instructions}
  3299. \label{sec:select-Lvar}
  3300. \index{subject}{instruction selection}
  3301. In the \code{select\_instructions} pass we begin the work of
  3302. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3303. language of this pass is a variant of x86 that still uses variables,
  3304. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3305. nonterminal of the \LangXInt{} abstract syntax
  3306. (figure~\ref{fig:x86-int-ast}).
  3307. \racket{We recommend implementing the
  3308. \code{select\_instructions} with three auxiliary functions, one for
  3309. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3310. $\Tail$.}
  3311. \python{We recommend implementing an auxiliary function
  3312. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3313. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3314. same and integer constants change to immediates; that is, $\INT{n}$
  3315. changes to $\IMM{n}$.}
  3316. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3317. arithmetic operations. For example, consider the following addition
  3318. operation, on the left side. There is an \key{addq} instruction in
  3319. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3320. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3321. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3322. $\Atm_2$, respectively.
  3323. \begin{transformation}
  3324. {\if\edition\racketEd
  3325. \begin{lstlisting}
  3326. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3327. \end{lstlisting}
  3328. \fi}
  3329. {\if\edition\pythonEd\pythonColor
  3330. \begin{lstlisting}
  3331. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3332. \end{lstlisting}
  3333. \fi}
  3334. \compilesto
  3335. \begin{lstlisting}
  3336. movq |$\Arg_1$|, |$\itm{var}$|
  3337. addq |$\Arg_2$|, |$\itm{var}$|
  3338. \end{lstlisting}
  3339. \end{transformation}
  3340. There are also cases that require special care to avoid generating
  3341. needlessly complicated code. For example, if one of the arguments of
  3342. the addition is the same variable as the left-hand side of the
  3343. assignment, as shown next, then there is no need for the extra move
  3344. instruction. The assignment statement can be translated into a single
  3345. \key{addq} instruction, as follows.
  3346. \begin{transformation}
  3347. {\if\edition\racketEd
  3348. \begin{lstlisting}
  3349. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3350. \end{lstlisting}
  3351. \fi}
  3352. {\if\edition\pythonEd\pythonColor
  3353. \begin{lstlisting}
  3354. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3355. \end{lstlisting}
  3356. \fi}
  3357. \compilesto
  3358. \begin{lstlisting}
  3359. addq |$\Arg_1$|, |$\itm{var}$|
  3360. \end{lstlisting}
  3361. \end{transformation}
  3362. The \READOP{} operation does not have a direct counterpart in x86
  3363. assembly, so we provide this functionality with the function
  3364. \code{read\_int} in the file \code{runtime.c}, written in
  3365. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3366. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3367. system}, or simply the \emph{runtime} for short. When compiling your
  3368. generated x86 assembly code, you need to compile \code{runtime.c} to
  3369. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3370. \code{-c}) and link it into the executable. For our purposes of code
  3371. generation, all you need to do is translate an assignment of
  3372. \READOP{} into a call to the \code{read\_int} function followed by a
  3373. move from \code{rax} to the left-hand side variable. (Recall that the
  3374. return value of a function goes into \code{rax}.)
  3375. \begin{transformation}
  3376. {\if\edition\racketEd
  3377. \begin{lstlisting}
  3378. |$\itm{var}$| = (read);
  3379. \end{lstlisting}
  3380. \fi}
  3381. {\if\edition\pythonEd\pythonColor
  3382. \begin{lstlisting}
  3383. |$\itm{var}$| = input_int();
  3384. \end{lstlisting}
  3385. \fi}
  3386. \compilesto
  3387. \begin{lstlisting}
  3388. callq read_int
  3389. movq %rax, |$\itm{var}$|
  3390. \end{lstlisting}
  3391. \end{transformation}
  3392. {\if\edition\pythonEd\pythonColor
  3393. %
  3394. Similarly, we translate the \code{print} operation, shown below, into
  3395. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3396. In x86, the first six arguments to functions are passed in registers,
  3397. with the first argument passed in register \code{rdi}. So we move the
  3398. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3399. \code{callq} instruction.
  3400. \begin{transformation}
  3401. \begin{lstlisting}
  3402. print(|$\Atm$|)
  3403. \end{lstlisting}
  3404. \compilesto
  3405. \begin{lstlisting}
  3406. movq |$\Arg$|, %rdi
  3407. callq print_int
  3408. \end{lstlisting}
  3409. \end{transformation}
  3410. %
  3411. \fi}
  3412. {\if\edition\racketEd
  3413. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3414. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3415. assignment to the \key{rax} register followed by a jump to the
  3416. conclusion of the program (so the conclusion needs to be labeled).
  3417. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3418. recursively and then append the resulting instructions.
  3419. \fi}
  3420. {\if\edition\pythonEd\pythonColor
  3421. We recommend that you use the function \code{utils.label\_name()} to
  3422. transform a string into an label argument suitably suitable for, e.g.,
  3423. the target of the \code{callq} instruction. This practice makes your
  3424. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3425. all labels.
  3426. \fi}
  3427. \begin{exercise}
  3428. \normalfont\normalsize
  3429. {\if\edition\racketEd
  3430. Implement the \code{select\_instructions} pass in
  3431. \code{compiler.rkt}. Create three new example programs that are
  3432. designed to exercise all the interesting cases in this pass.
  3433. %
  3434. In the \code{run-tests.rkt} script, add the following entry to the
  3435. list of \code{passes} and then run the script to test your compiler.
  3436. \begin{lstlisting}
  3437. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3438. \end{lstlisting}
  3439. \fi}
  3440. {\if\edition\pythonEd\pythonColor
  3441. Implement the \key{select\_instructions} pass in
  3442. \code{compiler.py}. Create three new example programs that are
  3443. designed to exercise all the interesting cases in this pass.
  3444. Run the \code{run-tests.py} script to to check
  3445. whether the output programs produce the same result as the input
  3446. programs.
  3447. \fi}
  3448. \end{exercise}
  3449. \section{Assign Homes}
  3450. \label{sec:assign-Lvar}
  3451. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3452. \LangXVar{} programs that no longer use program variables. Thus, the
  3453. \code{assign\_homes} pass is responsible for placing all the program
  3454. variables in registers or on the stack. For runtime efficiency, it is
  3455. better to place variables in registers, but because there are only
  3456. sixteen registers, some programs must necessarily resort to placing
  3457. some variables on the stack. In this chapter we focus on the mechanics
  3458. of placing variables on the stack. We study an algorithm for placing
  3459. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3460. Consider again the following \LangVar{} program from
  3461. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3462. % var_test_20.rkt
  3463. \begin{minipage}{0.96\textwidth}
  3464. {\if\edition\racketEd
  3465. \begin{lstlisting}
  3466. (let ([a 42])
  3467. (let ([b a])
  3468. b))
  3469. \end{lstlisting}
  3470. \fi}
  3471. {\if\edition\pythonEd\pythonColor
  3472. \begin{lstlisting}
  3473. a = 42
  3474. b = a
  3475. print(b)
  3476. \end{lstlisting}
  3477. \fi}
  3478. \end{minipage}\\
  3479. %
  3480. The output of \code{select\_instructions} is shown next, on the left,
  3481. and the output of \code{assign\_homes} is on the right. In this
  3482. example, we assign variable \code{a} to stack location
  3483. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3484. \begin{transformation}
  3485. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3486. movq $42, a
  3487. movq a, b
  3488. movq b, %rax
  3489. \end{lstlisting}
  3490. \compilesto
  3491. %stack-space: 16
  3492. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3493. movq $42, -8(%rbp)
  3494. movq -8(%rbp), -16(%rbp)
  3495. movq -16(%rbp), %rax
  3496. \end{lstlisting}
  3497. \end{transformation}
  3498. \racket{
  3499. The \code{assign\_homes} pass should replace all variables
  3500. with stack locations.
  3501. The list of variables can be obtained from
  3502. the \code{locals-types} entry in the $\itm{info}$ of the
  3503. \code{X86Program} node. The \code{locals-types} entry is an alist
  3504. mapping all the variables in the program to their types
  3505. (for now, just \code{Integer}).
  3506. As an aside, the \code{locals-types} entry is
  3507. computed by \code{type-check-Cvar} in the support code, which
  3508. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3509. which you should propagate to the \code{X86Program} node.}
  3510. %
  3511. \python{The \code{assign\_homes} pass should replace all uses of
  3512. variables with stack locations.}
  3513. %
  3514. In the process of assigning variables to stack locations, it is
  3515. convenient for you to compute and store the size of the frame (in
  3516. bytes) in
  3517. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3518. %
  3519. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3520. %
  3521. which is needed later to generate the conclusion of the \code{main}
  3522. procedure. The x86-64 standard requires the frame size to be a
  3523. multiple of 16 bytes.\index{subject}{frame}
  3524. % TODO: store the number of variables instead? -Jeremy
  3525. \begin{exercise}\normalfont\normalsize
  3526. Implement the \code{assign\_homes} pass in
  3527. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3528. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3529. grammar. We recommend that the auxiliary functions take an extra
  3530. parameter that maps variable names to homes (stack locations for now).
  3531. %
  3532. {\if\edition\racketEd
  3533. In the \code{run-tests.rkt} script, add the following entry to the
  3534. list of \code{passes} and then run the script to test your compiler.
  3535. \begin{lstlisting}
  3536. (list "assign homes" assign-homes interp_x86-0)
  3537. \end{lstlisting}
  3538. \fi}
  3539. {\if\edition\pythonEd\pythonColor
  3540. Run the \code{run-tests.py} script to to check
  3541. whether the output programs produce the same result as the input
  3542. programs.
  3543. \fi}
  3544. \end{exercise}
  3545. \section{Patch Instructions}
  3546. \label{sec:patch-s0}
  3547. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3548. \LangXInt{} by making sure that each instruction adheres to the
  3549. restriction that at most one argument of an instruction may be a
  3550. memory reference.
  3551. We return to the following example.\\
  3552. \begin{minipage}{0.5\textwidth}
  3553. % var_test_20.rkt
  3554. {\if\edition\racketEd
  3555. \begin{lstlisting}
  3556. (let ([a 42])
  3557. (let ([b a])
  3558. b))
  3559. \end{lstlisting}
  3560. \fi}
  3561. {\if\edition\pythonEd\pythonColor
  3562. \begin{lstlisting}
  3563. a = 42
  3564. b = a
  3565. print(b)
  3566. \end{lstlisting}
  3567. \fi}
  3568. \end{minipage}\\
  3569. The \code{assign\_homes} pass produces the following translation. \\
  3570. \begin{minipage}{0.5\textwidth}
  3571. {\if\edition\racketEd
  3572. \begin{lstlisting}
  3573. movq $42, -8(%rbp)
  3574. movq -8(%rbp), -16(%rbp)
  3575. movq -16(%rbp), %rax
  3576. \end{lstlisting}
  3577. \fi}
  3578. {\if\edition\pythonEd\pythonColor
  3579. \begin{lstlisting}
  3580. movq 42, -8(%rbp)
  3581. movq -8(%rbp), -16(%rbp)
  3582. movq -16(%rbp), %rdi
  3583. callq print_int
  3584. \end{lstlisting}
  3585. \fi}
  3586. \end{minipage}\\
  3587. The second \key{movq} instruction is problematic because both
  3588. arguments are stack locations. We suggest fixing this problem by
  3589. moving from the source location to the register \key{rax} and then
  3590. from \key{rax} to the destination location, as follows.
  3591. \begin{lstlisting}
  3592. movq -8(%rbp), %rax
  3593. movq %rax, -16(%rbp)
  3594. \end{lstlisting}
  3595. \begin{exercise}
  3596. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3597. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3598. Create three new example programs that are
  3599. designed to exercise all the interesting cases in this pass.
  3600. %
  3601. {\if\edition\racketEd
  3602. In the \code{run-tests.rkt} script, add the following entry to the
  3603. list of \code{passes} and then run the script to test your compiler.
  3604. \begin{lstlisting}
  3605. (list "patch instructions" patch_instructions interp_x86-0)
  3606. \end{lstlisting}
  3607. \fi}
  3608. {\if\edition\pythonEd\pythonColor
  3609. Run the \code{run-tests.py} script to to check
  3610. whether the output programs produce the same result as the input
  3611. programs.
  3612. \fi}
  3613. \end{exercise}
  3614. \section{Generate Prelude and Conclusion}
  3615. \label{sec:print-x86}
  3616. \index{subject}{prelude}\index{subject}{conclusion}
  3617. The last step of the compiler from \LangVar{} to x86 is to generate
  3618. the \code{main} function with a prelude and conclusion wrapped around
  3619. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3620. discussed in section~\ref{sec:x86}.
  3621. When running on Mac OS X, your compiler should prefix an underscore to
  3622. all labels, e.g., changing \key{main} to \key{\_main}.
  3623. %
  3624. \racket{The Racket call \code{(system-type 'os)} is useful for
  3625. determining which operating system the compiler is running on. It
  3626. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3627. %
  3628. \python{The Python \code{platform} library includes a \code{system()}
  3629. function that returns \code{'Linux'}, \code{'Windows'}, or
  3630. \code{'Darwin'} (for Mac).}
  3631. \begin{exercise}\normalfont\normalsize
  3632. %
  3633. Implement the \key{prelude\_and\_conclusion} pass in
  3634. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3635. %
  3636. {\if\edition\racketEd
  3637. In the \code{run-tests.rkt} script, add the following entry to the
  3638. list of \code{passes} and then run the script to test your compiler.
  3639. \begin{lstlisting}
  3640. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3641. \end{lstlisting}
  3642. %
  3643. Uncomment the call to the \key{compiler-tests} function
  3644. (appendix~\ref{appendix:utilities}), which tests your complete
  3645. compiler by executing the generated x86 code. It translates the x86
  3646. AST that you produce into a string by invoking the \code{print-x86}
  3647. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3648. the provided \key{runtime.c} file to \key{runtime.o} using
  3649. \key{gcc}. Run the script to test your compiler.
  3650. %
  3651. \fi}
  3652. {\if\edition\pythonEd\pythonColor
  3653. %
  3654. Run the \code{run-tests.py} script to to check whether the output
  3655. programs produce the same result as the input programs. That script
  3656. translates the x86 AST that you produce into a string by invoking the
  3657. \code{repr} method that is implemented by the x86 AST classes in
  3658. \code{x86\_ast.py}.
  3659. %
  3660. \fi}
  3661. \end{exercise}
  3662. \section{Challenge: Partial Evaluator for \LangVar{}}
  3663. \label{sec:pe-Lvar}
  3664. \index{subject}{partial evaluation}
  3665. This section describes two optional challenge exercises that involve
  3666. adapting and improving the partial evaluator for \LangInt{} that was
  3667. introduced in section~\ref{sec:partial-evaluation}.
  3668. \begin{exercise}\label{ex:pe-Lvar}
  3669. \normalfont\normalsize
  3670. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3671. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3672. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3673. %
  3674. \racket{\key{let} binding}\python{assignment}
  3675. %
  3676. to the \LangInt{} language, so you will need to add cases for them in
  3677. the \code{pe\_exp}
  3678. %
  3679. \racket{function.}
  3680. %
  3681. \python{and \code{pe\_stmt} functions.}
  3682. %
  3683. Once complete, add the partial evaluation pass to the front of your
  3684. compiler, and make sure that your compiler still passes all the
  3685. tests.
  3686. \end{exercise}
  3687. \begin{exercise}
  3688. \normalfont\normalsize
  3689. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3690. \code{pe\_add} auxiliary functions with functions that know more about
  3691. arithmetic. For example, your partial evaluator should translate
  3692. {\if\edition\racketEd
  3693. \[
  3694. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3695. \code{(+ 2 (read))}
  3696. \]
  3697. \fi}
  3698. {\if\edition\pythonEd\pythonColor
  3699. \[
  3700. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3701. \code{2 + input\_int()}
  3702. \]
  3703. \fi}
  3704. %
  3705. To accomplish this, the \code{pe\_exp} function should produce output
  3706. in the form of the $\itm{residual}$ nonterminal of the following
  3707. grammar. The idea is that when processing an addition expression, we
  3708. can always produce one of the following: (1) an integer constant, (2)
  3709. an addition expression with an integer constant on the left-hand side
  3710. but not the right-hand side, or (3) an addition expression in which
  3711. neither subexpression is a constant.
  3712. %
  3713. {\if\edition\racketEd
  3714. \[
  3715. \begin{array}{lcl}
  3716. \itm{inert} &::=& \Var
  3717. \MID \LP\key{read}\RP
  3718. \MID \LP\key{-} ~\Var\RP
  3719. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3720. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3721. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3722. \itm{residual} &::=& \Int
  3723. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3724. \MID \itm{inert}
  3725. \end{array}
  3726. \]
  3727. \fi}
  3728. {\if\edition\pythonEd\pythonColor
  3729. \[
  3730. \begin{array}{lcl}
  3731. \itm{inert} &::=& \Var
  3732. \MID \key{input\_int}\LP\RP
  3733. \MID \key{-} \Var
  3734. \MID \key{-} \key{input\_int}\LP\RP
  3735. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3736. \itm{residual} &::=& \Int
  3737. \MID \Int ~ \key{+} ~ \itm{inert}
  3738. \MID \itm{inert}
  3739. \end{array}
  3740. \]
  3741. \fi}
  3742. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3743. inputs are $\itm{residual}$ expressions and they should return
  3744. $\itm{residual}$ expressions. Once the improvements are complete,
  3745. make sure that your compiler still passes all the tests. After
  3746. all, fast code is useless if it produces incorrect results!
  3747. \end{exercise}
  3748. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3749. {\if\edition\pythonEd\pythonColor
  3750. \chapter{Parsing}
  3751. \label{ch:parsing}
  3752. \setcounter{footnote}{0}
  3753. \index{subject}{parsing}
  3754. In this chapter we learn how to use the Lark parser
  3755. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3756. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3757. You will then be asked to use Lark to create a parser for \LangVar{}.
  3758. We also describe the parsing algorithms used inside Lark, studying the
  3759. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3760. A parser framework such as Lark takes in a specification of the
  3761. concrete syntax and an input program and produces a parse tree. Even
  3762. though a parser framework does most of the work for us, using one
  3763. properly requires some knowledge. In particular, we must learn about
  3764. its specification languages and we must learn how to deal with
  3765. ambiguity in our language specifications. Also, some algorithms, such
  3766. as LALR(1) place restrictions on the grammars they can handle, in
  3767. which case it helps to know the algorithm when trying to decipher the
  3768. error messages.
  3769. The process of parsing is traditionally subdivided into two phases:
  3770. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3771. analysis} (also called parsing). The lexical analysis phase
  3772. translates the sequence of characters into a sequence of
  3773. \emph{tokens}, that is, words consisting of several characters. The
  3774. parsing phase organizes the tokens into a \emph{parse tree} that
  3775. captures how the tokens were matched by rules in the grammar of the
  3776. language. The reason for the subdivision into two phases is to enable
  3777. the use of a faster but less powerful algorithm for lexical analysis
  3778. and the use of a slower but more powerful algorithm for parsing.
  3779. %
  3780. %% Likewise, parser generators typical come in pairs, with separate
  3781. %% generators for the lexical analyzer (or lexer for short) and for the
  3782. %% parser. A particularly influential pair of generators were
  3783. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3784. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3785. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3786. %% Compiler Compiler.
  3787. %
  3788. The Lark parser framework that we use in this chapter includes both
  3789. lexical analyzers and parsers. The next section discusses lexical
  3790. analysis and the remainder of the chapter discusses parsing.
  3791. \section{Lexical Analysis and Regular Expressions}
  3792. \label{sec:lex}
  3793. The lexical analyzers produced by Lark turn a sequence of characters
  3794. (a string) into a sequence of token objects. For example, a Lark
  3795. generated lexer for \LangInt{} converts the string
  3796. \begin{lstlisting}
  3797. 'print(1 + 3)'
  3798. \end{lstlisting}
  3799. \noindent into the following sequence of token objects
  3800. \begin{center}
  3801. \begin{minipage}{0.95\textwidth}
  3802. \begin{lstlisting}
  3803. Token('PRINT', 'print')
  3804. Token('LPAR', '(')
  3805. Token('INT', '1')
  3806. Token('PLUS', '+')
  3807. Token('INT', '3')
  3808. Token('RPAR', ')')
  3809. Token('NEWLINE', '\n')
  3810. \end{lstlisting}
  3811. \end{minipage}
  3812. \end{center}
  3813. Each token includes a field for its \code{type}, such as \code{'INT'},
  3814. and a field for its \code{value}, such as \code{'1'}.
  3815. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3816. specification language for Lark's lexer is one regular expression for
  3817. each type of token. The term \emph{regular} comes from the term
  3818. \emph{regular languages}, which are the languages that can be
  3819. recognized by a finite state machine. A \emph{regular expression} is a
  3820. pattern formed of the following core elements:\index{subject}{regular
  3821. expression}\footnote{Regular expressions traditionally include the
  3822. empty regular expression that matches any zero-length part of a
  3823. string, but Lark does not support the empty regular expression.}
  3824. \begin{itemize}
  3825. \item A single character $c$ is a regular expression and it only
  3826. matches itself. For example, the regular expression \code{a} only
  3827. matches with the string \code{'a'}.
  3828. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3829. R_2$ form a regular expression that matches any string that matches
  3830. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3831. matches the string \code{'a'} and the string \code{'c'}.
  3832. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3833. expression that matches any string that can be formed by
  3834. concatenating two strings, where the first string matches $R_1$ and
  3835. the second string matches $R_2$. For example, the regular expression
  3836. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3837. (Parentheses can be used to control the grouping of operators within
  3838. a regular expression.)
  3839. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3840. Kleene closure) is a regular expression that matches any string that
  3841. can be formed by concatenating zero or more strings that each match
  3842. the regular expression $R$. For example, the regular expression
  3843. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} but not
  3844. \code{'abc'}.
  3845. \end{itemize}
  3846. For our convenience, Lark also accepts the following extended set of
  3847. regular expressions that are automatically translated into the core
  3848. regular expressions.
  3849. \begin{itemize}
  3850. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3851. c_n]$ is a regular expression that matches any one of the
  3852. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3853. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3854. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3855. a regular expression that matches any character between $c_1$ and
  3856. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3857. letter in the alphabet.
  3858. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3859. is a regular expression that matches any string that can
  3860. be formed by concatenating one or more strings that each match $R$.
  3861. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3862. matches \code{'b'} and \code{'bzca'}.
  3863. \item A regular expression followed by a question mark $R\ttm{?}$
  3864. is a regular expression that matches any string that either
  3865. matches $R$ or that is the empty string.
  3866. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3867. \item A string, such as \code{"hello"}, which matches itself,
  3868. that is, \code{'hello'}.
  3869. \end{itemize}
  3870. In a Lark grammar file, specify a name for each type of token followed
  3871. by a colon and then a regular expression surrounded by \code{/}
  3872. characters. For example, the \code{DIGIT}, \code{INT}, and
  3873. \code{NEWLINE} types of tokens are specified in the following way.
  3874. \begin{center}
  3875. \begin{minipage}{0.95\textwidth}
  3876. \begin{lstlisting}
  3877. DIGIT: /[0-9]/
  3878. INT: "-"? DIGIT+
  3879. NEWLINE: (/\r/? /\n/)+
  3880. \end{lstlisting}
  3881. \end{minipage}
  3882. \end{center}
  3883. \noindent In Lark, the regular expression operators can be used both
  3884. inside a regular expression, that is, between the \code{/} characters,
  3885. and they can be used to combine regular expressions, outside the
  3886. \code{/} characters.
  3887. \section{Grammars and Parse Trees}
  3888. \label{sec:CFG}
  3889. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3890. specify the abstract syntax of a language. We now take a closer look
  3891. at using grammar rules to specify the concrete syntax. Recall that
  3892. each rule has a left-hand side and a right-hand side where the
  3893. left-hand side is a nonterminal and the right-hand side is a pattern
  3894. that defines what can be parsed as that nonterminal.
  3895. For concrete syntax, each right-hand side expresses a pattern for a
  3896. string, instead of a pattern for an abstract syntax tree. In
  3897. particular, each right-hand side is a sequence of
  3898. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3899. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3900. a string. The nonterminals play the same role as in the abstract
  3901. syntax, defining categories of syntax. The nonterminals of a grammar
  3902. include the tokens defined in the lexer and all the nonterminals
  3903. defined by the grammar rules.
  3904. As an example, let us take a closer look at the concrete syntax of the
  3905. \LangInt{} language, repeated here.
  3906. \[
  3907. \begin{array}{l}
  3908. \LintGrammarPython \\
  3909. \begin{array}{rcl}
  3910. \LangInt{} &::=& \Stmt^{*}
  3911. \end{array}
  3912. \end{array}
  3913. \]
  3914. The Lark syntax for grammar rules differs slightly from the variant of
  3915. BNF that we use in this book. In particular, the notation $::=$ is
  3916. replaced by a single colon and the use of typewriter font for string
  3917. literals is replaced by quotation marks. The following grammar serves
  3918. as a first draft of a Lark grammar for \LangInt{}.
  3919. \begin{center}
  3920. \begin{minipage}{0.95\textwidth}
  3921. \begin{lstlisting}[escapechar=$]
  3922. exp: INT
  3923. | "input_int" "(" ")"
  3924. | "-" exp
  3925. | exp "+" exp
  3926. | exp "-" exp
  3927. | "(" exp ")"
  3928. stmt_list:
  3929. | stmt NEWLINE stmt_list
  3930. lang_int: stmt_list
  3931. \end{lstlisting}
  3932. \end{minipage}
  3933. \end{center}
  3934. Let us begin by discussing the rule \code{exp: INT} which says that if
  3935. the lexer matches a string to \code{INT}, then the parser also
  3936. categorizes the string as an \code{exp}. Recall that in
  3937. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  3938. nonterminal with an English sentence. Here we specify \code{INT} more
  3939. formally using a type of token \code{INT} and its regular expression
  3940. \code{"-"? DIGIT+}.
  3941. The rule \code{exp: exp "+" exp} says that any string that matches
  3942. \code{exp}, followed by the \code{+} character, followed by another
  3943. string that matches \code{exp}, is itself an \code{exp}. For example,
  3944. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  3945. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  3946. the rule for addition applies to categorize \code{'1+3'} as an
  3947. \code{exp}. We can visualize the application of grammar rules to parse
  3948. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  3949. internal node in the tree is an application of a grammar rule and is
  3950. labeled with its left-hand side nonterminal. Each leaf node is a
  3951. substring of the input program. The parse tree for \code{'1+3'} is
  3952. shown in figure~\ref{fig:simple-parse-tree}.
  3953. \begin{figure}[tbp]
  3954. \begin{tcolorbox}[colback=white]
  3955. \centering
  3956. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  3957. \end{tcolorbox}
  3958. \caption{The parse tree for \code{'1+3'}.}
  3959. \label{fig:simple-parse-tree}
  3960. \end{figure}
  3961. The result of parsing \code{'1+3'} with this Lark grammar is the
  3962. following parse tree as represented by \code{Tree} and \code{Token}
  3963. objects.
  3964. \begin{lstlisting}
  3965. Tree('lang_int',
  3966. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  3967. Tree('exp', [Token('INT', '3')])])]),
  3968. Token('NEWLINE', '\n')])
  3969. \end{lstlisting}
  3970. The nodes that come from the lexer are \code{Token} objects whereas
  3971. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  3972. object has a \code{data} field containing the name of the nonterminal
  3973. for the grammar rule that was applied. Each \code{Tree} object also
  3974. has a \code{children} field that is a list containing trees and/or
  3975. tokens. Note that Lark does not produce nodes for string literals in
  3976. the grammar. For example, the \code{Tree} node for the addition
  3977. expression has only two children for the two integers but is missing
  3978. its middle child for the \code{"+"} terminal. This would be
  3979. problematic except that Lark provides a mechanism for customizing the
  3980. \code{data} field of each \code{Tree} node based on which rule was
  3981. applied. Next to each alternative in a grammar rule, write \code{->}
  3982. followed by a string that you would like to appear in the \code{data}
  3983. field. The following is a second draft of a Lark grammar for
  3984. \LangInt{}, this time with more specific labels on the \code{Tree}
  3985. nodes.
  3986. \begin{center}
  3987. \begin{minipage}{0.95\textwidth}
  3988. \begin{lstlisting}[escapechar=$]
  3989. exp: INT -> int
  3990. | "input_int" "(" ")" -> input_int
  3991. | "-" exp -> usub
  3992. | exp "+" exp -> add
  3993. | exp "-" exp -> sub
  3994. | "(" exp ")" -> paren
  3995. stmt: "print" "(" exp ")" -> print
  3996. | exp -> expr
  3997. stmt_list: -> empty_stmt
  3998. | stmt NEWLINE stmt_list -> add_stmt
  3999. lang_int: stmt_list -> module
  4000. \end{lstlisting}
  4001. \end{minipage}
  4002. \end{center}
  4003. Here is the resulting parse tree.
  4004. \begin{lstlisting}
  4005. Tree('module',
  4006. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4007. Tree('int', [Token('INT', '3')])])]),
  4008. Token('NEWLINE', '\n')])
  4009. \end{lstlisting}
  4010. \section{Ambiguous Grammars}
  4011. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4012. can be parsed in more than one way. For example, consider the string
  4013. \code{'1-2+3'}. This string can parsed in two different ways using
  4014. our draft grammar, resulting in the two parse trees shown in
  4015. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4016. interpreting the second parse tree would yield \code{-4} even through
  4017. the correct answer is \code{2}.
  4018. \begin{figure}[tbp]
  4019. \begin{tcolorbox}[colback=white]
  4020. \centering
  4021. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4022. \end{tcolorbox}
  4023. \caption{The two parse trees for \code{'1-2+3'}.}
  4024. \label{fig:ambig-parse-tree}
  4025. \end{figure}
  4026. To deal with this problem we can change the grammar by categorizing
  4027. the syntax in a more fine grained fashion. In this case we want to
  4028. disallow the application of the rule \code{exp: exp "-" exp} when the
  4029. child on the right is an addition. To do this we can replace the
  4030. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4031. the expressions except for addition, as in the following.
  4032. \begin{center}
  4033. \begin{minipage}{0.95\textwidth}
  4034. \begin{lstlisting}[escapechar=$]
  4035. exp: exp "-" exp_no_add -> sub
  4036. | exp "+" exp -> add
  4037. | exp_no_add
  4038. exp_no_add: INT -> int
  4039. | "input_int" "(" ")" -> input_int
  4040. | "-" exp -> usub
  4041. | exp "-" exp_no_add -> sub
  4042. | "(" exp ")" -> paren
  4043. \end{lstlisting}
  4044. \end{minipage}
  4045. \end{center}
  4046. However, there remains some ambiguity in the grammar. For example, the
  4047. string \code{'1-2-3'} can still be parsed in two different ways, as
  4048. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4049. to say, subtraction is left associative. Likewise, addition in Python
  4050. is left associative. We also need to consider the interaction of unary
  4051. subtraction with both addition and subtraction. How should we parse
  4052. \code{'-1+2'}? Unary subtraction has higher
  4053. \emph{precendence}\index{subject}{precedence} than addition and
  4054. subtraction, so \code{'-1+2'} should parse the same as \code{'(-1)+2'}
  4055. and not \code{'-(1+2)'}. The grammar in
  4056. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4057. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4058. all the other expressions, and uses \code{exp\_hi} for the second
  4059. child in the rules for addition and subtraction. Furthermore, unary
  4060. subtraction uses \code{exp\_hi} for its child.
  4061. For languages with more operators and more precedence levels, one must
  4062. refine the \code{exp} nonterminal into several nonterminals, one for
  4063. each precedence level.
  4064. \begin{figure}[tbp]
  4065. \begin{tcolorbox}[colback=white]
  4066. \centering
  4067. \begin{lstlisting}[escapechar=$]
  4068. exp: exp "+" exp_hi -> add
  4069. | exp "-" exp_hi -> sub
  4070. | exp_hi
  4071. exp_hi: INT -> int
  4072. | "input_int" "(" ")" -> input_int
  4073. | "-" exp_hi -> usub
  4074. | "(" exp ")" -> paren
  4075. stmt: "print" "(" exp ")" -> print
  4076. | exp -> expr
  4077. stmt_list: -> empty_stmt
  4078. | stmt NEWLINE stmt_list -> add_stmt
  4079. lang_int: stmt_list -> module
  4080. \end{lstlisting}
  4081. \end{tcolorbox}
  4082. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4083. \label{fig:Lint-lark-grammar}
  4084. \end{figure}
  4085. \section{From Parse Trees to Abstract Syntax Trees}
  4086. As we have seen, the output of a Lark parser is a parse tree, that is,
  4087. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4088. step is to convert the parse tree to an abstract syntax tree. This can
  4089. be accomplished with a recursive function that inspects the
  4090. \code{data} field of each node and then constructs the corresponding
  4091. AST node, using recursion to handle its children. The following is an
  4092. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4093. \begin{center}
  4094. \begin{minipage}{0.95\textwidth}
  4095. \begin{lstlisting}
  4096. def parse_tree_to_ast(e):
  4097. if e.data == 'int':
  4098. return Constant(int(e.children[0].value))
  4099. elif e.data == 'input_int':
  4100. return Call(Name('input_int'), [])
  4101. elif e.data == 'add':
  4102. e1, e2 = e.children
  4103. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4104. ...
  4105. else:
  4106. raise Exception('unhandled parse tree', e)
  4107. \end{lstlisting}
  4108. \end{minipage}
  4109. \end{center}
  4110. \begin{exercise}
  4111. \normalfont\normalsize
  4112. %
  4113. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4114. default parsing algorithm (Earley) with the \code{ambiguity} option
  4115. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4116. output will include multiple parse trees which will indicate to you
  4117. that there is a problem with your grammar. Your parser should ignore
  4118. white space so we recommend using Lark's \code{\%ignore} directive
  4119. as follows.
  4120. \begin{lstlisting}
  4121. WS: /[ \t\f\r\n]/+
  4122. %ignore WS
  4123. \end{lstlisting}
  4124. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4125. Lark parser instead of using the \code{parse} function from
  4126. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4127. programs that you have created and create four additional programs
  4128. that test for ambiguities in your grammar.
  4129. \end{exercise}
  4130. \section{The Earley Algorithm}
  4131. \label{sec:earley}
  4132. In this section we discuss the parsing algorithm of
  4133. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4134. algorithm is powerful in that it can handle any context-free grammar,
  4135. which makes it easy to use. However, it is not the most efficient
  4136. parsing algorithm: it is $O(n^3)$ for ambiguous grammars and $O(n^2)$
  4137. for unambiguous grammars, where $n$ is the number of tokens in the
  4138. input string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr}
  4139. we learn about the LALR(1) algorithm, which is more efficient but
  4140. cannot handle all context-free grammars.
  4141. The Earley algorithm can be viewed as an interpreter; it treats the
  4142. grammar as the program being interpreted and it treats the concrete
  4143. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4144. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4145. keep track of its progress and to memoize its results. The chart is an
  4146. array with one slot for each position in the input string, where
  4147. position $0$ is before the first character and position $n$ is
  4148. immediately after the last character. So the array has length $n+1$
  4149. for an input string of length $n$. Each slot in the chart contains a
  4150. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4151. with a period indicating how much of its right-hand side has already
  4152. been parsed. For example, the dotted rule
  4153. \begin{lstlisting}
  4154. exp: exp "+" . exp_hi
  4155. \end{lstlisting}
  4156. represents a partial parse that has matched an \code{exp} followed by
  4157. \code{+}, but has not yet parsed an \code{exp} to the right of
  4158. \code{+}.
  4159. %
  4160. The Earley algorithm starts with an initialization phase, and then
  4161. repeats three actions---prediction, scanning, and completion---for as
  4162. long as opportunities arise. We demonstrate the Earley algorithm on a
  4163. running example, parsing the following program:
  4164. \begin{lstlisting}
  4165. print(1 + 3)
  4166. \end{lstlisting}
  4167. The algorithm's initialization phase creates dotted rules for all the
  4168. grammar rules whose left-hand side is the start symbol and places them
  4169. in slot $0$ of the chart. We also record the starting position of the
  4170. dotted rule in parentheses on the right. For example, given the
  4171. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4172. \begin{lstlisting}
  4173. lang_int: . stmt_list (0)
  4174. \end{lstlisting}
  4175. in slot $0$ of the chart. The algorithm then proceeds with
  4176. \emph{prediction} actions in which it adds more dotted rules to the
  4177. chart based on which nonterminals come immediately after a period. In
  4178. the above, the nonterminal \code{stmt\_list} appears after a period,
  4179. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4180. period at the beginning of their right-hand sides, as follows:
  4181. \begin{lstlisting}
  4182. stmt_list: . (0)
  4183. stmt_list: . stmt NEWLINE stmt_list (0)
  4184. \end{lstlisting}
  4185. We continue to perform prediction actions as more opportunities
  4186. arise. For example, the \code{stmt} nonterminal now appears after a
  4187. period, so we add all the rules for \code{stmt}.
  4188. \begin{lstlisting}
  4189. stmt: . "print" "(" exp ")" (0)
  4190. stmt: . exp (0)
  4191. \end{lstlisting}
  4192. This reveals yet more opportunities for prediction, so we add the grammar
  4193. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4194. \begin{lstlisting}[escapechar=$]
  4195. exp: . exp "+" exp_hi (0)
  4196. exp: . exp "-" exp_hi (0)
  4197. exp: . exp_hi (0)
  4198. exp_hi: . INT (0)
  4199. exp_hi: . "input_int" "(" ")" (0)
  4200. exp_hi: . "-" exp_hi (0)
  4201. exp_hi: . "(" exp ")" (0)
  4202. \end{lstlisting}
  4203. We have exhausted the opportunities for prediction, so the algorithm
  4204. proceeds to \emph{scanning}, in which we inspect the next input token
  4205. and look for a dotted rule at the current position that has a matching
  4206. terminal immediately following the period. In our running example, the
  4207. first input token is \code{"print"} so we identify the rule in slot
  4208. $0$ of the chart where \code{"print"} follows the period:
  4209. \begin{lstlisting}
  4210. stmt: . "print" "(" exp ")" (0)
  4211. \end{lstlisting}
  4212. We advance the period past \code{"print"} and add the resulting rule
  4213. to slot $1$ of the chart:
  4214. \begin{lstlisting}
  4215. stmt: "print" . "(" exp ")" (0)
  4216. \end{lstlisting}
  4217. If the new dotted rule had a nonterminal after the period, we would
  4218. need to carry out a prediction action, adding more dotted rules into
  4219. slot $1$. That is not the case, so we continue scanning. The next
  4220. input token is \code{"("}, so we add the following to slot $2$ of the
  4221. chart.
  4222. \begin{lstlisting}
  4223. stmt: "print" "(" . exp ")" (0)
  4224. \end{lstlisting}
  4225. Now we have a nonterminal after the period, so we carry out several
  4226. prediction actions, adding dotted rules for \code{exp} and
  4227. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4228. starting position $2$.
  4229. \begin{lstlisting}[escapechar=$]
  4230. exp: . exp "+" exp_hi (2)
  4231. exp: . exp "-" exp_hi (2)
  4232. exp: . exp_hi (2)
  4233. exp_hi: . INT (2)
  4234. exp_hi: . "input_int" "(" ")" (2)
  4235. exp_hi: . "-" exp_hi (2)
  4236. exp_hi: . "(" exp ")" (2)
  4237. \end{lstlisting}
  4238. With this prediction complete, we return to scanning, noting that the
  4239. next input token is \code{"1"} which the lexer parses as an
  4240. \code{INT}. There is a matching rule in slot $2$:
  4241. \begin{lstlisting}
  4242. exp_hi: . INT (2)
  4243. \end{lstlisting}
  4244. so we advance the period and put the following rule is slot $3$.
  4245. \begin{lstlisting}
  4246. exp_hi: INT . (2)
  4247. \end{lstlisting}
  4248. This brings us to \emph{completion} actions. When the period reaches
  4249. the end of a dotted rule, we recognize that the substring
  4250. has matched the nonterminal on the left-hand side of the rule, in this case
  4251. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4252. rules in slot $2$ (the starting position for the finished rule) if
  4253. the period is immediately followed by \code{exp\_hi}. So we identify
  4254. \begin{lstlisting}
  4255. exp: . exp_hi (2)
  4256. \end{lstlisting}
  4257. and add the following dotted rule to slot $3$
  4258. \begin{lstlisting}
  4259. exp: exp_hi . (2)
  4260. \end{lstlisting}
  4261. This triggers another completion step for the nonterminal \code{exp},
  4262. adding two more dotted rules to slot $3$.
  4263. \begin{lstlisting}[escapechar=$]
  4264. exp: exp . "+" exp_hi (2)
  4265. exp: exp . "-" exp_hi (2)
  4266. \end{lstlisting}
  4267. Returning to scanning, the next input token is \code{"+"}, so
  4268. we add the following to slot $4$.
  4269. \begin{lstlisting}[escapechar=$]
  4270. exp: exp "+" . exp_hi (2)
  4271. \end{lstlisting}
  4272. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4273. the following dotted rules to slot $4$ of the chart.
  4274. \begin{lstlisting}[escapechar=$]
  4275. exp_hi: . INT (4)
  4276. exp_hi: . "input_int" "(" ")" (4)
  4277. exp_hi: . "-" exp_hi (4)
  4278. exp_hi: . "(" exp ")" (4)
  4279. \end{lstlisting}
  4280. The next input token is \code{"3"} which the lexer categorized as an
  4281. \code{INT}, so we advance the period past \code{INT} for the rules in
  4282. slot $4$, of which there is just one, and put the following in slot $5$.
  4283. \begin{lstlisting}[escapechar=$]
  4284. exp_hi: INT . (4)
  4285. \end{lstlisting}
  4286. The period at the end of the rule triggers a completion action for the
  4287. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4288. So we advance the period and put the following in slot $5$.
  4289. \begin{lstlisting}[escapechar=$]
  4290. exp: exp "+" exp_hi . (2)
  4291. \end{lstlisting}
  4292. This triggers another completion action for the rules in slot $2$ that
  4293. have a period before \code{exp}.
  4294. \begin{lstlisting}[escapechar=$]
  4295. stmt: "print" "(" exp . ")" (0)
  4296. exp: exp . "+" exp_hi (2)
  4297. exp: exp . "-" exp_hi (2)
  4298. \end{lstlisting}
  4299. We scan the next input token \code{")"}, placing the following dotted
  4300. rule in slot $6$.
  4301. \begin{lstlisting}[escapechar=$]
  4302. stmt: "print" "(" exp ")" . (0)
  4303. \end{lstlisting}
  4304. This triggers the completion of \code{stmt} in slot $0$
  4305. \begin{lstlisting}
  4306. stmt_list: stmt . NEWLINE stmt_list (0)
  4307. \end{lstlisting}
  4308. The last input token is a \code{NEWLINE}, so we advance the period
  4309. and place the new dotted rule in slot $7$.
  4310. \begin{lstlisting}
  4311. stmt_list: stmt NEWLINE . stmt_list (0)
  4312. \end{lstlisting}
  4313. We are close to the end of parsing the input!
  4314. The period is before the \code{stmt\_list} nonterminal, so we
  4315. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4316. \begin{lstlisting}
  4317. stmt_list: . (7)
  4318. stmt_list: . stmt NEWLINE stmt_list (7)
  4319. stmt: . "print" "(" exp ")" (7)
  4320. stmt: . exp (7)
  4321. \end{lstlisting}
  4322. There is immediately an opportunity for completion of \code{stmt\_list},
  4323. so we add the following to slot $7$.
  4324. \begin{lstlisting}
  4325. stmt_list: stmt NEWLINE stmt_list . (0)
  4326. \end{lstlisting}
  4327. This triggers another completion action for \code{stmt\_list} in slot $0$
  4328. \begin{lstlisting}
  4329. lang_int: stmt_list . (0)
  4330. \end{lstlisting}
  4331. which in turn completes \code{lang\_int}, the start symbol of the
  4332. grammar, so the parsing of the input is complete.
  4333. For reference, we now give a general description of the Earley
  4334. algorithm.
  4335. \begin{enumerate}
  4336. \item The algorithm begins by initializing slot $0$ of the chart with the
  4337. grammar rule for the start symbol, placing a period at the beginning
  4338. of the right-hand side, and recording its starting position as $0$.
  4339. \item The algorithm repeatedly applies the following three kinds of
  4340. actions for as long as there are opportunities to do so.
  4341. \begin{itemize}
  4342. \item Prediction: if there is a rule in slot $k$ whose period comes
  4343. before a nonterminal, add the rules for that nonterminal into slot
  4344. $k$, placing a period at the beginning of their right-hand sides
  4345. and recording their starting position as $k$.
  4346. \item Scanning: If the token at position $k$ of the input string
  4347. matches the symbol after the period in a dotted rule in slot $k$
  4348. of the chart, advance the period in the dotted rule, adding
  4349. the result to slot $k+1$.
  4350. \item Completion: If a dotted rule in slot $k$ has a period at the
  4351. end, inspect the rules in the slot corresponding to the starting
  4352. position of the completed rule. If any of those rules have a
  4353. nonterminal following their period that matches the left-hand side
  4354. of the completed rule, then advance their period, placing the new
  4355. dotted rule in slot $k$.
  4356. \end{itemize}
  4357. While repeating these three actions, take care to never add
  4358. duplicate dotted rules to the chart.
  4359. \end{enumerate}
  4360. We have described how the Earley algorithm recognizes that an input
  4361. string matches a grammar, but we have not described how it builds a
  4362. parse tree. The basic idea is simple, but building parse trees in an
  4363. efficient way is more complex, requiring a data structure called a
  4364. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4365. to attach a partial parse tree to every dotted rule in the chart.
  4366. Initially, the tree node associated with a dotted rule has no
  4367. children. As the period moves to the right, the nodes from the
  4368. subparses are added as children to the tree node.
  4369. As mentioned at the beginning of this section, the Earley algorithm is
  4370. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4371. files that contain thousands of tokens in a reasonable amount of time,
  4372. but not millions.
  4373. %
  4374. In the next section we discuss the LALR(1) parsing algorithm, which is
  4375. efficient enough to use with even the largest of input files.
  4376. \section{The LALR(1) Algorithm}
  4377. \label{sec:lalr}
  4378. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4379. two phase approach in which it first compiles the grammar into a state
  4380. machine and then runs the state machine to parse an input string. The
  4381. second phase has time complexity $O(n)$ where $n$ is the number of
  4382. tokens in the input, so LALR(1) is the best one could hope for with
  4383. respect to efficiency.
  4384. %
  4385. A particularly influential implementation of LALR(1) is the
  4386. \texttt{yacc} parser generator by \citet{Johnson:1979qy}, which stands
  4387. for Yet Another Compiler Compiler.
  4388. %
  4389. The LALR(1) state machine uses a stack to record its progress in
  4390. parsing the input string. Each element of the stack is a pair: a
  4391. state number and a grammar symbol (a terminal or nonterminal). The
  4392. symbol characterizes the input that has been parsed so-far and the
  4393. state number is used to remember how to proceed once the next
  4394. symbol-worth of input has been parsed. Each state in the machine
  4395. represents where the parser stands in the parsing process with respect
  4396. to certain grammar rules. In particular, each state is associated with
  4397. a set of dotted rules.
  4398. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4399. (also called parse table) for the following simple but ambiguous
  4400. grammar:
  4401. \begin{lstlisting}[escapechar=$]
  4402. exp: INT
  4403. | exp "+" exp
  4404. stmt: "print" exp
  4405. start: stmt
  4406. \end{lstlisting}
  4407. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4408. read in a \lstinline{"print"} token, so the top of the stack is
  4409. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4410. the input according to grammar rule 1, which is signified by showing
  4411. rule 1 with a period after the \code{"print"} token and before the
  4412. \code{exp} nonterminal. There are several rules that could apply next,
  4413. both rule 2 and 3, so state 1 also shows those rules with a period at
  4414. the beginning of their right-hand sides. The edges between states
  4415. indicate which transitions the machine should make depending on the
  4416. next input token. So, for example, if the next input token is
  4417. \code{INT} then the parser will push \code{INT} and the target state 4
  4418. on the stack and transition to state 4. Suppose we are now at the end
  4419. of the input. In state 4 it says we should reduce by rule 3, so we pop
  4420. from the stack the same number of items as the number of symbols in
  4421. the right-hand side of the rule, in this case just one. We then
  4422. momentarily jump to the state at the top of the stack (state 1) and
  4423. then follow the goto edge that corresponds to the left-hand side of
  4424. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4425. state 3. (A slightly longer example parse is shown in
  4426. Figure~\ref{fig:shift-reduce}.)
  4427. \begin{figure}[htbp]
  4428. \centering
  4429. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4430. \caption{An LALR(1) parse table and a trace of an example run.}
  4431. \label{fig:shift-reduce}
  4432. \end{figure}
  4433. In general, the algorithm works as follows. Set the current state to
  4434. state $0$. Then repeat the following, looking at the next input token.
  4435. \begin{itemize}
  4436. \item If there there is a shift edge for the input token in the
  4437. current state, push the edge's target state and the input token on
  4438. the stack and proceed to the edge's target state.
  4439. \item If there is a reduce action for the input token in the current
  4440. state, pop $k$ elements from the stack, where $k$ is the number of
  4441. symbols in the right-hand side of the rule being reduced. Jump to
  4442. the state at the top of the stack and then follow the goto edge for
  4443. the nonterminal that matches the left-hand side of the rule that we
  4444. reducing by. Push the edge's target state and the nonterminal on the
  4445. stack.
  4446. \end{itemize}
  4447. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4448. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4449. algorithm does not know which action to take in this case. When a
  4450. state has both a shift and a reduce action for the same token, we say
  4451. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4452. will arise, for example, when trying to parse the input
  4453. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4454. the parser will be in state 6, and it will not know whether to
  4455. reduce to form an \code{exp} of \lstinline{1 + 2}, or whether it
  4456. should proceed by shifting the next \lstinline{+} from the input.
  4457. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4458. arises when there are two reduce actions in a state for the same
  4459. token. To understand which grammars gives rise to shift/reduce and
  4460. reduce/reduce conflicts, it helps to know how the parse table is
  4461. generated from the grammar, which we discuss next.
  4462. The parse table is generated one state at a time. State 0 represents
  4463. the start of the parser. We add the grammar rule for the start symbol
  4464. to this state with a period at the beginning of the right-hand side,
  4465. similar to the initialization phase of the Earley parser. If the
  4466. period appears immediately before another nonterminal, we add all the
  4467. rules with that nonterminal on the left-hand side. Again, we place a
  4468. period at the beginning of the right-hand side of each the new
  4469. rules. This process, called \emph{state closure}, is continued
  4470. until there are no more rules to add (similar to the prediction
  4471. actions of an Earley parser). We then examine each dotted rule in the
  4472. current state $I$. Suppose a dotted rule has the form $A ::=
  4473. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4474. are sequences of symbols. We create a new state, call it $J$. If $X$
  4475. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4476. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4477. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4478. state $J$. We start by adding all dotted rules from state $I$ that
  4479. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4480. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4481. the period moved past the $X$. (This is analogous to completion in
  4482. the Earley algorithm.) We then perform state closure on $J$. This
  4483. process repeats until there are no more states or edges to add.
  4484. We then mark states as accepting states if they have a dotted rule
  4485. that is the start rule with a period at the end. Also, to add
  4486. in the reduce actions, we look for any state containing a dotted rule
  4487. with a period at the end. Let $n$ be the rule number for this dotted
  4488. rule. We then put a reduce $n$ action into that state for every token
  4489. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4490. dotted rule with a period at the end. We therefore put a reduce by
  4491. rule 3 action into state 4 for every
  4492. token.
  4493. When inserting reduce actions, take care to spot any shift/reduce or
  4494. reduce/reduce conflicts. If there are any, abort the construction of
  4495. the parse table.
  4496. \begin{exercise}
  4497. \normalfont\normalsize
  4498. %
  4499. On a piece of paper, walk through the parse table generation process
  4500. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4501. your results against parse table in figure~\ref{fig:shift-reduce}.
  4502. \end{exercise}
  4503. \begin{exercise}
  4504. \normalfont\normalsize
  4505. %
  4506. Change the parser in your compiler for \LangVar{} to set the
  4507. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4508. all the \LangVar{} programs that you have created. In doing so, Lark
  4509. may signal an error due to shift/reduce or reduce/reduce conflicts
  4510. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4511. remove those conflicts.
  4512. \end{exercise}
  4513. \section{Further Reading}
  4514. In this chapter we have just scratched the surface of the field of
  4515. parsing, with the study of a very general but less efficient algorithm
  4516. (Earley) and with a more limited but highly efficient algorithm
  4517. (LALR). There are many more algorithms, and classes of grammars, that
  4518. fall between these two ends of the spectrum. We recommend the reader
  4519. to \citet{Aho:2006wb} for a thorough treatment of parsing.
  4520. Regarding lexical analysis, we described the specification language,
  4521. the regular expressions, but not the algorithms for recognizing them.
  4522. In short, regular expressions can be translated to nondeterministic
  4523. finite automata, which in turn are translated to finite automata. We
  4524. refer the reader again to \citet{Aho:2006wb} for all the details on
  4525. lexical analysis.
  4526. \fi}
  4527. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4528. \chapter{Register Allocation}
  4529. \label{ch:register-allocation-Lvar}
  4530. \setcounter{footnote}{0}
  4531. \index{subject}{register allocation}
  4532. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4533. storing variables on the procedure call stack. The CPU may require tens
  4534. to hundreds of cycles to access a location on the stack, whereas
  4535. accessing a register takes only a single cycle. In this chapter we
  4536. improve the efficiency of our generated code by storing some variables
  4537. in registers. The goal of register allocation is to fit as many
  4538. variables into registers as possible. Some programs have more
  4539. variables than registers, so we cannot always map each variable to a
  4540. different register. Fortunately, it is common for different variables
  4541. to be in use during different periods of time during program
  4542. execution, and in those cases we can map multiple variables to the
  4543. same register.
  4544. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4545. example. The source program is on the left and the output of
  4546. instruction selection is on the right. The program is almost
  4547. completely in the x86 assembly language, but it still uses variables.
  4548. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4549. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4550. the other hand, is used only after this point, so \code{x} and
  4551. \code{z} could share the same register.
  4552. \begin{figure}
  4553. \begin{tcolorbox}[colback=white]
  4554. \begin{minipage}{0.45\textwidth}
  4555. Example \LangVar{} program:
  4556. % var_test_28.rkt
  4557. {\if\edition\racketEd
  4558. \begin{lstlisting}
  4559. (let ([v 1])
  4560. (let ([w 42])
  4561. (let ([x (+ v 7)])
  4562. (let ([y x])
  4563. (let ([z (+ x w)])
  4564. (+ z (- y)))))))
  4565. \end{lstlisting}
  4566. \fi}
  4567. {\if\edition\pythonEd\pythonColor
  4568. \begin{lstlisting}
  4569. v = 1
  4570. w = 42
  4571. x = v + 7
  4572. y = x
  4573. z = x + w
  4574. print(z + (- y))
  4575. \end{lstlisting}
  4576. \fi}
  4577. \end{minipage}
  4578. \begin{minipage}{0.45\textwidth}
  4579. After instruction selection:
  4580. {\if\edition\racketEd
  4581. \begin{lstlisting}
  4582. locals-types:
  4583. x : Integer, y : Integer,
  4584. z : Integer, t : Integer,
  4585. v : Integer, w : Integer
  4586. start:
  4587. movq $1, v
  4588. movq $42, w
  4589. movq v, x
  4590. addq $7, x
  4591. movq x, y
  4592. movq x, z
  4593. addq w, z
  4594. movq y, t
  4595. negq t
  4596. movq z, %rax
  4597. addq t, %rax
  4598. jmp conclusion
  4599. \end{lstlisting}
  4600. \fi}
  4601. {\if\edition\pythonEd\pythonColor
  4602. \begin{lstlisting}
  4603. movq $1, v
  4604. movq $42, w
  4605. movq v, x
  4606. addq $7, x
  4607. movq x, y
  4608. movq x, z
  4609. addq w, z
  4610. movq y, tmp_0
  4611. negq tmp_0
  4612. movq z, tmp_1
  4613. addq tmp_0, tmp_1
  4614. movq tmp_1, %rdi
  4615. callq print_int
  4616. \end{lstlisting}
  4617. \fi}
  4618. \end{minipage}
  4619. \end{tcolorbox}
  4620. \caption{A running example for register allocation.}
  4621. \label{fig:reg-eg}
  4622. \end{figure}
  4623. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4624. compute where a variable is in use. Once we have that information, we
  4625. compute which variables are in use at the same time, i.e., which ones
  4626. \emph{interfere}\index{subject}{interfere} with each other, and
  4627. represent this relation as an undirected graph whose vertices are
  4628. variables and edges indicate when two variables interfere
  4629. (section~\ref{sec:build-interference}). We then model register
  4630. allocation as a graph coloring problem
  4631. (section~\ref{sec:graph-coloring}).
  4632. If we run out of registers despite these efforts, we place the
  4633. remaining variables on the stack, similarly to how we handled
  4634. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4635. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4636. location. The decision to spill a variable is handled as part of the
  4637. graph coloring process.
  4638. We make the simplifying assumption that each variable is assigned to
  4639. one location (a register or stack address). A more sophisticated
  4640. approach is to assign a variable to one or more locations in different
  4641. regions of the program. For example, if a variable is used many times
  4642. in short sequence and then used again only after many other
  4643. instructions, it could be more efficient to assign the variable to a
  4644. register during the initial sequence and then move it to the stack for
  4645. the rest of its lifetime. We refer the interested reader to
  4646. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4647. approach.
  4648. % discuss prioritizing variables based on how much they are used.
  4649. \section{Registers and Calling Conventions}
  4650. \label{sec:calling-conventions}
  4651. \index{subject}{calling conventions}
  4652. As we perform register allocation, we must be aware of the
  4653. \emph{calling conventions} \index{subject}{calling conventions} that
  4654. govern how functions calls are performed in x86.
  4655. %
  4656. Even though \LangVar{} does not include programmer-defined functions,
  4657. our generated code includes a \code{main} function that is called by
  4658. the operating system and our generated code contains calls to the
  4659. \code{read\_int} function.
  4660. Function calls require coordination between two pieces of code that
  4661. may be written by different programmers or generated by different
  4662. compilers. Here we follow the System V calling conventions that are
  4663. used by the GNU C compiler on Linux and
  4664. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4665. %
  4666. The calling conventions include rules about how functions share the
  4667. use of registers. In particular, the caller is responsible for freeing
  4668. some registers prior to the function call for use by the callee.
  4669. These are called the \emph{caller-saved registers}
  4670. \index{subject}{caller-saved registers}
  4671. and they are
  4672. \begin{lstlisting}
  4673. rax rcx rdx rsi rdi r8 r9 r10 r11
  4674. \end{lstlisting}
  4675. On the other hand, the callee is responsible for preserving the values
  4676. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4677. which are
  4678. \begin{lstlisting}
  4679. rsp rbp rbx r12 r13 r14 r15
  4680. \end{lstlisting}
  4681. We can think about this caller/callee convention from two points of
  4682. view, the caller view and the callee view, as follows:
  4683. \begin{itemize}
  4684. \item The caller should assume that all the caller-saved registers get
  4685. overwritten with arbitrary values by the callee. On the other hand,
  4686. the caller can safely assume that all the callee-saved registers
  4687. retain their original values.
  4688. \item The callee can freely use any of the caller-saved registers.
  4689. However, if the callee wants to use a callee-saved register, the
  4690. callee must arrange to put the original value back in the register
  4691. prior to returning to the caller. This can be accomplished by saving
  4692. the value to the stack in the prelude of the function and restoring
  4693. the value in the conclusion of the function.
  4694. \end{itemize}
  4695. In x86, registers are also used for passing arguments to a function
  4696. and for the return value. In particular, the first six arguments of a
  4697. function are passed in the following six registers, in this order.
  4698. \index{subject}{argument-passing registers}
  4699. \index{subject}{parameter-passing registers}
  4700. \begin{lstlisting}
  4701. rdi rsi rdx rcx r8 r9
  4702. \end{lstlisting}
  4703. If there are more than six arguments, the convention is to use
  4704. space on the frame of the caller for the rest of the
  4705. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4706. need more than six arguments.
  4707. %
  4708. \racket{For now, the only function we care about is \code{read\_int},
  4709. which takes zero arguments.}
  4710. %
  4711. \python{For now, the only functions we care about are \code{read\_int}
  4712. and \code{print\_int}, which take zero and one argument, respectively.}
  4713. %
  4714. The register \code{rax} is used for the return value of a function.
  4715. The next question is how these calling conventions impact register
  4716. allocation. Consider the \LangVar{} program presented in
  4717. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4718. example from the caller point of view and then from the callee point
  4719. of view. We refer to a variable that is in use during a function call
  4720. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4721. The program makes two calls to \READOP{}. The variable \code{x} is
  4722. call-live because it is in use during the second call to \READOP{}; we
  4723. must ensure that the value in \code{x} does not get overwritten during
  4724. the call to \READOP{}. One obvious approach is to save all the values
  4725. that reside in caller-saved registers to the stack prior to each
  4726. function call and to restore them after each call. That way, if the
  4727. register allocator chooses to assign \code{x} to a caller-saved
  4728. register, its value will be preserved across the call to \READOP{}.
  4729. However, saving and restoring to the stack is relatively slow. If
  4730. \code{x} is not used many times, it may be better to assign \code{x}
  4731. to a stack location in the first place. Or better yet, if we can
  4732. arrange for \code{x} to be placed in a callee-saved register, then it
  4733. won't need to be saved and restored during function calls.
  4734. We recommend an approach that captures these issues in the
  4735. interference graph, without complicating the graph coloring algorithm.
  4736. During liveness analysis we know which variables are call-live because
  4737. we compute which variables are in use at every instruction
  4738. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4739. interference graph (section~\ref{sec:build-interference}), we can
  4740. place an edge in the interference graph between each call-live
  4741. variable and the caller-saved registers. This will prevent the graph
  4742. coloring algorithm from assigning call-live variables to caller-saved
  4743. registers.
  4744. On the other hand, for variables that are not call-live, we prefer
  4745. placing them in caller-saved registers to leave more room for
  4746. call-live variables in the callee-saved registers. This can also be
  4747. implemented without complicating the graph coloring algorithm. We
  4748. recommend that the graph coloring algorithm assign variables to
  4749. natural numbers, choosing the lowest number for which there is no
  4750. interference. After the coloring is complete, we map the numbers to
  4751. registers and stack locations: mapping the lowest numbers to
  4752. caller-saved registers, the next lowest to callee-saved registers, and
  4753. the largest numbers to stack locations. This ordering gives preference
  4754. to registers over stack locations and to caller-saved registers over
  4755. callee-saved registers.
  4756. Returning to the example in
  4757. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4758. generated x86 code on the right-hand side. Variable \code{x} is
  4759. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4760. in a safe place during the second call to \code{read\_int}. Next,
  4761. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4762. because \code{y} is not a call-live variable.
  4763. We have completed the analysis from the caller point of view, so now
  4764. we switch to the callee point of view, focusing on the prelude and
  4765. conclusion of the \code{main} function. As usual, the prelude begins
  4766. with saving the \code{rbp} register to the stack and setting the
  4767. \code{rbp} to the current stack pointer. We now know why it is
  4768. necessary to save the \code{rbp}: it is a callee-saved register. The
  4769. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4770. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4771. (\code{x}). The other callee-saved registers are not saved in the
  4772. prelude because they are not used. The prelude subtracts 8 bytes from
  4773. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4774. conclusion, we see that \code{rbx} is restored from the stack with a
  4775. \code{popq} instruction.
  4776. \index{subject}{prelude}\index{subject}{conclusion}
  4777. \begin{figure}[tp]
  4778. \begin{tcolorbox}[colback=white]
  4779. \begin{minipage}{0.45\textwidth}
  4780. Example \LangVar{} program:
  4781. %var_test_14.rkt
  4782. {\if\edition\racketEd
  4783. \begin{lstlisting}
  4784. (let ([x (read)])
  4785. (let ([y (read)])
  4786. (+ (+ x y) 42)))
  4787. \end{lstlisting}
  4788. \fi}
  4789. {\if\edition\pythonEd\pythonColor
  4790. \begin{lstlisting}
  4791. x = input_int()
  4792. y = input_int()
  4793. print((x + y) + 42)
  4794. \end{lstlisting}
  4795. \fi}
  4796. \end{minipage}
  4797. \begin{minipage}{0.45\textwidth}
  4798. Generated x86 assembly:
  4799. {\if\edition\racketEd
  4800. \begin{lstlisting}
  4801. start:
  4802. callq read_int
  4803. movq %rax, %rbx
  4804. callq read_int
  4805. movq %rax, %rcx
  4806. addq %rcx, %rbx
  4807. movq %rbx, %rax
  4808. addq $42, %rax
  4809. jmp _conclusion
  4810. .globl main
  4811. main:
  4812. pushq %rbp
  4813. movq %rsp, %rbp
  4814. pushq %rbx
  4815. subq $8, %rsp
  4816. jmp start
  4817. conclusion:
  4818. addq $8, %rsp
  4819. popq %rbx
  4820. popq %rbp
  4821. retq
  4822. \end{lstlisting}
  4823. \fi}
  4824. {\if\edition\pythonEd\pythonColor
  4825. \begin{lstlisting}
  4826. .globl main
  4827. main:
  4828. pushq %rbp
  4829. movq %rsp, %rbp
  4830. pushq %rbx
  4831. subq $8, %rsp
  4832. callq read_int
  4833. movq %rax, %rbx
  4834. callq read_int
  4835. movq %rax, %rcx
  4836. movq %rbx, %rdx
  4837. addq %rcx, %rdx
  4838. movq %rdx, %rcx
  4839. addq $42, %rcx
  4840. movq %rcx, %rdi
  4841. callq print_int
  4842. addq $8, %rsp
  4843. popq %rbx
  4844. popq %rbp
  4845. retq
  4846. \end{lstlisting}
  4847. \fi}
  4848. \end{minipage}
  4849. \end{tcolorbox}
  4850. \caption{An example with function calls.}
  4851. \label{fig:example-calling-conventions}
  4852. \end{figure}
  4853. %\clearpage
  4854. \section{Liveness Analysis}
  4855. \label{sec:liveness-analysis-Lvar}
  4856. \index{subject}{liveness analysis}
  4857. The \code{uncover\_live} \racket{pass}\python{function} performs
  4858. \emph{liveness analysis}; that is, it discovers which variables are
  4859. in use in different regions of a program.
  4860. %
  4861. A variable or register is \emph{live} at a program point if its
  4862. current value is used at some later point in the program. We refer to
  4863. variables, stack locations, and registers collectively as
  4864. \emph{locations}.
  4865. %
  4866. Consider the following code fragment in which there are two writes to
  4867. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4868. time?
  4869. \begin{center}
  4870. \begin{minipage}{0.96\textwidth}
  4871. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4872. movq $5, a
  4873. movq $30, b
  4874. movq a, c
  4875. movq $10, b
  4876. addq b, c
  4877. \end{lstlisting}
  4878. \end{minipage}
  4879. \end{center}
  4880. The answer is no, because \code{a} is live from line 1 to 3 and
  4881. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4882. line 2 is never used because it is overwritten (line 4) before the
  4883. next read (line 5).
  4884. The live locations for each instruction can be computed by traversing
  4885. the instruction sequence back to front (i.e., backward in execution
  4886. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4887. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4888. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4889. locations before instruction $I_k$. \racket{We recommend representing
  4890. these sets with the Racket \code{set} data structure described in
  4891. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4892. with the Python
  4893. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4894. data structure.}
  4895. {\if\edition\racketEd
  4896. \begin{figure}[tp]
  4897. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4898. \small
  4899. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4900. A \emph{set} is an unordered collection of elements without duplicates.
  4901. Here are some of the operations defined on sets.
  4902. \index{subject}{set}
  4903. \begin{description}
  4904. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4905. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4906. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4907. difference of the two sets.
  4908. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4909. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4910. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4911. \end{description}
  4912. \end{tcolorbox}
  4913. %\end{wrapfigure}
  4914. \caption{The \code{set} data structure.}
  4915. \label{fig:set}
  4916. \end{figure}
  4917. \fi}
  4918. The live locations after an instruction are always the same as the
  4919. live locations before the next instruction.
  4920. \index{subject}{live-after} \index{subject}{live-before}
  4921. \begin{equation} \label{eq:live-after-before-next}
  4922. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4923. \end{equation}
  4924. To start things off, there are no live locations after the last
  4925. instruction, so
  4926. \begin{equation}\label{eq:live-last-empty}
  4927. L_{\mathsf{after}}(n) = \emptyset
  4928. \end{equation}
  4929. We then apply the following rule repeatedly, traversing the
  4930. instruction sequence back to front.
  4931. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4932. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4933. \end{equation}
  4934. where $W(k)$ are the locations written to by instruction $I_k$, and
  4935. $R(k)$ are the locations read by instruction $I_k$.
  4936. {\if\edition\racketEd
  4937. %
  4938. There is a special case for \code{jmp} instructions. The locations
  4939. that are live before a \code{jmp} should be the locations in
  4940. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4941. maintaining an alist named \code{label->live} that maps each label to
  4942. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4943. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4944. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4945. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4946. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4947. %
  4948. \fi}
  4949. Let us walk through the previous example, applying these formulas
  4950. starting with the instruction on line 5 of the code fragment. We
  4951. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4952. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4953. $\emptyset$ because it is the last instruction
  4954. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4955. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4956. variables \code{b} and \code{c}
  4957. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4958. \[
  4959. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4960. \]
  4961. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4962. the live-before set from line 5 to be the live-after set for this
  4963. instruction (formula~\eqref{eq:live-after-before-next}).
  4964. \[
  4965. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4966. \]
  4967. This move instruction writes to \code{b} and does not read from any
  4968. variables, so we have the following live-before set
  4969. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4970. \[
  4971. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4972. \]
  4973. The live-before for instruction \code{movq a, c}
  4974. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4975. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4976. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4977. variable that is not live and does not read from a variable.
  4978. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4979. because it writes to variable \code{a}.
  4980. \begin{figure}[tbp]
  4981. \centering
  4982. \begin{tcolorbox}[colback=white]
  4983. \hspace{10pt}
  4984. \begin{minipage}{0.4\textwidth}
  4985. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4986. movq $5, a
  4987. movq $30, b
  4988. movq a, c
  4989. movq $10, b
  4990. addq b, c
  4991. \end{lstlisting}
  4992. \end{minipage}
  4993. \vrule\hspace{10pt}
  4994. \begin{minipage}{0.45\textwidth}
  4995. \begin{align*}
  4996. L_{\mathsf{before}}(1)= \emptyset,
  4997. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4998. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4999. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5000. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5001. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5002. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5003. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5004. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5005. L_{\mathsf{after}}(5)= \emptyset
  5006. \end{align*}
  5007. \end{minipage}
  5008. \end{tcolorbox}
  5009. \caption{Example output of liveness analysis on a short example.}
  5010. \label{fig:liveness-example-0}
  5011. \end{figure}
  5012. \begin{exercise}\normalfont\normalsize
  5013. Perform liveness analysis by hand on the running example in
  5014. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5015. sets for each instruction. Compare your answers to the solution
  5016. shown in figure~\ref{fig:live-eg}.
  5017. \end{exercise}
  5018. \begin{figure}[tp]
  5019. \hspace{20pt}
  5020. \begin{minipage}{0.55\textwidth}
  5021. \begin{tcolorbox}[colback=white]
  5022. {\if\edition\racketEd
  5023. \begin{lstlisting}
  5024. |$\{\ttm{rsp}\}$|
  5025. movq $1, v
  5026. |$\{\ttm{v},\ttm{rsp}\}$|
  5027. movq $42, w
  5028. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5029. movq v, x
  5030. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5031. addq $7, x
  5032. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5033. movq x, y
  5034. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5035. movq x, z
  5036. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5037. addq w, z
  5038. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5039. movq y, t
  5040. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5041. negq t
  5042. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5043. movq z, %rax
  5044. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5045. addq t, %rax
  5046. |$\{\ttm{rax},\ttm{rsp}\}$|
  5047. jmp conclusion
  5048. \end{lstlisting}
  5049. \fi}
  5050. {\if\edition\pythonEd\pythonColor
  5051. \begin{lstlisting}
  5052. movq $1, v
  5053. |$\{\ttm{v}\}$|
  5054. movq $42, w
  5055. |$\{\ttm{w}, \ttm{v}\}$|
  5056. movq v, x
  5057. |$\{\ttm{w}, \ttm{x}\}$|
  5058. addq $7, x
  5059. |$\{\ttm{w}, \ttm{x}\}$|
  5060. movq x, y
  5061. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5062. movq x, z
  5063. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5064. addq w, z
  5065. |$\{\ttm{y}, \ttm{z}\}$|
  5066. movq y, tmp_0
  5067. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5068. negq tmp_0
  5069. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5070. movq z, tmp_1
  5071. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5072. addq tmp_0, tmp_1
  5073. |$\{\ttm{tmp\_1}\}$|
  5074. movq tmp_1, %rdi
  5075. |$\{\ttm{rdi}\}$|
  5076. callq print_int
  5077. |$\{\}$|
  5078. \end{lstlisting}
  5079. \fi}
  5080. \end{tcolorbox}
  5081. \end{minipage}
  5082. \caption{The running example annotated with live-after sets.}
  5083. \label{fig:live-eg}
  5084. \end{figure}
  5085. \begin{exercise}\normalfont\normalsize
  5086. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5087. %
  5088. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5089. field of the \code{Block} structure.}
  5090. %
  5091. \python{Return a dictionary that maps each instruction to its
  5092. live-after set.}
  5093. %
  5094. \racket{We recommend creating an auxiliary function that takes a list
  5095. of instructions and an initial live-after set (typically empty) and
  5096. returns the list of live-after sets.}
  5097. %
  5098. We recommend creating auxiliary functions to (1) compute the set
  5099. of locations that appear in an \Arg{}, (2) compute the locations read
  5100. by an instruction (the $R$ function), and (3) the locations written by
  5101. an instruction (the $W$ function). The \code{callq} instruction should
  5102. include all the caller-saved registers in its write set $W$ because
  5103. the calling convention says that those registers may be written to
  5104. during the function call. Likewise, the \code{callq} instruction
  5105. should include the appropriate argument-passing registers in its
  5106. read set $R$, depending on the arity of the function being
  5107. called. (This is why the abstract syntax for \code{callq} includes the
  5108. arity.)
  5109. \end{exercise}
  5110. %\clearpage
  5111. \section{Build the Interference Graph}
  5112. \label{sec:build-interference}
  5113. {\if\edition\racketEd
  5114. \begin{figure}[tp]
  5115. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5116. \small
  5117. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5118. A \emph{graph} is a collection of vertices and edges where each
  5119. edge connects two vertices. A graph is \emph{directed} if each
  5120. edge points from a source to a target. Otherwise the graph is
  5121. \emph{undirected}.
  5122. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5123. \begin{description}
  5124. %% We currently don't use directed graphs. We instead use
  5125. %% directed multi-graphs. -Jeremy
  5126. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5127. directed graph from a list of edges. Each edge is a list
  5128. containing the source and target vertex.
  5129. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5130. undirected graph from a list of edges. Each edge is represented by
  5131. a list containing two vertices.
  5132. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5133. inserts a vertex into the graph.
  5134. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5135. inserts an edge between the two vertices.
  5136. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5137. returns a sequence of vertices adjacent to the vertex.
  5138. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5139. returns a sequence of all vertices in the graph.
  5140. \end{description}
  5141. \end{tcolorbox}
  5142. %\end{wrapfigure}
  5143. \caption{The Racket \code{graph} package.}
  5144. \label{fig:graph}
  5145. \end{figure}
  5146. \fi}
  5147. On the basis of the liveness analysis, we know where each location is
  5148. live. However, during register allocation, we need to answer
  5149. questions of the specific form: are locations $u$ and $v$ live at the
  5150. same time? (If so, they cannot be assigned to the same register.) To
  5151. make this question more efficient to answer, we create an explicit
  5152. data structure, an \emph{interference
  5153. graph}\index{subject}{interference graph}. An interference graph is
  5154. an undirected graph that has a node for every variable and register
  5155. and has an edge between two nodes if they are
  5156. live at the same time, that is, if they interfere with each other.
  5157. %
  5158. \racket{We recommend using the Racket \code{graph} package
  5159. (figure~\ref{fig:graph}) to represent the interference graph.}
  5160. %
  5161. \python{We provide implementations of directed and undirected graph
  5162. data structures in the file \code{graph.py} of the support code.}
  5163. A straightforward way to compute the interference graph is to look at
  5164. the set of live locations between each instruction and add an edge to
  5165. the graph for every pair of variables in the same set. This approach
  5166. is less than ideal for two reasons. First, it can be expensive because
  5167. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5168. locations. Second, in the special case in which two locations hold the
  5169. same value (because one was assigned to the other), they can be live
  5170. at the same time without interfering with each other.
  5171. A better way to compute the interference graph is to focus on
  5172. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5173. must not overwrite something in a live location. So for each
  5174. instruction, we create an edge between the locations being written to
  5175. and the live locations. (However, a location never interferes with
  5176. itself.) For the \key{callq} instruction, we consider all the
  5177. caller-saved registers to have been written to, so an edge is added
  5178. between every live variable and every caller-saved register. Also, for
  5179. \key{movq} there is the special case of two variables holding the same
  5180. value. If a live variable $v$ is the same as the source of the
  5181. \key{movq}, then there is no need to add an edge between $v$ and the
  5182. destination, because they both hold the same value.
  5183. %
  5184. Hence we have the following two rules:
  5185. \begin{enumerate}
  5186. \item If instruction $I_k$ is a move instruction of the form
  5187. \key{movq} $s$\key{,} $d$, then for every $v \in
  5188. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5189. $(d,v)$.
  5190. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5191. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5192. $(d,v)$.
  5193. \end{enumerate}
  5194. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5195. these rules to each instruction. We highlight a few of the
  5196. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5197. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5198. so \code{v} interferes with \code{rsp}.}
  5199. %
  5200. \python{The first instruction is \lstinline{movq $1, v}, and the
  5201. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5202. no interference because $\ttm{v}$ is the destination of the move.}
  5203. %
  5204. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5205. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5206. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5207. %
  5208. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5209. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5210. $\ttm{x}$ interferes with \ttm{w}.}
  5211. %
  5212. \racket{The next instruction is \lstinline{movq x, y}, and the
  5213. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5214. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5215. \ttm{x} because \ttm{x} is the source of the move and therefore
  5216. \ttm{x} and \ttm{y} hold the same value.}
  5217. %
  5218. \python{The next instruction is \lstinline{movq x, y}, and the
  5219. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5220. applies, so \ttm{y} interferes with \ttm{w} but not
  5221. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5222. \ttm{x} and \ttm{y} hold the same value.}
  5223. %
  5224. Figure~\ref{fig:interference-results} lists the interference results
  5225. for all the instructions, and the resulting interference graph is
  5226. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5227. the interference graph in figure~\ref{fig:interfere} because there
  5228. were no interference edges involving registers and we did not wish to
  5229. clutter the graph, but in general one needs to include all the
  5230. registers in the interference graph.
  5231. \begin{figure}[tbp]
  5232. \begin{tcolorbox}[colback=white]
  5233. \begin{quote}
  5234. {\if\edition\racketEd
  5235. \begin{tabular}{ll}
  5236. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5237. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5238. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5239. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5240. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5241. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5242. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5243. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5244. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5245. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5246. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5247. \lstinline!jmp conclusion!& no interference.
  5248. \end{tabular}
  5249. \fi}
  5250. {\if\edition\pythonEd\pythonColor
  5251. \begin{tabular}{ll}
  5252. \lstinline!movq $1, v!& no interference\\
  5253. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5254. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5255. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5256. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5257. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5258. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5259. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5260. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5261. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5262. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5263. \lstinline!movq tmp_1, %rdi! & no interference \\
  5264. \lstinline!callq print_int!& no interference.
  5265. \end{tabular}
  5266. \fi}
  5267. \end{quote}
  5268. \end{tcolorbox}
  5269. \caption{Interference results for the running example.}
  5270. \label{fig:interference-results}
  5271. \end{figure}
  5272. \begin{figure}[tbp]
  5273. \begin{tcolorbox}[colback=white]
  5274. \large
  5275. {\if\edition\racketEd
  5276. \[
  5277. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5278. \node (rax) at (0,0) {$\ttm{rax}$};
  5279. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5280. \node (t1) at (0,2) {$\ttm{t}$};
  5281. \node (z) at (3,2) {$\ttm{z}$};
  5282. \node (x) at (6,2) {$\ttm{x}$};
  5283. \node (y) at (3,0) {$\ttm{y}$};
  5284. \node (w) at (6,0) {$\ttm{w}$};
  5285. \node (v) at (9,0) {$\ttm{v}$};
  5286. \draw (t1) to (rax);
  5287. \draw (t1) to (z);
  5288. \draw (z) to (y);
  5289. \draw (z) to (w);
  5290. \draw (x) to (w);
  5291. \draw (y) to (w);
  5292. \draw (v) to (w);
  5293. \draw (v) to (rsp);
  5294. \draw (w) to (rsp);
  5295. \draw (x) to (rsp);
  5296. \draw (y) to (rsp);
  5297. \path[-.,bend left=15] (z) edge node {} (rsp);
  5298. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5299. \draw (rax) to (rsp);
  5300. \end{tikzpicture}
  5301. \]
  5302. \fi}
  5303. {\if\edition\pythonEd\pythonColor
  5304. \[
  5305. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5306. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5307. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5308. \node (z) at (3,2) {$\ttm{z}$};
  5309. \node (x) at (6,2) {$\ttm{x}$};
  5310. \node (y) at (3,0) {$\ttm{y}$};
  5311. \node (w) at (6,0) {$\ttm{w}$};
  5312. \node (v) at (9,0) {$\ttm{v}$};
  5313. \draw (t0) to (t1);
  5314. \draw (t0) to (z);
  5315. \draw (z) to (y);
  5316. \draw (z) to (w);
  5317. \draw (x) to (w);
  5318. \draw (y) to (w);
  5319. \draw (v) to (w);
  5320. \end{tikzpicture}
  5321. \]
  5322. \fi}
  5323. \end{tcolorbox}
  5324. \caption{The interference graph of the example program.}
  5325. \label{fig:interfere}
  5326. \end{figure}
  5327. %% Our next concern is to choose a data structure for representing the
  5328. %% interference graph. There are many choices for how to represent a
  5329. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  5330. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  5331. %% data structure is to study the algorithm that uses the data structure,
  5332. %% determine what operations need to be performed, and then choose the
  5333. %% data structure that provide the most efficient implementations of
  5334. %% those operations. Often times the choice of data structure can have an
  5335. %% effect on the time complexity of the algorithm, as it does here. If
  5336. %% you skim the next section, you will see that the register allocation
  5337. %% algorithm needs to ask the graph for all its vertices and, given a
  5338. %% vertex, it needs to known all the adjacent vertices. Thus, the
  5339. %% correct choice of graph representation is that of an adjacency
  5340. %% list. There are helper functions in \code{utilities.rkt} for
  5341. %% representing graphs using the adjacency list representation:
  5342. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  5343. %% (Appendix~\ref{appendix:utilities}).
  5344. %% %
  5345. %% \margincomment{\footnotesize To do: change to use the
  5346. %% Racket graph library. \\ --Jeremy}
  5347. %% %
  5348. %% In particular, those functions use a hash table to map each vertex to
  5349. %% the set of adjacent vertices, and the sets are represented using
  5350. %% Racket's \key{set}, which is also a hash table.
  5351. \begin{exercise}\normalfont\normalsize
  5352. \racket{Implement the compiler pass named \code{build\_interference} according
  5353. to the algorithm suggested here. We recommend using the Racket
  5354. \code{graph} package to create and inspect the interference graph.
  5355. The output graph of this pass should be stored in the $\itm{info}$ field of
  5356. the program, under the key \code{conflicts}.}
  5357. %
  5358. \python{Implement a function named \code{build\_interference}
  5359. according to the algorithm suggested above that
  5360. returns the interference graph.}
  5361. \end{exercise}
  5362. \section{Graph Coloring via Sudoku}
  5363. \label{sec:graph-coloring}
  5364. \index{subject}{graph coloring}
  5365. \index{subject}{sudoku}
  5366. \index{subject}{color}
  5367. We come to the main event discussed in this chapter, mapping variables
  5368. to registers and stack locations. Variables that interfere with each
  5369. other must be mapped to different locations. In terms of the
  5370. interference graph, this means that adjacent vertices must be mapped
  5371. to different locations. If we think of locations as colors, the
  5372. register allocation problem becomes the graph coloring
  5373. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5374. The reader may be more familiar with the graph coloring problem than he
  5375. or she realizes; the popular game of sudoku is an instance of the
  5376. graph coloring problem. The following describes how to build a graph
  5377. out of an initial sudoku board.
  5378. \begin{itemize}
  5379. \item There is one vertex in the graph for each sudoku square.
  5380. \item There is an edge between two vertices if the corresponding squares
  5381. are in the same row, in the same column, or in the same $3\times 3$ region.
  5382. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5383. \item On the basis of the initial assignment of numbers to squares on the
  5384. sudoku board, assign the corresponding colors to the corresponding
  5385. vertices in the graph.
  5386. \end{itemize}
  5387. If you can color the remaining vertices in the graph with the nine
  5388. colors, then you have also solved the corresponding game of sudoku.
  5389. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5390. the corresponding graph with colored vertices. Here we use a
  5391. monochrome representation of colors, mapping the sudoku number 1 to
  5392. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5393. of the vertices (the colored ones) because showing edges for all the
  5394. vertices would make the graph unreadable.
  5395. \begin{figure}[tbp]
  5396. \begin{tcolorbox}[colback=white]
  5397. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5398. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5399. \end{tcolorbox}
  5400. \caption{A sudoku game board and the corresponding colored graph.}
  5401. \label{fig:sudoku-graph}
  5402. \end{figure}
  5403. Some techniques for playing sudoku correspond to heuristics used in
  5404. graph coloring algorithms. For example, one of the basic techniques
  5405. for sudoku is called Pencil Marks. The idea is to use a process of
  5406. elimination to determine what numbers are no longer available for a
  5407. square and to write those numbers in the square (writing very
  5408. small). For example, if the number $1$ is assigned to a square, then
  5409. write the pencil mark $1$ in all the squares in the same row, column,
  5410. and region to indicate that $1$ is no longer an option for those other
  5411. squares.
  5412. %
  5413. The Pencil Marks technique corresponds to the notion of
  5414. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5415. saturation of a vertex, in sudoku terms, is the set of numbers that
  5416. are no longer available. In graph terminology, we have the following
  5417. definition:
  5418. \begin{equation*}
  5419. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5420. \text{ and } \mathrm{color}(v) = c \}
  5421. \end{equation*}
  5422. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5423. edge with $u$.
  5424. The Pencil Marks technique leads to a simple strategy for filling in
  5425. numbers: if there is a square with only one possible number left, then
  5426. choose that number! But what if there are no squares with only one
  5427. possibility left? One brute-force approach is to try them all: choose
  5428. the first one, and if that ultimately leads to a solution, great. If
  5429. not, backtrack and choose the next possibility. One good thing about
  5430. Pencil Marks is that it reduces the degree of branching in the search
  5431. tree. Nevertheless, backtracking can be terribly time consuming. One
  5432. way to reduce the amount of backtracking is to use the
  5433. most-constrained-first heuristic (aka minimum remaining
  5434. values)~\citep{Russell2003}. That is, in choosing a square, always
  5435. choose one with the fewest possibilities left (the vertex with the
  5436. highest saturation). The idea is that choosing highly constrained
  5437. squares earlier rather than later is better, because later on there may
  5438. not be any possibilities left in the highly saturated squares.
  5439. However, register allocation is easier than sudoku, because the
  5440. register allocator can fall back to assigning variables to stack
  5441. locations when the registers run out. Thus, it makes sense to replace
  5442. backtracking with greedy search: make the best choice at the time and
  5443. keep going. We still wish to minimize the number of colors needed, so
  5444. we use the most-constrained-first heuristic in the greedy search.
  5445. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5446. algorithm for register allocation based on saturation and the
  5447. most-constrained-first heuristic. It is roughly equivalent to the
  5448. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5449. sudoku, the algorithm represents colors with integers. The integers
  5450. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5451. register allocation. In particular, we recommend the following
  5452. correspondence, with $k=11$.
  5453. \begin{lstlisting}
  5454. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5455. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5456. \end{lstlisting}
  5457. The integers $k$ and larger correspond to stack locations. The
  5458. registers that are not used for register allocation, such as
  5459. \code{rax}, are assigned to negative integers. In particular, we
  5460. recommend the following correspondence.
  5461. \begin{lstlisting}
  5462. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5463. \end{lstlisting}
  5464. %% One might wonder why we include registers at all in the liveness
  5465. %% analysis and interference graph. For example, we never allocate a
  5466. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5467. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5468. %% to use register for passing arguments to functions, it will be
  5469. %% necessary for those registers to appear in the interference graph
  5470. %% because those registers will also be assigned to variables, and we
  5471. %% don't want those two uses to encroach on each other. Regarding
  5472. %% registers such as \code{rax} and \code{rsp} that are not used for
  5473. %% variables, we could omit them from the interference graph but that
  5474. %% would require adding special cases to our algorithm, which would
  5475. %% complicate the logic for little gain.
  5476. \begin{figure}[btp]
  5477. \begin{tcolorbox}[colback=white]
  5478. \centering
  5479. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5480. Algorithm: DSATUR
  5481. Input: A graph |$G$|
  5482. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5483. |$W \gets \mathrm{vertices}(G)$|
  5484. while |$W \neq \emptyset$| do
  5485. pick a vertex |$u$| from |$W$| with the highest saturation,
  5486. breaking ties randomly
  5487. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5488. |$\mathrm{color}[u] \gets c$|
  5489. |$W \gets W - \{u\}$|
  5490. \end{lstlisting}
  5491. \end{tcolorbox}
  5492. \caption{The saturation-based greedy graph coloring algorithm.}
  5493. \label{fig:satur-algo}
  5494. \end{figure}
  5495. {\if\edition\racketEd
  5496. With the DSATUR algorithm in hand, let us return to the running
  5497. example and consider how to color the interference graph shown in
  5498. figure~\ref{fig:interfere}.
  5499. %
  5500. We start by assigning each register node to its own color. For
  5501. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5502. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5503. (To reduce clutter in the intereference graph, we elide nodes
  5504. that do not have intereference edges, such as \code{rcx}.)
  5505. The variables are not yet colored, so they are annotated with a dash. We
  5506. then update the saturation for vertices that are adjacent to a
  5507. register, obtaining the following annotated graph. For example, the
  5508. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5509. \code{rax} and \code{rsp}.
  5510. \[
  5511. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5512. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5513. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5514. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5515. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5516. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5517. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5518. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5519. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5520. \draw (t1) to (rax);
  5521. \draw (t1) to (z);
  5522. \draw (z) to (y);
  5523. \draw (z) to (w);
  5524. \draw (x) to (w);
  5525. \draw (y) to (w);
  5526. \draw (v) to (w);
  5527. \draw (v) to (rsp);
  5528. \draw (w) to (rsp);
  5529. \draw (x) to (rsp);
  5530. \draw (y) to (rsp);
  5531. \path[-.,bend left=15] (z) edge node {} (rsp);
  5532. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5533. \draw (rax) to (rsp);
  5534. \end{tikzpicture}
  5535. \]
  5536. The algorithm says to select a maximally saturated vertex. So, we pick
  5537. $\ttm{t}$ and color it with the first available integer, which is
  5538. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5539. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5540. \[
  5541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5542. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5543. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5544. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5545. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5546. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5547. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5548. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5549. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5550. \draw (t1) to (rax);
  5551. \draw (t1) to (z);
  5552. \draw (z) to (y);
  5553. \draw (z) to (w);
  5554. \draw (x) to (w);
  5555. \draw (y) to (w);
  5556. \draw (v) to (w);
  5557. \draw (v) to (rsp);
  5558. \draw (w) to (rsp);
  5559. \draw (x) to (rsp);
  5560. \draw (y) to (rsp);
  5561. \path[-.,bend left=15] (z) edge node {} (rsp);
  5562. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5563. \draw (rax) to (rsp);
  5564. \end{tikzpicture}
  5565. \]
  5566. We repeat the process, selecting a maximally saturated vertex,
  5567. choosing \code{z}, and coloring it with the first available number, which
  5568. is $1$. We add $1$ to the saturation for the neighboring vertices
  5569. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5570. \[
  5571. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5572. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5573. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5574. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5575. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5576. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5577. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5578. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5579. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5580. \draw (t1) to (rax);
  5581. \draw (t1) to (z);
  5582. \draw (z) to (y);
  5583. \draw (z) to (w);
  5584. \draw (x) to (w);
  5585. \draw (y) to (w);
  5586. \draw (v) to (w);
  5587. \draw (v) to (rsp);
  5588. \draw (w) to (rsp);
  5589. \draw (x) to (rsp);
  5590. \draw (y) to (rsp);
  5591. \path[-.,bend left=15] (z) edge node {} (rsp);
  5592. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5593. \draw (rax) to (rsp);
  5594. \end{tikzpicture}
  5595. \]
  5596. The most saturated vertices are now \code{w} and \code{y}. We color
  5597. \code{w} with the first available color, which is $0$.
  5598. \[
  5599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5601. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5602. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5603. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5604. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5605. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5606. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5607. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5608. \draw (t1) to (rax);
  5609. \draw (t1) to (z);
  5610. \draw (z) to (y);
  5611. \draw (z) to (w);
  5612. \draw (x) to (w);
  5613. \draw (y) to (w);
  5614. \draw (v) to (w);
  5615. \draw (v) to (rsp);
  5616. \draw (w) to (rsp);
  5617. \draw (x) to (rsp);
  5618. \draw (y) to (rsp);
  5619. \path[-.,bend left=15] (z) edge node {} (rsp);
  5620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5621. \draw (rax) to (rsp);
  5622. \end{tikzpicture}
  5623. \]
  5624. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5625. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5626. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5627. and \code{z}, whose colors are $0$ and $1$ respectively.
  5628. \[
  5629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5630. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5631. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5632. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5633. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5634. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5635. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5636. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5637. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5638. \draw (t1) to (rax);
  5639. \draw (t1) to (z);
  5640. \draw (z) to (y);
  5641. \draw (z) to (w);
  5642. \draw (x) to (w);
  5643. \draw (y) to (w);
  5644. \draw (v) to (w);
  5645. \draw (v) to (rsp);
  5646. \draw (w) to (rsp);
  5647. \draw (x) to (rsp);
  5648. \draw (y) to (rsp);
  5649. \path[-.,bend left=15] (z) edge node {} (rsp);
  5650. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5651. \draw (rax) to (rsp);
  5652. \end{tikzpicture}
  5653. \]
  5654. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5655. \[
  5656. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5657. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5658. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5659. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5660. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5661. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5662. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5663. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5664. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5665. \draw (t1) to (rax);
  5666. \draw (t1) to (z);
  5667. \draw (z) to (y);
  5668. \draw (z) to (w);
  5669. \draw (x) to (w);
  5670. \draw (y) to (w);
  5671. \draw (v) to (w);
  5672. \draw (v) to (rsp);
  5673. \draw (w) to (rsp);
  5674. \draw (x) to (rsp);
  5675. \draw (y) to (rsp);
  5676. \path[-.,bend left=15] (z) edge node {} (rsp);
  5677. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5678. \draw (rax) to (rsp);
  5679. \end{tikzpicture}
  5680. \]
  5681. In the last step of the algorithm, we color \code{x} with $1$.
  5682. \[
  5683. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5684. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5685. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5686. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5687. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5688. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5689. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5690. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5691. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5692. \draw (t1) to (rax);
  5693. \draw (t1) to (z);
  5694. \draw (z) to (y);
  5695. \draw (z) to (w);
  5696. \draw (x) to (w);
  5697. \draw (y) to (w);
  5698. \draw (v) to (w);
  5699. \draw (v) to (rsp);
  5700. \draw (w) to (rsp);
  5701. \draw (x) to (rsp);
  5702. \draw (y) to (rsp);
  5703. \path[-.,bend left=15] (z) edge node {} (rsp);
  5704. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5705. \draw (rax) to (rsp);
  5706. \end{tikzpicture}
  5707. \]
  5708. So, we obtain the following coloring:
  5709. \[
  5710. \{
  5711. \ttm{rax} \mapsto -1,
  5712. \ttm{rsp} \mapsto -2,
  5713. \ttm{t} \mapsto 0,
  5714. \ttm{z} \mapsto 1,
  5715. \ttm{x} \mapsto 1,
  5716. \ttm{y} \mapsto 2,
  5717. \ttm{w} \mapsto 0,
  5718. \ttm{v} \mapsto 1
  5719. \}
  5720. \]
  5721. \fi}
  5722. %
  5723. {\if\edition\pythonEd\pythonColor
  5724. %
  5725. With the DSATUR algorithm in hand, let us return to the running
  5726. example and consider how to color the interference graph in
  5727. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5728. to indicate that it has not yet been assigned a color. Each register
  5729. node (not shown) should be assigned the number that the register
  5730. corresponds to, for example, color \code{rcx} with the number \code{0}
  5731. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5732. each node; all of them start as the empty set. We do not show the
  5733. register nodes in the graph below because there were no interference
  5734. edges involving registers in this program, but in general there can
  5735. be.
  5736. %
  5737. \[
  5738. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5739. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5740. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5741. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5742. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5743. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5744. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5745. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5746. \draw (t0) to (t1);
  5747. \draw (t0) to (z);
  5748. \draw (z) to (y);
  5749. \draw (z) to (w);
  5750. \draw (x) to (w);
  5751. \draw (y) to (w);
  5752. \draw (v) to (w);
  5753. \end{tikzpicture}
  5754. \]
  5755. The algorithm says to select a maximally saturated vertex, but they
  5756. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5757. then color it with the first available integer, which is $0$. We mark
  5758. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5759. they interfere with $\ttm{tmp\_0}$.
  5760. \[
  5761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5762. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5763. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5764. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5765. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5766. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5767. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5768. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5769. \draw (t0) to (t1);
  5770. \draw (t0) to (z);
  5771. \draw (z) to (y);
  5772. \draw (z) to (w);
  5773. \draw (x) to (w);
  5774. \draw (y) to (w);
  5775. \draw (v) to (w);
  5776. \end{tikzpicture}
  5777. \]
  5778. We repeat the process. The most saturated vertices are \code{z} and
  5779. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5780. available number, which is $1$. We add $1$ to the saturation for the
  5781. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5782. \[
  5783. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5784. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5785. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5786. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5787. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5788. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5789. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5790. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5791. \draw (t0) to (t1);
  5792. \draw (t0) to (z);
  5793. \draw (z) to (y);
  5794. \draw (z) to (w);
  5795. \draw (x) to (w);
  5796. \draw (y) to (w);
  5797. \draw (v) to (w);
  5798. \end{tikzpicture}
  5799. \]
  5800. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5801. \code{y}. We color \code{w} with the first available color, which
  5802. is $0$.
  5803. \[
  5804. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5805. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5806. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5807. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5808. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5809. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5810. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5811. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5812. \draw (t0) to (t1);
  5813. \draw (t0) to (z);
  5814. \draw (z) to (y);
  5815. \draw (z) to (w);
  5816. \draw (x) to (w);
  5817. \draw (y) to (w);
  5818. \draw (v) to (w);
  5819. \end{tikzpicture}
  5820. \]
  5821. Now \code{y} is the most saturated, so we color it with $2$.
  5822. \[
  5823. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5824. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5825. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5826. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5827. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5828. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5829. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5830. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5831. \draw (t0) to (t1);
  5832. \draw (t0) to (z);
  5833. \draw (z) to (y);
  5834. \draw (z) to (w);
  5835. \draw (x) to (w);
  5836. \draw (y) to (w);
  5837. \draw (v) to (w);
  5838. \end{tikzpicture}
  5839. \]
  5840. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5841. We choose to color \code{v} with $1$.
  5842. \[
  5843. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5844. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5845. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5846. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5847. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5848. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5849. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5850. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5851. \draw (t0) to (t1);
  5852. \draw (t0) to (z);
  5853. \draw (z) to (y);
  5854. \draw (z) to (w);
  5855. \draw (x) to (w);
  5856. \draw (y) to (w);
  5857. \draw (v) to (w);
  5858. \end{tikzpicture}
  5859. \]
  5860. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5861. \[
  5862. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5863. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5864. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5865. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5866. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5867. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5868. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5869. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5870. \draw (t0) to (t1);
  5871. \draw (t0) to (z);
  5872. \draw (z) to (y);
  5873. \draw (z) to (w);
  5874. \draw (x) to (w);
  5875. \draw (y) to (w);
  5876. \draw (v) to (w);
  5877. \end{tikzpicture}
  5878. \]
  5879. So, we obtain the following coloring:
  5880. \[
  5881. \{ \ttm{tmp\_0} \mapsto 0,
  5882. \ttm{tmp\_1} \mapsto 1,
  5883. \ttm{z} \mapsto 1,
  5884. \ttm{x} \mapsto 1,
  5885. \ttm{y} \mapsto 2,
  5886. \ttm{w} \mapsto 0,
  5887. \ttm{v} \mapsto 1 \}
  5888. \]
  5889. \fi}
  5890. We recommend creating an auxiliary function named \code{color\_graph}
  5891. that takes an interference graph and a list of all the variables in
  5892. the program. This function should return a mapping of variables to
  5893. their colors (represented as natural numbers). By creating this helper
  5894. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5895. when we add support for functions.
  5896. To prioritize the processing of highly saturated nodes inside the
  5897. \code{color\_graph} function, we recommend using the priority queue
  5898. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5899. addition, you will need to maintain a mapping from variables to their
  5900. handles in the priority queue so that you can notify the priority
  5901. queue when their saturation changes.}
  5902. {\if\edition\racketEd
  5903. \begin{figure}[tp]
  5904. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5905. \small
  5906. \begin{tcolorbox}[title=Priority Queue]
  5907. A \emph{priority queue} is a collection of items in which the
  5908. removal of items is governed by priority. In a min queue,
  5909. lower priority items are removed first. An implementation is in
  5910. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5911. queue} \index{subject}{minimum priority queue}
  5912. \begin{description}
  5913. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5914. priority queue that uses the $\itm{cmp}$ predicate to determine
  5915. whether its first argument has lower or equal priority to its
  5916. second argument.
  5917. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5918. items in the queue.
  5919. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5920. the item into the queue and returns a handle for the item in the
  5921. queue.
  5922. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5923. the lowest priority.
  5924. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5925. notifies the queue that the priority has decreased for the item
  5926. associated with the given handle.
  5927. \end{description}
  5928. \end{tcolorbox}
  5929. %\end{wrapfigure}
  5930. \caption{The priority queue data structure.}
  5931. \label{fig:priority-queue}
  5932. \end{figure}
  5933. \fi}
  5934. With the coloring complete, we finalize the assignment of variables to
  5935. registers and stack locations. We map the first $k$ colors to the $k$
  5936. registers and the rest of the colors to stack locations. Suppose for
  5937. the moment that we have just one register to use for register
  5938. allocation, \key{rcx}. Then we have the following map from colors to
  5939. locations.
  5940. \[
  5941. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5942. \]
  5943. Composing this mapping with the coloring, we arrive at the following
  5944. assignment of variables to locations.
  5945. {\if\edition\racketEd
  5946. \begin{gather*}
  5947. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5948. \ttm{w} \mapsto \key{\%rcx}, \,
  5949. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5950. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5951. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5952. \ttm{t} \mapsto \key{\%rcx} \}
  5953. \end{gather*}
  5954. \fi}
  5955. {\if\edition\pythonEd\pythonColor
  5956. \begin{gather*}
  5957. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5958. \ttm{w} \mapsto \key{\%rcx}, \,
  5959. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5960. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5961. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5962. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5963. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5964. \end{gather*}
  5965. \fi}
  5966. Adapt the code from the \code{assign\_homes} pass
  5967. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5968. assigned location. Applying this assignment to our running
  5969. example shown next, on the left, yields the program on the right.
  5970. % why frame size of 32? -JGS
  5971. \begin{center}
  5972. {\if\edition\racketEd
  5973. \begin{minipage}{0.3\textwidth}
  5974. \begin{lstlisting}
  5975. movq $1, v
  5976. movq $42, w
  5977. movq v, x
  5978. addq $7, x
  5979. movq x, y
  5980. movq x, z
  5981. addq w, z
  5982. movq y, t
  5983. negq t
  5984. movq z, %rax
  5985. addq t, %rax
  5986. jmp conclusion
  5987. \end{lstlisting}
  5988. \end{minipage}
  5989. $\Rightarrow\qquad$
  5990. \begin{minipage}{0.45\textwidth}
  5991. \begin{lstlisting}
  5992. movq $1, -8(%rbp)
  5993. movq $42, %rcx
  5994. movq -8(%rbp), -8(%rbp)
  5995. addq $7, -8(%rbp)
  5996. movq -8(%rbp), -16(%rbp)
  5997. movq -8(%rbp), -8(%rbp)
  5998. addq %rcx, -8(%rbp)
  5999. movq -16(%rbp), %rcx
  6000. negq %rcx
  6001. movq -8(%rbp), %rax
  6002. addq %rcx, %rax
  6003. jmp conclusion
  6004. \end{lstlisting}
  6005. \end{minipage}
  6006. \fi}
  6007. {\if\edition\pythonEd\pythonColor
  6008. \begin{minipage}{0.3\textwidth}
  6009. \begin{lstlisting}
  6010. movq $1, v
  6011. movq $42, w
  6012. movq v, x
  6013. addq $7, x
  6014. movq x, y
  6015. movq x, z
  6016. addq w, z
  6017. movq y, tmp_0
  6018. negq tmp_0
  6019. movq z, tmp_1
  6020. addq tmp_0, tmp_1
  6021. movq tmp_1, %rdi
  6022. callq print_int
  6023. \end{lstlisting}
  6024. \end{minipage}
  6025. $\Rightarrow\qquad$
  6026. \begin{minipage}{0.45\textwidth}
  6027. \begin{lstlisting}
  6028. movq $1, -8(%rbp)
  6029. movq $42, %rcx
  6030. movq -8(%rbp), -8(%rbp)
  6031. addq $7, -8(%rbp)
  6032. movq -8(%rbp), -16(%rbp)
  6033. movq -8(%rbp), -8(%rbp)
  6034. addq %rcx, -8(%rbp)
  6035. movq -16(%rbp), %rcx
  6036. negq %rcx
  6037. movq -8(%rbp), -8(%rbp)
  6038. addq %rcx, -8(%rbp)
  6039. movq -8(%rbp), %rdi
  6040. callq print_int
  6041. \end{lstlisting}
  6042. \end{minipage}
  6043. \fi}
  6044. \end{center}
  6045. \begin{exercise}\normalfont\normalsize
  6046. Implement the \code{allocate\_registers} pass.
  6047. Create five programs that exercise all aspects of the register
  6048. allocation algorithm, including spilling variables to the stack.
  6049. %
  6050. {\if\edition\racketEd
  6051. Replace \code{assign\_homes} in the list of \code{passes} in the
  6052. \code{run-tests.rkt} script with the three new passes:
  6053. \code{uncover\_live}, \code{build\_interference}, and
  6054. \code{allocate\_registers}.
  6055. Temporarily remove the call to \code{compiler-tests}.
  6056. Run the script to test the register allocator.
  6057. \fi}
  6058. %
  6059. {\if\edition\pythonEd\pythonColor
  6060. Run the \code{run-tests.py} script to to check whether the
  6061. output programs produce the same result as the input programs.
  6062. \fi}
  6063. \end{exercise}
  6064. \section{Patch Instructions}
  6065. \label{sec:patch-instructions}
  6066. The remaining step in the compilation to x86 is to ensure that the
  6067. instructions have at most one argument that is a memory access.
  6068. %
  6069. In the running example, the instruction \code{movq -8(\%rbp),
  6070. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6071. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6072. then move \code{rax} into \code{-16(\%rbp)}.
  6073. %
  6074. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6075. problematic, but they can simply be deleted. In general, we recommend
  6076. deleting all the trivial moves whose source and destination are the
  6077. same location.
  6078. %
  6079. The following is the output of \code{patch\_instructions} on the
  6080. running example.
  6081. \begin{center}
  6082. {\if\edition\racketEd
  6083. \begin{minipage}{0.4\textwidth}
  6084. \begin{lstlisting}
  6085. movq $1, -8(%rbp)
  6086. movq $42, %rcx
  6087. movq -8(%rbp), -8(%rbp)
  6088. addq $7, -8(%rbp)
  6089. movq -8(%rbp), -16(%rbp)
  6090. movq -8(%rbp), -8(%rbp)
  6091. addq %rcx, -8(%rbp)
  6092. movq -16(%rbp), %rcx
  6093. negq %rcx
  6094. movq -8(%rbp), %rax
  6095. addq %rcx, %rax
  6096. jmp conclusion
  6097. \end{lstlisting}
  6098. \end{minipage}
  6099. $\Rightarrow\qquad$
  6100. \begin{minipage}{0.45\textwidth}
  6101. \begin{lstlisting}
  6102. movq $1, -8(%rbp)
  6103. movq $42, %rcx
  6104. addq $7, -8(%rbp)
  6105. movq -8(%rbp), %rax
  6106. movq %rax, -16(%rbp)
  6107. addq %rcx, -8(%rbp)
  6108. movq -16(%rbp), %rcx
  6109. negq %rcx
  6110. movq -8(%rbp), %rax
  6111. addq %rcx, %rax
  6112. jmp conclusion
  6113. \end{lstlisting}
  6114. \end{minipage}
  6115. \fi}
  6116. {\if\edition\pythonEd\pythonColor
  6117. \begin{minipage}{0.4\textwidth}
  6118. \begin{lstlisting}
  6119. movq $1, -8(%rbp)
  6120. movq $42, %rcx
  6121. movq -8(%rbp), -8(%rbp)
  6122. addq $7, -8(%rbp)
  6123. movq -8(%rbp), -16(%rbp)
  6124. movq -8(%rbp), -8(%rbp)
  6125. addq %rcx, -8(%rbp)
  6126. movq -16(%rbp), %rcx
  6127. negq %rcx
  6128. movq -8(%rbp), -8(%rbp)
  6129. addq %rcx, -8(%rbp)
  6130. movq -8(%rbp), %rdi
  6131. callq print_int
  6132. \end{lstlisting}
  6133. \end{minipage}
  6134. $\Rightarrow\qquad$
  6135. \begin{minipage}{0.45\textwidth}
  6136. \begin{lstlisting}
  6137. movq $1, -8(%rbp)
  6138. movq $42, %rcx
  6139. addq $7, -8(%rbp)
  6140. movq -8(%rbp), %rax
  6141. movq %rax, -16(%rbp)
  6142. addq %rcx, -8(%rbp)
  6143. movq -16(%rbp), %rcx
  6144. negq %rcx
  6145. addq %rcx, -8(%rbp)
  6146. movq -8(%rbp), %rdi
  6147. callq print_int
  6148. \end{lstlisting}
  6149. \end{minipage}
  6150. \fi}
  6151. \end{center}
  6152. \begin{exercise}\normalfont\normalsize
  6153. %
  6154. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6155. %
  6156. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6157. %in the \code{run-tests.rkt} script.
  6158. %
  6159. Run the script to test the \code{patch\_instructions} pass.
  6160. \end{exercise}
  6161. \section{Prelude and Conclusion}
  6162. \label{sec:print-x86-reg-alloc}
  6163. \index{subject}{calling conventions}
  6164. \index{subject}{prelude}\index{subject}{conclusion}
  6165. Recall that this pass generates the prelude and conclusion
  6166. instructions to satisfy the x86 calling conventions
  6167. (section~\ref{sec:calling-conventions}). With the addition of the
  6168. register allocator, the callee-saved registers used by the register
  6169. allocator must be saved in the prelude and restored in the conclusion.
  6170. In the \code{allocate\_registers} pass,
  6171. %
  6172. \racket{add an entry to the \itm{info}
  6173. of \code{X86Program} named \code{used\_callee}}
  6174. %
  6175. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6176. %
  6177. that stores the set of callee-saved registers that were assigned to
  6178. variables. The \code{prelude\_and\_conclusion} pass can then access
  6179. this information to decide which callee-saved registers need to be
  6180. saved and restored.
  6181. %
  6182. When calculating the amount to adjust the \code{rsp} in the prelude,
  6183. make sure to take into account the space used for saving the
  6184. callee-saved registers. Also, remember that the frame needs to be a
  6185. multiple of 16 bytes! We recommend using the following equation for
  6186. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6187. of spilled variables and $C$ be the number of callee-saved registers
  6188. that were allocated to variables. The $\itm{align}$ function rounds a
  6189. number up to the nearest 16 bytes.
  6190. \[
  6191. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6192. \]
  6193. The reason we subtract $8\itm{C}$ in this equation is that the
  6194. prelude uses \code{pushq} to save each of the callee-saved registers,
  6195. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6196. \racket{An overview of all the passes involved in register
  6197. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6198. {\if\edition\racketEd
  6199. \begin{figure}[tbp]
  6200. \begin{tcolorbox}[colback=white]
  6201. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6202. \node (Lvar) at (0,2) {\large \LangVar{}};
  6203. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6204. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6205. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6206. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6207. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6208. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6209. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6210. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6211. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6212. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6213. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6214. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  6215. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6216. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6217. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6218. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6219. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6220. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6221. \end{tikzpicture}
  6222. \end{tcolorbox}
  6223. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6224. \label{fig:reg-alloc-passes}
  6225. \end{figure}
  6226. \fi}
  6227. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6228. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6229. use of registers and the stack, we limit the register allocator for
  6230. this example to use just two registers: \code{rbx} and \code{rcx}. In
  6231. the prelude\index{subject}{prelude} of the \code{main} function, we
  6232. push \code{rbx} onto the stack because it is a callee-saved register
  6233. and it was assigned to a variable by the register allocator. We
  6234. subtract \code{8} from the \code{rsp} at the end of the prelude to
  6235. reserve space for the one spilled variable. After that subtraction,
  6236. the \code{rsp} is aligned to 16 bytes.
  6237. Moving on to the program proper, we see how the registers were
  6238. allocated.
  6239. %
  6240. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  6241. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  6242. %
  6243. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6244. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6245. were assigned to \code{rbx}.}
  6246. %
  6247. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  6248. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6249. callee-save register \code{rbx} onto the stack. The spilled variables
  6250. must be placed lower on the stack than the saved callee-save
  6251. registers, so in this case \racket{\code{w}}\python{z} is placed at
  6252. \code{-16(\%rbp)}.
  6253. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6254. done in the prelude. We move the stack pointer up by \code{8} bytes
  6255. (the room for spilled variables), then pop the old values of
  6256. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6257. \code{retq} to return control to the operating system.
  6258. \begin{figure}[tbp]
  6259. \begin{minipage}{0.55\textwidth}
  6260. \begin{tcolorbox}[colback=white]
  6261. % var_test_28.rkt
  6262. % (use-minimal-set-of-registers! #t)
  6263. % and only rbx rcx
  6264. % tmp 0 rbx
  6265. % z 1 rcx
  6266. % y 0 rbx
  6267. % w 2 16(%rbp)
  6268. % v 0 rbx
  6269. % x 0 rbx
  6270. {\if\edition\racketEd
  6271. \begin{lstlisting}
  6272. start:
  6273. movq $1, %rbx
  6274. movq $42, -16(%rbp)
  6275. addq $7, %rbx
  6276. movq %rbx, %rcx
  6277. addq -16(%rbp), %rcx
  6278. negq %rbx
  6279. movq %rcx, %rax
  6280. addq %rbx, %rax
  6281. jmp conclusion
  6282. .globl main
  6283. main:
  6284. pushq %rbp
  6285. movq %rsp, %rbp
  6286. pushq %rbx
  6287. subq $8, %rsp
  6288. jmp start
  6289. conclusion:
  6290. addq $8, %rsp
  6291. popq %rbx
  6292. popq %rbp
  6293. retq
  6294. \end{lstlisting}
  6295. \fi}
  6296. {\if\edition\pythonEd\pythonColor
  6297. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6298. \begin{lstlisting}
  6299. .globl main
  6300. main:
  6301. pushq %rbp
  6302. movq %rsp, %rbp
  6303. pushq %rbx
  6304. subq $8, %rsp
  6305. movq $1, %rcx
  6306. movq $42, %rbx
  6307. addq $7, %rcx
  6308. movq %rcx, -16(%rbp)
  6309. addq %rbx, -16(%rbp)
  6310. negq %rcx
  6311. movq -16(%rbp), %rbx
  6312. addq %rcx, %rbx
  6313. movq %rbx, %rdi
  6314. callq print_int
  6315. addq $8, %rsp
  6316. popq %rbx
  6317. popq %rbp
  6318. retq
  6319. \end{lstlisting}
  6320. \fi}
  6321. \end{tcolorbox}
  6322. \end{minipage}
  6323. \caption{The x86 output from the running example
  6324. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6325. and \code{rcx}.}
  6326. \label{fig:running-example-x86}
  6327. \end{figure}
  6328. \begin{exercise}\normalfont\normalsize
  6329. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6330. %
  6331. \racket{
  6332. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6333. list of passes and the call to \code{compiler-tests}.}
  6334. %
  6335. Run the script to test the complete compiler for \LangVar{} that
  6336. performs register allocation.
  6337. \end{exercise}
  6338. \section{Challenge: Move Biasing}
  6339. \label{sec:move-biasing}
  6340. \index{subject}{move biasing}
  6341. This section describes an enhancement to the register allocator,
  6342. called move biasing, for students who are looking for an extra
  6343. challenge.
  6344. {\if\edition\racketEd
  6345. To motivate the need for move biasing we return to the running example,
  6346. but this time we use all the general purpose registers. So, we have
  6347. the following mapping of color numbers to registers.
  6348. \[
  6349. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6350. \]
  6351. Using the same assignment of variables to color numbers that was
  6352. produced by the register allocator described in the last section, we
  6353. get the following program.
  6354. \begin{center}
  6355. \begin{minipage}{0.3\textwidth}
  6356. \begin{lstlisting}
  6357. movq $1, v
  6358. movq $42, w
  6359. movq v, x
  6360. addq $7, x
  6361. movq x, y
  6362. movq x, z
  6363. addq w, z
  6364. movq y, t
  6365. negq t
  6366. movq z, %rax
  6367. addq t, %rax
  6368. jmp conclusion
  6369. \end{lstlisting}
  6370. \end{minipage}
  6371. $\Rightarrow\qquad$
  6372. \begin{minipage}{0.45\textwidth}
  6373. \begin{lstlisting}
  6374. movq $1, %rdx
  6375. movq $42, %rcx
  6376. movq %rdx, %rdx
  6377. addq $7, %rdx
  6378. movq %rdx, %rsi
  6379. movq %rdx, %rdx
  6380. addq %rcx, %rdx
  6381. movq %rsi, %rcx
  6382. negq %rcx
  6383. movq %rdx, %rax
  6384. addq %rcx, %rax
  6385. jmp conclusion
  6386. \end{lstlisting}
  6387. \end{minipage}
  6388. \end{center}
  6389. In this output code there are two \key{movq} instructions that
  6390. can be removed because their source and target are the same. However,
  6391. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6392. register, we could instead remove three \key{movq} instructions. We
  6393. can accomplish this by taking into account which variables appear in
  6394. \key{movq} instructions with which other variables.
  6395. \fi}
  6396. {\if\edition\pythonEd\pythonColor
  6397. %
  6398. To motivate the need for move biasing we return to the running example
  6399. and recall that in section~\ref{sec:patch-instructions} we were able to
  6400. remove three trivial move instructions from the running
  6401. example. However, we could remove another trivial move if we were able
  6402. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6403. We say that two variables $p$ and $q$ are \emph{move
  6404. related}\index{subject}{move related} if they participate together in
  6405. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6406. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  6407. if there are multiple variables with the same saturation, prefer
  6408. variables that can be assigned to a color that is the same as the
  6409. color of a move-related variable. Furthermore, when the register
  6410. allocator chooses a color for a variable, it should prefer a color
  6411. that has already been used for a move-related variable (assuming that
  6412. they do not interfere). Of course, this preference should not override
  6413. the preference for registers over stack locations. So, this preference
  6414. should be used as a tie breaker in choosing between registers and
  6415. in choosing between stack locations.
  6416. We recommend representing the move relationships in a graph, similarly
  6417. to how we represented interference. The following is the \emph{move
  6418. graph} for our running example.
  6419. {\if\edition\racketEd
  6420. \[
  6421. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6422. \node (rax) at (0,0) {$\ttm{rax}$};
  6423. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6424. \node (t) at (0,2) {$\ttm{t}$};
  6425. \node (z) at (3,2) {$\ttm{z}$};
  6426. \node (x) at (6,2) {$\ttm{x}$};
  6427. \node (y) at (3,0) {$\ttm{y}$};
  6428. \node (w) at (6,0) {$\ttm{w}$};
  6429. \node (v) at (9,0) {$\ttm{v}$};
  6430. \draw (v) to (x);
  6431. \draw (x) to (y);
  6432. \draw (x) to (z);
  6433. \draw (y) to (t);
  6434. \end{tikzpicture}
  6435. \]
  6436. \fi}
  6437. %
  6438. {\if\edition\pythonEd\pythonColor
  6439. \[
  6440. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6441. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6442. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6443. \node (z) at (3,2) {$\ttm{z}$};
  6444. \node (x) at (6,2) {$\ttm{x}$};
  6445. \node (y) at (3,0) {$\ttm{y}$};
  6446. \node (w) at (6,0) {$\ttm{w}$};
  6447. \node (v) at (9,0) {$\ttm{v}$};
  6448. \draw (y) to (t0);
  6449. \draw (z) to (x);
  6450. \draw (z) to (t1);
  6451. \draw (x) to (y);
  6452. \draw (x) to (v);
  6453. \end{tikzpicture}
  6454. \]
  6455. \fi}
  6456. {\if\edition\racketEd
  6457. Now we replay the graph coloring, pausing to see the coloring of
  6458. \code{y}. Recall the following configuration. The most saturated vertices
  6459. were \code{w} and \code{y}.
  6460. \[
  6461. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6462. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6463. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6464. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6465. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6466. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6467. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6468. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6469. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6470. \draw (t1) to (rax);
  6471. \draw (t1) to (z);
  6472. \draw (z) to (y);
  6473. \draw (z) to (w);
  6474. \draw (x) to (w);
  6475. \draw (y) to (w);
  6476. \draw (v) to (w);
  6477. \draw (v) to (rsp);
  6478. \draw (w) to (rsp);
  6479. \draw (x) to (rsp);
  6480. \draw (y) to (rsp);
  6481. \path[-.,bend left=15] (z) edge node {} (rsp);
  6482. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6483. \draw (rax) to (rsp);
  6484. \end{tikzpicture}
  6485. \]
  6486. %
  6487. The last time, we chose to color \code{w} with $0$. This time, we see
  6488. that \code{w} is not move-related to any vertex, but \code{y} is
  6489. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6490. the same color as \code{t}.
  6491. \[
  6492. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6493. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6494. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6495. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6496. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6497. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6498. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6499. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6500. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6501. \draw (t1) to (rax);
  6502. \draw (t1) to (z);
  6503. \draw (z) to (y);
  6504. \draw (z) to (w);
  6505. \draw (x) to (w);
  6506. \draw (y) to (w);
  6507. \draw (v) to (w);
  6508. \draw (v) to (rsp);
  6509. \draw (w) to (rsp);
  6510. \draw (x) to (rsp);
  6511. \draw (y) to (rsp);
  6512. \path[-.,bend left=15] (z) edge node {} (rsp);
  6513. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6514. \draw (rax) to (rsp);
  6515. \end{tikzpicture}
  6516. \]
  6517. Now \code{w} is the most saturated, so we color it $2$.
  6518. \[
  6519. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6520. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6521. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6522. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6523. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6524. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6525. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6526. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6527. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6528. \draw (t1) to (rax);
  6529. \draw (t1) to (z);
  6530. \draw (z) to (y);
  6531. \draw (z) to (w);
  6532. \draw (x) to (w);
  6533. \draw (y) to (w);
  6534. \draw (v) to (w);
  6535. \draw (v) to (rsp);
  6536. \draw (w) to (rsp);
  6537. \draw (x) to (rsp);
  6538. \draw (y) to (rsp);
  6539. \path[-.,bend left=15] (z) edge node {} (rsp);
  6540. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6541. \draw (rax) to (rsp);
  6542. \end{tikzpicture}
  6543. \]
  6544. At this point, vertices \code{x} and \code{v} are most saturated, but
  6545. \code{x} is move related to \code{y} and \code{z}, so we color
  6546. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6547. \[
  6548. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6549. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6550. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6551. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6552. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6553. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6554. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6555. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6556. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6557. \draw (t1) to (rax);
  6558. \draw (t) to (z);
  6559. \draw (z) to (y);
  6560. \draw (z) to (w);
  6561. \draw (x) to (w);
  6562. \draw (y) to (w);
  6563. \draw (v) to (w);
  6564. \draw (v) to (rsp);
  6565. \draw (w) to (rsp);
  6566. \draw (x) to (rsp);
  6567. \draw (y) to (rsp);
  6568. \path[-.,bend left=15] (z) edge node {} (rsp);
  6569. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6570. \draw (rax) to (rsp);
  6571. \end{tikzpicture}
  6572. \]
  6573. \fi}
  6574. %
  6575. {\if\edition\pythonEd\pythonColor
  6576. Now we replay the graph coloring, pausing before the coloring of
  6577. \code{w}. Recall the following configuration. The most saturated vertices
  6578. were \code{tmp\_1}, \code{w}, and \code{y}.
  6579. \[
  6580. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6581. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6582. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6583. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6584. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6585. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6586. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6587. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6588. \draw (t0) to (t1);
  6589. \draw (t0) to (z);
  6590. \draw (z) to (y);
  6591. \draw (z) to (w);
  6592. \draw (x) to (w);
  6593. \draw (y) to (w);
  6594. \draw (v) to (w);
  6595. \end{tikzpicture}
  6596. \]
  6597. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6598. or \code{y}, but note that \code{w} is not move related to any
  6599. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6600. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6601. \code{y} and color it $0$, we can delete another move instruction.
  6602. \[
  6603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6604. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6605. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6606. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6607. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6608. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6609. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6610. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6611. \draw (t0) to (t1);
  6612. \draw (t0) to (z);
  6613. \draw (z) to (y);
  6614. \draw (z) to (w);
  6615. \draw (x) to (w);
  6616. \draw (y) to (w);
  6617. \draw (v) to (w);
  6618. \end{tikzpicture}
  6619. \]
  6620. Now \code{w} is the most saturated, so we color it $2$.
  6621. \[
  6622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6623. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6624. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6625. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6626. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6627. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6628. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6629. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6630. \draw (t0) to (t1);
  6631. \draw (t0) to (z);
  6632. \draw (z) to (y);
  6633. \draw (z) to (w);
  6634. \draw (x) to (w);
  6635. \draw (y) to (w);
  6636. \draw (v) to (w);
  6637. \end{tikzpicture}
  6638. \]
  6639. To finish the coloring, \code{x} and \code{v} get $0$ and
  6640. \code{tmp\_1} gets $1$.
  6641. \[
  6642. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6643. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6644. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6645. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6646. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6647. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6648. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6649. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6650. \draw (t0) to (t1);
  6651. \draw (t0) to (z);
  6652. \draw (z) to (y);
  6653. \draw (z) to (w);
  6654. \draw (x) to (w);
  6655. \draw (y) to (w);
  6656. \draw (v) to (w);
  6657. \end{tikzpicture}
  6658. \]
  6659. \fi}
  6660. So, we have the following assignment of variables to registers.
  6661. {\if\edition\racketEd
  6662. \begin{gather*}
  6663. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6664. \ttm{w} \mapsto \key{\%rsi}, \,
  6665. \ttm{x} \mapsto \key{\%rcx}, \,
  6666. \ttm{y} \mapsto \key{\%rcx}, \,
  6667. \ttm{z} \mapsto \key{\%rdx}, \,
  6668. \ttm{t} \mapsto \key{\%rcx} \}
  6669. \end{gather*}
  6670. \fi}
  6671. {\if\edition\pythonEd\pythonColor
  6672. \begin{gather*}
  6673. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6674. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6675. \ttm{x} \mapsto \key{\%rcx}, \,
  6676. \ttm{y} \mapsto \key{\%rcx}, \\
  6677. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6678. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6679. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6680. \end{gather*}
  6681. \fi}
  6682. %
  6683. We apply this register assignment to the running example shown next,
  6684. on the left, to obtain the code in the middle. The
  6685. \code{patch\_instructions} then deletes the trivial moves to obtain
  6686. the code on the right.
  6687. {\if\edition\racketEd
  6688. \begin{minipage}{0.25\textwidth}
  6689. \begin{lstlisting}
  6690. movq $1, v
  6691. movq $42, w
  6692. movq v, x
  6693. addq $7, x
  6694. movq x, y
  6695. movq x, z
  6696. addq w, z
  6697. movq y, t
  6698. negq t
  6699. movq z, %rax
  6700. addq t, %rax
  6701. jmp conclusion
  6702. \end{lstlisting}
  6703. \end{minipage}
  6704. $\Rightarrow\qquad$
  6705. \begin{minipage}{0.25\textwidth}
  6706. \begin{lstlisting}
  6707. movq $1, %rcx
  6708. movq $42, %rsi
  6709. movq %rcx, %rcx
  6710. addq $7, %rcx
  6711. movq %rcx, %rcx
  6712. movq %rcx, %rdx
  6713. addq %rsi, %rdx
  6714. movq %rcx, %rcx
  6715. negq %rcx
  6716. movq %rdx, %rax
  6717. addq %rcx, %rax
  6718. jmp conclusion
  6719. \end{lstlisting}
  6720. \end{minipage}
  6721. $\Rightarrow\qquad$
  6722. \begin{minipage}{0.25\textwidth}
  6723. \begin{lstlisting}
  6724. movq $1, %rcx
  6725. movq $42, %rsi
  6726. addq $7, %rcx
  6727. movq %rcx, %rdx
  6728. addq %rsi, %rdx
  6729. negq %rcx
  6730. movq %rdx, %rax
  6731. addq %rcx, %rax
  6732. jmp conclusion
  6733. \end{lstlisting}
  6734. \end{minipage}
  6735. \fi}
  6736. {\if\edition\pythonEd\pythonColor
  6737. \begin{minipage}{0.20\textwidth}
  6738. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6739. movq $1, v
  6740. movq $42, w
  6741. movq v, x
  6742. addq $7, x
  6743. movq x, y
  6744. movq x, z
  6745. addq w, z
  6746. movq y, tmp_0
  6747. negq tmp_0
  6748. movq z, tmp_1
  6749. addq tmp_0, tmp_1
  6750. movq tmp_1, %rdi
  6751. callq _print_int
  6752. \end{lstlisting}
  6753. \end{minipage}
  6754. ${\Rightarrow\qquad}$
  6755. \begin{minipage}{0.30\textwidth}
  6756. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6757. movq $1, %rcx
  6758. movq $42, -16(%rbp)
  6759. movq %rcx, %rcx
  6760. addq $7, %rcx
  6761. movq %rcx, %rcx
  6762. movq %rcx, -8(%rbp)
  6763. addq -16(%rbp), -8(%rbp)
  6764. movq %rcx, %rcx
  6765. negq %rcx
  6766. movq -8(%rbp), -8(%rbp)
  6767. addq %rcx, -8(%rbp)
  6768. movq -8(%rbp), %rdi
  6769. callq _print_int
  6770. \end{lstlisting}
  6771. \end{minipage}
  6772. ${\Rightarrow\qquad}$
  6773. \begin{minipage}{0.20\textwidth}
  6774. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6775. movq $1, %rcx
  6776. movq $42, -16(%rbp)
  6777. addq $7, %rcx
  6778. movq %rcx, -8(%rbp)
  6779. movq -16(%rbp), %rax
  6780. addq %rax, -8(%rbp)
  6781. negq %rcx
  6782. addq %rcx, -8(%rbp)
  6783. movq -8(%rbp), %rdi
  6784. callq print_int
  6785. \end{lstlisting}
  6786. \end{minipage}
  6787. \fi}
  6788. \begin{exercise}\normalfont\normalsize
  6789. Change your implementation of \code{allocate\_registers} to take move
  6790. biasing into account. Create two new tests that include at least one
  6791. opportunity for move biasing, and visually inspect the output x86
  6792. programs to make sure that your move biasing is working properly. Make
  6793. sure that your compiler still passes all the tests.
  6794. \end{exercise}
  6795. %To do: another neat challenge would be to do
  6796. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6797. %% \subsection{Output of the Running Example}
  6798. %% \label{sec:reg-alloc-output}
  6799. % challenge: prioritize variables based on execution frequencies
  6800. % and the number of uses of a variable
  6801. % challenge: enhance the coloring algorithm using Chaitin's
  6802. % approach of prioritizing high-degree variables
  6803. % by removing low-degree variables (coloring them later)
  6804. % from the interference graph
  6805. \section{Further Reading}
  6806. \label{sec:register-allocation-further-reading}
  6807. Early register allocation algorithms were developed for Fortran
  6808. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6809. of graph coloring began in the late 1970s and early 1980s with the
  6810. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6811. algorithm is based on the following observation of
  6812. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6813. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6814. $v$ removed is also $k$ colorable. To see why, suppose that the
  6815. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6816. different colors, but because there are fewer than $k$ neighbors, there
  6817. will be one or more colors left over to use for coloring $v$ in $G$.
  6818. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6819. less than $k$ from the graph and recursively colors the rest of the
  6820. graph. Upon returning from the recursion, it colors $v$ with one of
  6821. the available colors and returns. \citet{Chaitin:1982vn} augments
  6822. this algorithm to handle spilling as follows. If there are no vertices
  6823. of degree lower than $k$ then pick a vertex at random, spill it,
  6824. remove it from the graph, and proceed recursively to color the rest of
  6825. the graph.
  6826. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6827. move-related and that don't interfere with each other, in a process
  6828. called \emph{coalescing}. Although coalescing decreases the number of
  6829. moves, it can make the graph more difficult to
  6830. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6831. which two variables are merged only if they have fewer than $k$
  6832. neighbors of high degree. \citet{George:1996aa} observed that
  6833. conservative coalescing is sometimes too conservative and made it more
  6834. aggressive by iterating the coalescing with the removal of low-degree
  6835. vertices.
  6836. %
  6837. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6838. also proposed \emph{biased coloring}, in which a variable is assigned to
  6839. the same color as another move-related variable if possible, as
  6840. discussed in section~\ref{sec:move-biasing}.
  6841. %
  6842. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6843. performs coalescing, graph coloring, and spill code insertion until
  6844. all variables have been assigned a location.
  6845. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6846. spilled variables that don't have to be: a high-degree variable can be
  6847. colorable if many of its neighbors are assigned the same color.
  6848. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6849. high-degree vertex is not immediately spilled. Instead the decision is
  6850. deferred until after the recursive call, at which point it is apparent
  6851. whether there is actually an available color or not. We observe that
  6852. this algorithm is equivalent to the smallest-last ordering
  6853. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6854. be registers and the rest to be stack locations.
  6855. %% biased coloring
  6856. Earlier editions of the compiler course at Indiana University
  6857. \citep{Dybvig:2010aa} were based on the algorithm of
  6858. \citet{Briggs:1994kx}.
  6859. The smallest-last ordering algorithm is one of many \emph{greedy}
  6860. coloring algorithms. A greedy coloring algorithm visits all the
  6861. vertices in a particular order and assigns each one the first
  6862. available color. An \emph{offline} greedy algorithm chooses the
  6863. ordering up front, prior to assigning colors. The algorithm of
  6864. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6865. ordering does not depend on the colors assigned. Other orderings are
  6866. possible. For example, \citet{Chow:1984ys} ordered variables according
  6867. to an estimate of runtime cost.
  6868. An \emph{online} greedy coloring algorithm uses information about the
  6869. current assignment of colors to influence the order in which the
  6870. remaining vertices are colored. The saturation-based algorithm
  6871. described in this chapter is one such algorithm. We choose to use
  6872. saturation-based coloring because it is fun to introduce graph
  6873. coloring via sudoku!
  6874. A register allocator may choose to map each variable to just one
  6875. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6876. variable to one or more locations. The latter can be achieved by
  6877. \emph{live range splitting}, where a variable is replaced by several
  6878. variables that each handle part of its live
  6879. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6880. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6881. %% replacement algorithm, bottom-up local
  6882. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6883. %% Cooper: top-down (priority bassed), bottom-up
  6884. %% top-down
  6885. %% order variables by priority (estimated cost)
  6886. %% caveat: split variables into two groups:
  6887. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6888. %% color the constrained ones first
  6889. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6890. %% cite J. Cocke for an algorithm that colors variables
  6891. %% in a high-degree first ordering
  6892. %Register Allocation via Usage Counts, Freiburghouse CACM
  6893. \citet{Palsberg:2007si} observed that many of the interference graphs
  6894. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6895. that is, every cycle with four or more edges has an edge that is not
  6896. part of the cycle but that connects two vertices on the cycle. Such
  6897. graphs can be optimally colored by the greedy algorithm with a vertex
  6898. ordering determined by maximum cardinality search.
  6899. In situations in which compile time is of utmost importance, such as
  6900. in just-in-time compilers, graph coloring algorithms can be too
  6901. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6902. be more appropriate.
  6903. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6904. \chapter{Booleans and Conditionals}
  6905. \label{ch:Lif}
  6906. \index{subject}{Boolean}
  6907. \index{subject}{control flow}
  6908. \index{subject}{conditional expression}
  6909. \setcounter{footnote}{0}
  6910. The \LangVar{} language has only a single kind of value, the
  6911. integers. In this chapter we add a second kind of value, the Booleans,
  6912. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6913. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6914. and \FALSE{}, respectively. The \LangIf{} language includes several
  6915. operations that involve Booleans (\key{and}, \key{not},
  6916. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6917. expression \python{and statement}. With the addition of \key{if},
  6918. programs can have nontrivial control flow which
  6919. %
  6920. \racket{impacts \code{explicate\_control} and liveness analysis}
  6921. %
  6922. \python{impacts liveness analysis and motivates a new pass named
  6923. \code{explicate\_control}}.
  6924. %
  6925. Also, because we now have two kinds of values, we need to handle
  6926. programs that apply an operation to the wrong kind of value, such as
  6927. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6928. There are two language design options for such situations. One option
  6929. is to signal an error and the other is to provide a wider
  6930. interpretation of the operation. \racket{The Racket
  6931. language}\python{Python} uses a mixture of these two options,
  6932. depending on the operation and the kind of value. For example, the
  6933. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6934. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6935. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6936. %
  6937. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6938. in Racket because \code{car} expects a pair.}
  6939. %
  6940. \python{On the other hand, \code{1[0]} results in a runtime error
  6941. in Python because an ``\code{int} object is not subscriptable''.}
  6942. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6943. design choices as \racket{Racket}\python{Python}, except that much of the
  6944. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6945. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6946. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6947. \python{MyPy} reports a compile-time error
  6948. %
  6949. \racket{because Racket expects the type of the argument to be of the form
  6950. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6951. %
  6952. \python{stating that a ``value of type \code{int} is not indexable''.}
  6953. The \LangIf{} language performs type checking during compilation just as
  6954. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6955. the alternative choice, that is, a dynamically typed language like
  6956. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6957. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6958. restrictive, for example, rejecting \racket{\code{(not
  6959. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6960. fairly simple because the focus of this book is on compilation and not
  6961. type systems, about which there are already several excellent
  6962. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6963. This chapter is organized as follows. We begin by defining the syntax
  6964. and interpreter for the \LangIf{} language
  6965. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6966. checking and define a type checker for \LangIf{}
  6967. (section~\ref{sec:type-check-Lif}).
  6968. %
  6969. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6970. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6971. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6972. %
  6973. The remaining sections of this chapter discuss how Booleans and
  6974. conditional control flow require changes to the existing compiler
  6975. passes and the addition of new ones. We introduce the \code{shrink}
  6976. pass to translate some operators into others, thereby reducing the
  6977. number of operators that need to be handled in later passes.
  6978. %
  6979. The main event of this chapter is the \code{explicate\_control} pass
  6980. that is responsible for translating \code{if}s into conditional
  6981. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6982. %
  6983. Regarding register allocation, there is the interesting question of
  6984. how to handle conditional \code{goto}s during liveness analysis.
  6985. \section{The \LangIf{} Language}
  6986. \label{sec:lang-if}
  6987. Definitions of the concrete syntax and abstract syntax of the
  6988. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6989. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6990. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6991. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6992. %
  6993. \python{, and the \code{if} statement}. We expand the set of
  6994. operators to include
  6995. \begin{enumerate}
  6996. \item the logical operators \key{and}, \key{or}, and \key{not},
  6997. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6998. for comparing integers or Booleans for equality, and
  6999. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  7000. comparing integers.
  7001. \end{enumerate}
  7002. \racket{We reorganize the abstract syntax for the primitive
  7003. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7004. rule for all of them. This means that the grammar no longer checks
  7005. whether the arity of an operators matches the number of
  7006. arguments. That responsibility is moved to the type checker for
  7007. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7008. \newcommand{\LifGrammarRacket}{
  7009. \begin{array}{lcl}
  7010. \Type &::=& \key{Boolean} \\
  7011. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7012. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7013. \Exp &::=& \itm{bool}
  7014. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7015. \MID (\key{not}\;\Exp) \\
  7016. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7017. \end{array}
  7018. }
  7019. \newcommand{\LifASTRacket}{
  7020. \begin{array}{lcl}
  7021. \Type &::=& \key{Boolean} \\
  7022. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7023. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7024. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7025. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7026. \end{array}
  7027. }
  7028. \newcommand{\LintOpAST}{
  7029. \begin{array}{rcl}
  7030. \Type &::=& \key{Integer} \\
  7031. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7032. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7033. \end{array}
  7034. }
  7035. \newcommand{\LifGrammarPython}{
  7036. \begin{array}{rcl}
  7037. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7038. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7039. \MID \key{not}~\Exp \\
  7040. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7041. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7042. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7043. \end{array}
  7044. }
  7045. \newcommand{\LifASTPython}{
  7046. \begin{array}{lcl}
  7047. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7048. \itm{unaryop} &::=& \code{Not()} \\
  7049. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7050. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7051. \Exp &::=& \BOOL{\itm{bool}}
  7052. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7053. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7054. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7055. \end{array}
  7056. }
  7057. \begin{figure}[tp]
  7058. \centering
  7059. \begin{tcolorbox}[colback=white]
  7060. {\if\edition\racketEd
  7061. \[
  7062. \begin{array}{l}
  7063. \gray{\LintGrammarRacket{}} \\ \hline
  7064. \gray{\LvarGrammarRacket{}} \\ \hline
  7065. \LifGrammarRacket{} \\
  7066. \begin{array}{lcl}
  7067. \LangIfM{} &::=& \Exp
  7068. \end{array}
  7069. \end{array}
  7070. \]
  7071. \fi}
  7072. {\if\edition\pythonEd\pythonColor
  7073. \[
  7074. \begin{array}{l}
  7075. \gray{\LintGrammarPython} \\ \hline
  7076. \gray{\LvarGrammarPython} \\ \hline
  7077. \LifGrammarPython \\
  7078. \begin{array}{rcl}
  7079. \LangIfM{} &::=& \Stmt^{*}
  7080. \end{array}
  7081. \end{array}
  7082. \]
  7083. \fi}
  7084. \end{tcolorbox}
  7085. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7086. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7087. \label{fig:Lif-concrete-syntax}
  7088. \end{figure}
  7089. \begin{figure}[tp]
  7090. %\begin{minipage}{0.66\textwidth}
  7091. \begin{tcolorbox}[colback=white]
  7092. \centering
  7093. {\if\edition\racketEd
  7094. \[
  7095. \begin{array}{l}
  7096. \gray{\LintOpAST} \\ \hline
  7097. \gray{\LvarASTRacket{}} \\ \hline
  7098. \LifASTRacket{} \\
  7099. \begin{array}{lcl}
  7100. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7101. \end{array}
  7102. \end{array}
  7103. \]
  7104. \fi}
  7105. {\if\edition\pythonEd\pythonColor
  7106. \[
  7107. \begin{array}{l}
  7108. \gray{\LintASTPython} \\ \hline
  7109. \gray{\LvarASTPython} \\ \hline
  7110. \LifASTPython \\
  7111. \begin{array}{lcl}
  7112. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7113. \end{array}
  7114. \end{array}
  7115. \]
  7116. \fi}
  7117. \end{tcolorbox}
  7118. %\end{minipage}
  7119. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  7120. \index{subject}{IfExp@\IFNAME{}}
  7121. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  7122. \index{subject}{and@\ANDNAME{}}
  7123. \index{subject}{or@\ORNAME{}}
  7124. \index{subject}{not@\NOTNAME{}}
  7125. \index{subject}{equal@\EQNAME{}}
  7126. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7127. \racket{
  7128. \index{subject}{lessthan@\texttt{<}}
  7129. \index{subject}{lessthaneq@\texttt{<=}}
  7130. \index{subject}{greaterthan@\texttt{>}}
  7131. \index{subject}{greaterthaneq@\texttt{>=}}
  7132. }
  7133. \python{
  7134. \index{subject}{BoolOp@\texttt{BoolOp}}
  7135. \index{subject}{Compare@\texttt{Compare}}
  7136. \index{subject}{Lt@\texttt{Lt}}
  7137. \index{subject}{LtE@\texttt{LtE}}
  7138. \index{subject}{Gt@\texttt{Gt}}
  7139. \index{subject}{GtE@\texttt{GtE}}
  7140. }
  7141. \caption{The abstract syntax of \LangIf{}.}
  7142. \label{fig:Lif-syntax}
  7143. \end{figure}
  7144. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7145. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7146. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7147. evaluate to the corresponding Boolean values. The conditional
  7148. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7149. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7150. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7151. \code{or}, and \code{not} behave according to propositional logic. In
  7152. addition, the \code{and} and \code{or} operations perform
  7153. \emph{short-circuit evaluation}.
  7154. %
  7155. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7156. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7157. %
  7158. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7159. evaluated if $e_1$ evaluates to \TRUE{}.
  7160. \racket{With the increase in the number of primitive operations, the
  7161. interpreter would become repetitive without some care. We refactor
  7162. the case for \code{Prim}, moving the code that differs with each
  7163. operation into the \code{interp\_op} method shown in
  7164. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7165. \code{or} operations separately because of their short-circuiting
  7166. behavior.}
  7167. \begin{figure}[tbp]
  7168. \begin{tcolorbox}[colback=white]
  7169. {\if\edition\racketEd
  7170. \begin{lstlisting}
  7171. (define interp-Lif-class
  7172. (class interp-Lvar-class
  7173. (super-new)
  7174. (define/public (interp_op op) ...)
  7175. (define/override ((interp_exp env) e)
  7176. (define recur (interp_exp env))
  7177. (match e
  7178. [(Bool b) b]
  7179. [(If cnd thn els)
  7180. (match (recur cnd)
  7181. [#t (recur thn)]
  7182. [#f (recur els)])]
  7183. [(Prim 'and (list e1 e2))
  7184. (match (recur e1)
  7185. [#t (match (recur e2) [#t #t] [#f #f])]
  7186. [#f #f])]
  7187. [(Prim 'or (list e1 e2))
  7188. (define v1 (recur e1))
  7189. (match v1
  7190. [#t #t]
  7191. [#f (match (recur e2) [#t #t] [#f #f])])]
  7192. [(Prim op args)
  7193. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7194. [else ((super interp_exp env) e)]))
  7195. ))
  7196. (define (interp_Lif p)
  7197. (send (new interp-Lif-class) interp_program p))
  7198. \end{lstlisting}
  7199. \fi}
  7200. {\if\edition\pythonEd\pythonColor
  7201. \begin{lstlisting}
  7202. class InterpLif(InterpLvar):
  7203. def interp_exp(self, e, env):
  7204. match e:
  7205. case IfExp(test, body, orelse):
  7206. if self.interp_exp(test, env):
  7207. return self.interp_exp(body, env)
  7208. else:
  7209. return self.interp_exp(orelse, env)
  7210. case UnaryOp(Not(), v):
  7211. return not self.interp_exp(v, env)
  7212. case BoolOp(And(), values):
  7213. if self.interp_exp(values[0], env):
  7214. return self.interp_exp(values[1], env)
  7215. else:
  7216. return False
  7217. case BoolOp(Or(), values):
  7218. if self.interp_exp(values[0], env):
  7219. return True
  7220. else:
  7221. return self.interp_exp(values[1], env)
  7222. case Compare(left, [cmp], [right]):
  7223. l = self.interp_exp(left, env)
  7224. r = self.interp_exp(right, env)
  7225. return self.interp_cmp(cmp)(l, r)
  7226. case _:
  7227. return super().interp_exp(e, env)
  7228. def interp_stmts(self, ss, env):
  7229. if len(ss) == 0:
  7230. return
  7231. match ss[0]:
  7232. case If(test, body, orelse):
  7233. if self.interp_exp(test, env):
  7234. return self.interp_stmts(body + ss[1:], env)
  7235. else:
  7236. return self.interp_stmts(orelse + ss[1:], env)
  7237. case _:
  7238. return super().interp_stmts(ss, env)
  7239. ...
  7240. \end{lstlisting}
  7241. \fi}
  7242. \end{tcolorbox}
  7243. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7244. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7245. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7246. \label{fig:interp-Lif}
  7247. \end{figure}
  7248. {\if\edition\racketEd
  7249. \begin{figure}[tbp]
  7250. \begin{tcolorbox}[colback=white]
  7251. \begin{lstlisting}
  7252. (define/public (interp_op op)
  7253. (match op
  7254. ['+ fx+]
  7255. ['- fx-]
  7256. ['read read-fixnum]
  7257. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7258. ['eq? (lambda (v1 v2)
  7259. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7260. (and (boolean? v1) (boolean? v2))
  7261. (and (vector? v1) (vector? v2)))
  7262. (eq? v1 v2)]))]
  7263. ['< (lambda (v1 v2)
  7264. (cond [(and (fixnum? v1) (fixnum? v2))
  7265. (< v1 v2)]))]
  7266. ['<= (lambda (v1 v2)
  7267. (cond [(and (fixnum? v1) (fixnum? v2))
  7268. (<= v1 v2)]))]
  7269. ['> (lambda (v1 v2)
  7270. (cond [(and (fixnum? v1) (fixnum? v2))
  7271. (> v1 v2)]))]
  7272. ['>= (lambda (v1 v2)
  7273. (cond [(and (fixnum? v1) (fixnum? v2))
  7274. (>= v1 v2)]))]
  7275. [else (error 'interp_op "unknown operator")]))
  7276. \end{lstlisting}
  7277. \end{tcolorbox}
  7278. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7279. \label{fig:interp-op-Lif}
  7280. \end{figure}
  7281. \fi}
  7282. {\if\edition\pythonEd\pythonColor
  7283. \begin{figure}
  7284. \begin{tcolorbox}[colback=white]
  7285. \begin{lstlisting}
  7286. class InterpLif(InterpLvar):
  7287. ...
  7288. def interp_cmp(self, cmp):
  7289. match cmp:
  7290. case Lt():
  7291. return lambda x, y: x < y
  7292. case LtE():
  7293. return lambda x, y: x <= y
  7294. case Gt():
  7295. return lambda x, y: x > y
  7296. case GtE():
  7297. return lambda x, y: x >= y
  7298. case Eq():
  7299. return lambda x, y: x == y
  7300. case NotEq():
  7301. return lambda x, y: x != y
  7302. \end{lstlisting}
  7303. \end{tcolorbox}
  7304. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7305. \label{fig:interp-cmp-Lif}
  7306. \end{figure}
  7307. \fi}
  7308. \section{Type Checking \LangIf{} Programs}
  7309. \label{sec:type-check-Lif}
  7310. \index{subject}{type checking}
  7311. \index{subject}{semantic analysis}
  7312. It is helpful to think about type checking in two complementary
  7313. ways. A type checker predicts the type of value that will be produced
  7314. by each expression in the program. For \LangIf{}, we have just two types,
  7315. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  7316. {\if\edition\racketEd
  7317. \begin{lstlisting}
  7318. (+ 10 (- (+ 12 20)))
  7319. \end{lstlisting}
  7320. \fi}
  7321. {\if\edition\pythonEd\pythonColor
  7322. \begin{lstlisting}
  7323. 10 + -(12 + 20)
  7324. \end{lstlisting}
  7325. \fi}
  7326. \noindent produces a value of type \INTTY{}, whereas
  7327. {\if\edition\racketEd
  7328. \begin{lstlisting}
  7329. (and (not #f) #t)
  7330. \end{lstlisting}
  7331. \fi}
  7332. {\if\edition\pythonEd\pythonColor
  7333. \begin{lstlisting}
  7334. (not False) and True
  7335. \end{lstlisting}
  7336. \fi}
  7337. \noindent produces a value of type \BOOLTY{}.
  7338. A second way to think about type checking is that it enforces a set of
  7339. rules about which operators can be applied to which kinds of
  7340. values. For example, our type checker for \LangIf{} signals an error
  7341. for the following expression:
  7342. %
  7343. {\if\edition\racketEd
  7344. \begin{lstlisting}
  7345. (not (+ 10 (- (+ 12 20))))
  7346. \end{lstlisting}
  7347. \fi}
  7348. {\if\edition\pythonEd\pythonColor
  7349. \begin{lstlisting}
  7350. not (10 + -(12 + 20))
  7351. \end{lstlisting}
  7352. \fi}
  7353. \noindent The subexpression
  7354. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7355. \python{\code{(10 + -(12 + 20))}}
  7356. has type \INTTY{}, but the type checker enforces the rule that the
  7357. argument of \code{not} must be an expression of type \BOOLTY{}.
  7358. We implement type checking using classes and methods because they
  7359. provide the open recursion needed to reuse code as we extend the type
  7360. checker in subsequent chapters, analogous to the use of classes and methods
  7361. for the interpreters (section~\ref{sec:extensible-interp}).
  7362. We separate the type checker for the \LangVar{} subset into its own
  7363. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7364. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7365. from the type checker for \LangVar{}. These type checkers are in the
  7366. files
  7367. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7368. and
  7369. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7370. of the support code.
  7371. %
  7372. Each type checker is a structurally recursive function over the AST.
  7373. Given an input expression \code{e}, the type checker either signals an
  7374. error or returns \racket{an expression and} its type.
  7375. %
  7376. \racket{It returns an expression because there are situations in which
  7377. we want to change or update the expression.}
  7378. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7379. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7380. constant is \INTTY{}. To handle variables, the type checker uses the
  7381. environment \code{env} to map variables to types.
  7382. %
  7383. \racket{Consider the case for \key{let}. We type check the
  7384. initializing expression to obtain its type \key{T} and then
  7385. associate type \code{T} with the variable \code{x} in the
  7386. environment used to type check the body of the \key{let}. Thus,
  7387. when the type checker encounters a use of variable \code{x}, it can
  7388. find its type in the environment.}
  7389. %
  7390. \python{Consider the case for assignment. We type check the
  7391. initializing expression to obtain its type \key{t}. If the variable
  7392. \code{lhs.id} is already in the environment because there was a
  7393. prior assignment, we check that this initializer has the same type
  7394. as the prior one. If this is the first assignment to the variable,
  7395. we associate type \code{t} with the variable \code{lhs.id} in the
  7396. environment. Thus, when the type checker encounters a use of
  7397. variable \code{x}, it can find its type in the environment.}
  7398. %
  7399. \racket{Regarding primitive operators, we recursively analyze the
  7400. arguments and then invoke \code{type\_check\_op} to check whether
  7401. the argument types are allowed.}
  7402. %
  7403. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7404. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7405. \racket{Several auxiliary methods are used in the type checker. The
  7406. method \code{operator-types} defines a dictionary that maps the
  7407. operator names to their parameter and return types. The
  7408. \code{type-equal?} method determines whether two types are equal,
  7409. which for now simply dispatches to \code{equal?} (deep
  7410. equality). The \code{check-type-equal?} method triggers an error if
  7411. the two types are not equal. The \code{type-check-op} method looks
  7412. up the operator in the \code{operator-types} dictionary and then
  7413. checks whether the argument types are equal to the parameter types.
  7414. The result is the return type of the operator.}
  7415. %
  7416. \python{The auxiliary method \code{check\_type\_equal} triggers
  7417. an error if the two types are not equal.}
  7418. \begin{figure}[tbp]
  7419. \begin{tcolorbox}[colback=white]
  7420. {\if\edition\racketEd
  7421. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7422. (define type-check-Lvar-class
  7423. (class object%
  7424. (super-new)
  7425. (define/public (operator-types)
  7426. '((+ . ((Integer Integer) . Integer))
  7427. (- . ((Integer Integer) . Integer))
  7428. (read . (() . Integer))))
  7429. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7430. (define/public (check-type-equal? t1 t2 e)
  7431. (unless (type-equal? t1 t2)
  7432. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7433. (define/public (type-check-op op arg-types e)
  7434. (match (dict-ref (operator-types) op)
  7435. [`(,param-types . ,return-type)
  7436. (for ([at arg-types] [pt param-types])
  7437. (check-type-equal? at pt e))
  7438. return-type]
  7439. [else (error 'type-check-op "unrecognized ~a" op)]))
  7440. (define/public (type-check-exp env)
  7441. (lambda (e)
  7442. (match e
  7443. [(Int n) (values (Int n) 'Integer)]
  7444. [(Var x) (values (Var x) (dict-ref env x))]
  7445. [(Let x e body)
  7446. (define-values (e^ Te) ((type-check-exp env) e))
  7447. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7448. (values (Let x e^ b) Tb)]
  7449. [(Prim op es)
  7450. (define-values (new-es ts)
  7451. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7452. (values (Prim op new-es) (type-check-op op ts e))]
  7453. [else (error 'type-check-exp "couldn't match" e)])))
  7454. (define/public (type-check-program e)
  7455. (match e
  7456. [(Program info body)
  7457. (define-values (body^ Tb) ((type-check-exp '()) body))
  7458. (check-type-equal? Tb 'Integer body)
  7459. (Program info body^)]
  7460. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7461. ))
  7462. (define (type-check-Lvar p)
  7463. (send (new type-check-Lvar-class) type-check-program p))
  7464. \end{lstlisting}
  7465. \fi}
  7466. {\if\edition\pythonEd\pythonColor
  7467. \begin{lstlisting}[escapechar=`]
  7468. class TypeCheckLvar:
  7469. def check_type_equal(self, t1, t2, e):
  7470. if t1 != t2:
  7471. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7472. raise Exception(msg)
  7473. def type_check_exp(self, e, env):
  7474. match e:
  7475. case BinOp(left, (Add() | Sub()), right):
  7476. l = self.type_check_exp(left, env)
  7477. check_type_equal(l, int, left)
  7478. r = self.type_check_exp(right, env)
  7479. check_type_equal(r, int, right)
  7480. return int
  7481. case UnaryOp(USub(), v):
  7482. t = self.type_check_exp(v, env)
  7483. check_type_equal(t, int, v)
  7484. return int
  7485. case Name(id):
  7486. return env[id]
  7487. case Constant(value) if isinstance(value, int):
  7488. return int
  7489. case Call(Name('input_int'), []):
  7490. return int
  7491. def type_check_stmts(self, ss, env):
  7492. if len(ss) == 0:
  7493. return
  7494. match ss[0]:
  7495. case Assign([lhs], value):
  7496. t = self.type_check_exp(value, env)
  7497. if lhs.id in env:
  7498. check_type_equal(env[lhs.id], t, value)
  7499. else:
  7500. env[lhs.id] = t
  7501. return self.type_check_stmts(ss[1:], env)
  7502. case Expr(Call(Name('print'), [arg])):
  7503. t = self.type_check_exp(arg, env)
  7504. check_type_equal(t, int, arg)
  7505. return self.type_check_stmts(ss[1:], env)
  7506. case Expr(value):
  7507. self.type_check_exp(value, env)
  7508. return self.type_check_stmts(ss[1:], env)
  7509. def type_check_P(self, p):
  7510. match p:
  7511. case Module(body):
  7512. self.type_check_stmts(body, {})
  7513. \end{lstlisting}
  7514. \fi}
  7515. \end{tcolorbox}
  7516. \caption{Type checker for the \LangVar{} language.}
  7517. \label{fig:type-check-Lvar}
  7518. \end{figure}
  7519. \begin{figure}[tbp]
  7520. \begin{tcolorbox}[colback=white]
  7521. {\if\edition\racketEd
  7522. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7523. (define type-check-Lif-class
  7524. (class type-check-Lvar-class
  7525. (super-new)
  7526. (inherit check-type-equal?)
  7527. (define/override (operator-types)
  7528. (append '((and . ((Boolean Boolean) . Boolean))
  7529. (or . ((Boolean Boolean) . Boolean))
  7530. (< . ((Integer Integer) . Boolean))
  7531. (<= . ((Integer Integer) . Boolean))
  7532. (> . ((Integer Integer) . Boolean))
  7533. (>= . ((Integer Integer) . Boolean))
  7534. (not . ((Boolean) . Boolean)))
  7535. (super operator-types)))
  7536. (define/override (type-check-exp env)
  7537. (lambda (e)
  7538. (match e
  7539. [(Bool b) (values (Bool b) 'Boolean)]
  7540. [(Prim 'eq? (list e1 e2))
  7541. (define-values (e1^ T1) ((type-check-exp env) e1))
  7542. (define-values (e2^ T2) ((type-check-exp env) e2))
  7543. (check-type-equal? T1 T2 e)
  7544. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7545. [(If cnd thn els)
  7546. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7547. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7548. (define-values (els^ Te) ((type-check-exp env) els))
  7549. (check-type-equal? Tc 'Boolean e)
  7550. (check-type-equal? Tt Te e)
  7551. (values (If cnd^ thn^ els^) Te)]
  7552. [else ((super type-check-exp env) e)])))
  7553. ))
  7554. (define (type-check-Lif p)
  7555. (send (new type-check-Lif-class) type-check-program p))
  7556. \end{lstlisting}
  7557. \fi}
  7558. {\if\edition\pythonEd\pythonColor
  7559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7560. class TypeCheckLif(TypeCheckLvar):
  7561. def type_check_exp(self, e, env):
  7562. match e:
  7563. case Constant(value) if isinstance(value, bool):
  7564. return bool
  7565. case BinOp(left, Sub(), right):
  7566. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7567. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7568. return int
  7569. case UnaryOp(Not(), v):
  7570. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7571. return bool
  7572. case BoolOp(op, values):
  7573. left = values[0] ; right = values[1]
  7574. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7575. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7576. return bool
  7577. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7578. or isinstance(cmp, NotEq):
  7579. l = self.type_check_exp(left, env)
  7580. r = self.type_check_exp(right, env)
  7581. check_type_equal(l, r, e)
  7582. return bool
  7583. case Compare(left, [cmp], [right]):
  7584. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7585. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7586. return bool
  7587. case IfExp(test, body, orelse):
  7588. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7589. b = self.type_check_exp(body, env)
  7590. o = self.type_check_exp(orelse, env)
  7591. check_type_equal(b, o, e)
  7592. return b
  7593. case _:
  7594. return super().type_check_exp(e, env)
  7595. def type_check_stmts(self, ss, env):
  7596. if len(ss) == 0:
  7597. return
  7598. match ss[0]:
  7599. case If(test, body, orelse):
  7600. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7601. b = self.type_check_stmts(body, env)
  7602. o = self.type_check_stmts(orelse, env)
  7603. check_type_equal(b, o, ss[0])
  7604. return self.type_check_stmts(ss[1:], env)
  7605. case _:
  7606. return super().type_check_stmts(ss, env)
  7607. \end{lstlisting}
  7608. \fi}
  7609. \end{tcolorbox}
  7610. \caption{Type checker for the \LangIf{} language.}
  7611. \label{fig:type-check-Lif}
  7612. \end{figure}
  7613. The definition of the type checker for \LangIf{} is shown in
  7614. figure~\ref{fig:type-check-Lif}.
  7615. %
  7616. The type of a Boolean constant is \BOOLTY{}.
  7617. %
  7618. \racket{The \code{operator-types} function adds dictionary entries for
  7619. the new operators.}
  7620. %
  7621. \python{Logical not requires its argument to be a \BOOLTY{} and
  7622. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7623. %
  7624. The equality operator requires the two arguments to have the same type,
  7625. and therefore we handle it separately from the other operators.
  7626. %
  7627. \python{The other comparisons (less-than, etc.) require their
  7628. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7629. %
  7630. The condition of an \code{if} must
  7631. be of \BOOLTY{} type, and the two branches must have the same type.
  7632. \begin{exercise}\normalfont\normalsize
  7633. Create ten new test programs in \LangIf{}. Half the programs should
  7634. have a type error. For those programs, create an empty file with the
  7635. same base name and with file extension \code{.tyerr}. For example, if
  7636. the test
  7637. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7638. is expected to error, then create
  7639. an empty file named \code{cond\_test\_14.tyerr}.
  7640. %
  7641. \racket{This indicates to \code{interp-tests} and
  7642. \code{compiler-tests} that a type error is expected. }
  7643. %
  7644. The other half of the test programs should not have type errors.
  7645. %
  7646. \racket{In the \code{run-tests.rkt} script, change the second argument
  7647. of \code{interp-tests} and \code{compiler-tests} to
  7648. \code{type-check-Lif}, which causes the type checker to run prior to
  7649. the compiler passes. Temporarily change the \code{passes} to an
  7650. empty list and run the script, thereby checking that the new test
  7651. programs either type check or do not, as intended.}
  7652. %
  7653. Run the test script to check that these test programs type check as
  7654. expected.
  7655. \end{exercise}
  7656. \clearpage
  7657. \section{The \LangCIf{} Intermediate Language}
  7658. \label{sec:Cif}
  7659. {\if\edition\racketEd
  7660. %
  7661. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7662. comparison operators to the \Exp{} nonterminal and the literals
  7663. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7664. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7665. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7666. comparison operation and the branches are \code{goto} statements,
  7667. making it straightforward to compile \code{if} statements to x86. The
  7668. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7669. expressions. A \code{goto} statement transfers control to the $\Tail$
  7670. expression corresponding to its label.
  7671. %
  7672. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7673. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7674. defines its abstract syntax.
  7675. %
  7676. \fi}
  7677. %
  7678. {\if\edition\pythonEd\pythonColor
  7679. %
  7680. The output of \key{explicate\_control} is a language similar to the
  7681. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7682. \code{goto} statements, so we name it \LangCIf{}.
  7683. %
  7684. The \LangCIf{} language supports the same operators as \LangIf{} but
  7685. the arguments of operators are restricted to atomic expressions. The
  7686. \LangCIf{} language does not include \code{if} expressions but it does
  7687. include a restricted form of \code{if} statement. The condition must be
  7688. a comparison and the two branches may only contain \code{goto}
  7689. statements. These restrictions make it easier to translate \code{if}
  7690. statements to x86. The \LangCIf{} language also adds a \code{return}
  7691. statement to finish the program with a specified value.
  7692. %
  7693. The \key{CProgram} construct contains a dictionary mapping labels to
  7694. lists of statements that end with a \code{return} statement, a
  7695. \code{goto}, or a conditional \code{goto}.
  7696. %% Statement lists of this
  7697. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7698. %% is a control transfer at the end and control only enters at the
  7699. %% beginning of the list, which is marked by the label.
  7700. %
  7701. A \code{goto} statement transfers control to the sequence of statements
  7702. associated with its label.
  7703. %
  7704. The concrete syntax for \LangCIf{} is defined in
  7705. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7706. in figure~\ref{fig:c1-syntax}.
  7707. %
  7708. \fi}
  7709. %
  7710. \newcommand{\CifGrammarRacket}{
  7711. \begin{array}{lcl}
  7712. \Atm &::=& \itm{bool} \\
  7713. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7714. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7715. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7716. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7717. \end{array}
  7718. }
  7719. \newcommand{\CifASTRacket}{
  7720. \begin{array}{lcl}
  7721. \Atm &::=& \BOOL{\itm{bool}} \\
  7722. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7723. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7724. \Tail &::= & \GOTO{\itm{label}} \\
  7725. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7726. \end{array}
  7727. }
  7728. \newcommand{\CifGrammarPython}{
  7729. \begin{array}{lcl}
  7730. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7731. \Exp &::= & \Atm \MID \CREAD{}
  7732. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7733. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7734. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7735. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7736. &\MID& \CASSIGN{\Var}{\Exp}
  7737. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7738. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7739. \end{array}
  7740. }
  7741. \newcommand{\CifASTPython}{
  7742. \begin{array}{lcl}
  7743. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7744. \Exp &::= & \Atm \MID \READ{} \\
  7745. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7746. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7747. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7748. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7749. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7750. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7751. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7752. \end{array}
  7753. }
  7754. \begin{figure}[tbp]
  7755. \begin{tcolorbox}[colback=white]
  7756. \small
  7757. {\if\edition\racketEd
  7758. \[
  7759. \begin{array}{l}
  7760. \gray{\CvarGrammarRacket} \\ \hline
  7761. \CifGrammarRacket \\
  7762. \begin{array}{lcl}
  7763. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7764. \end{array}
  7765. \end{array}
  7766. \]
  7767. \fi}
  7768. {\if\edition\pythonEd\pythonColor
  7769. \[
  7770. \begin{array}{l}
  7771. \CifGrammarPython \\
  7772. \begin{array}{lcl}
  7773. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7774. \end{array}
  7775. \end{array}
  7776. \]
  7777. \fi}
  7778. \end{tcolorbox}
  7779. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7780. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7781. \label{fig:c1-concrete-syntax}
  7782. \end{figure}
  7783. \begin{figure}[tp]
  7784. \begin{tcolorbox}[colback=white]
  7785. \small
  7786. {\if\edition\racketEd
  7787. \[
  7788. \begin{array}{l}
  7789. \gray{\CvarASTRacket} \\ \hline
  7790. \CifASTRacket \\
  7791. \begin{array}{lcl}
  7792. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7793. \end{array}
  7794. \end{array}
  7795. \]
  7796. \fi}
  7797. {\if\edition\pythonEd\pythonColor
  7798. \[
  7799. \begin{array}{l}
  7800. \CifASTPython \\
  7801. \begin{array}{lcl}
  7802. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7803. \end{array}
  7804. \end{array}
  7805. \]
  7806. \fi}
  7807. \end{tcolorbox}
  7808. \racket{
  7809. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7810. }
  7811. \index{subject}{Goto@\texttt{Goto}}
  7812. \index{subject}{Return@\texttt{Return}}
  7813. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7814. (figure~\ref{fig:c0-syntax})}.}
  7815. \label{fig:c1-syntax}
  7816. \end{figure}
  7817. \section{The \LangXIf{} Language}
  7818. \label{sec:x86-if}
  7819. \index{subject}{x86} To implement the new logical operations, the
  7820. comparison operations, and the \key{if} expression\python{ and
  7821. statement}, we delve further into the x86
  7822. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7823. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7824. subset of x86, which includes instructions for logical operations,
  7825. comparisons, and \racket{conditional} jumps.
  7826. %
  7827. \python{The abstract syntax for an \LangXIf{} program contains a
  7828. dictionary mapping labels to sequences of instructions, each of
  7829. which we refer to as a \emph{basic block}\index{subject}{basic
  7830. block}.}
  7831. One challenge is that x86 does not provide an instruction that
  7832. directly implements logical negation (\code{not} in \LangIf{} and
  7833. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7834. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7835. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7836. bit of its arguments, and writes the results into its second argument.
  7837. Recall the following truth table for exclusive-or:
  7838. \begin{center}
  7839. \begin{tabular}{l|cc}
  7840. & 0 & 1 \\ \hline
  7841. 0 & 0 & 1 \\
  7842. 1 & 1 & 0
  7843. \end{tabular}
  7844. \end{center}
  7845. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7846. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7847. for the bit $1$, the result is the opposite of the second bit. Thus,
  7848. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7849. the first argument, as follows, where $\Arg$ is the translation of
  7850. $\Atm$ to x86:
  7851. \[
  7852. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7853. \qquad\Rightarrow\qquad
  7854. \begin{array}{l}
  7855. \key{movq}~ \Arg\key{,} \Var\\
  7856. \key{xorq}~ \key{\$1,} \Var
  7857. \end{array}
  7858. \]
  7859. \newcommand{\GrammarXIf}{
  7860. \begin{array}{lcl}
  7861. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7862. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7863. \Arg &::=& \key{\%}\itm{bytereg}\\
  7864. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7865. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7866. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7867. \MID \key{set}cc~\Arg
  7868. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7869. &\MID& \key{j}cc~\itm{label} \\
  7870. \end{array}
  7871. }
  7872. \begin{figure}[tp]
  7873. \begin{tcolorbox}[colback=white]
  7874. \[
  7875. \begin{array}{l}
  7876. \gray{\GrammarXInt} \\ \hline
  7877. \GrammarXIf \\
  7878. \begin{array}{lcl}
  7879. \LangXIfM{} &::= & \key{.globl main} \\
  7880. & & \key{main:} \; \Instr\ldots
  7881. \end{array}
  7882. \end{array}
  7883. \]
  7884. \end{tcolorbox}
  7885. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7886. \label{fig:x86-1-concrete}
  7887. \end{figure}
  7888. \newcommand{\ASTXIfRacket}{
  7889. \begin{array}{lcl}
  7890. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7891. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7892. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7893. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7894. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7895. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7896. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7897. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7898. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7899. \end{array}
  7900. }
  7901. \begin{figure}[tp]
  7902. \begin{tcolorbox}[colback=white]
  7903. \small
  7904. {\if\edition\racketEd
  7905. \[\arraycolsep=3pt
  7906. \begin{array}{l}
  7907. \gray{\ASTXIntRacket} \\ \hline
  7908. \ASTXIfRacket \\
  7909. \begin{array}{lcl}
  7910. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7911. \end{array}
  7912. \end{array}
  7913. \]
  7914. \fi}
  7915. %
  7916. {\if\edition\pythonEd\pythonColor
  7917. \[
  7918. \begin{array}{lcl}
  7919. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7920. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7921. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7922. \MID \BYTEREG{\itm{bytereg}} \\
  7923. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7924. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7925. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7926. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7927. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7928. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7929. \MID \PUSHQ{\Arg}} \\
  7930. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7931. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7932. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7933. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7934. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7935. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7936. \Block &::= & \Instr^{+} \\
  7937. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7938. \end{array}
  7939. \]
  7940. \fi}
  7941. \end{tcolorbox}
  7942. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7943. \label{fig:x86-1}
  7944. \end{figure}
  7945. Next we consider the x86 instructions that are relevant for compiling
  7946. the comparison operations. The \key{cmpq} instruction compares its two
  7947. arguments to determine whether one argument is less than, equal to, or
  7948. greater than the other argument. The \key{cmpq} instruction is unusual
  7949. regarding the order of its arguments and where the result is
  7950. placed. The argument order is backward: if you want to test whether
  7951. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7952. \key{cmpq} is placed in the special EFLAGS register. This register
  7953. cannot be accessed directly, but it can be queried by a number of
  7954. instructions, including the \key{set} instruction. The instruction
  7955. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7956. depending on whether the contents of the EFLAGS register matches the
  7957. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7958. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7959. The \key{set} instruction has a quirk in that its destination argument
  7960. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7961. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7962. register. Thankfully, the \key{movzbq} instruction can be used to
  7963. move from a single-byte register to a normal 64-bit register. The
  7964. abstract syntax for the \code{set} instruction differs from the
  7965. concrete syntax in that it separates the instruction name from the
  7966. condition code.
  7967. \python{The x86 instructions for jumping are relevant to the
  7968. compilation of \key{if} expressions.}
  7969. %
  7970. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7971. counter to the address of the instruction after the specified
  7972. label.}
  7973. %
  7974. \racket{The x86 instruction for conditional jump is relevant to the
  7975. compilation of \key{if} expressions.}
  7976. %
  7977. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7978. counter to point to the instruction after \itm{label}, depending on
  7979. whether the result in the EFLAGS register matches the condition code
  7980. \itm{cc}; otherwise, the jump instruction falls through to the next
  7981. instruction. Like the abstract syntax for \code{set}, the abstract
  7982. syntax for conditional jump separates the instruction name from the
  7983. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7984. corresponds to \code{jle foo}. Because the conditional jump instruction
  7985. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7986. a \key{cmpq} instruction to set the EFLAGS register.
  7987. \section{Shrink the \LangIf{} Language}
  7988. \label{sec:shrink-Lif}
  7989. The \LangIf{} language includes several features that are easily
  7990. expressible with other features. For example, \code{and} and \code{or}
  7991. are expressible using \code{if} as follows.
  7992. \begin{align*}
  7993. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7994. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7995. \end{align*}
  7996. By performing these translations in the front end of the compiler,
  7997. subsequent passes of the compiler do not need to deal with these features,
  7998. thus making the passes shorter.
  7999. On the other hand, translations sometimes reduce the efficiency of the
  8000. generated code by increasing the number of instructions. For example,
  8001. expressing subtraction in terms of negation
  8002. \[
  8003. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8004. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8005. \]
  8006. produces code with two x86 instructions (\code{negq} and \code{addq})
  8007. instead of just one (\code{subq}).
  8008. \begin{exercise}\normalfont\normalsize
  8009. %
  8010. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8011. the language by translating them to \code{if} expressions in \LangIf{}.
  8012. %
  8013. Create four test programs that involve these operators.
  8014. %
  8015. {\if\edition\racketEd
  8016. In the \code{run-tests.rkt} script, add the following entry for
  8017. \code{shrink} to the list of passes (it should be the only pass at
  8018. this point).
  8019. \begin{lstlisting}
  8020. (list "shrink" shrink interp_Lif type-check-Lif)
  8021. \end{lstlisting}
  8022. This instructs \code{interp-tests} to run the interpreter
  8023. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8024. output of \code{shrink}.
  8025. \fi}
  8026. %
  8027. Run the script to test your compiler on all the test programs.
  8028. \end{exercise}
  8029. {\if\edition\racketEd
  8030. \section{Uniquify Variables}
  8031. \label{sec:uniquify-Lif}
  8032. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8033. \code{if} expressions.
  8034. \begin{exercise}\normalfont\normalsize
  8035. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8036. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8037. \begin{lstlisting}
  8038. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8039. \end{lstlisting}
  8040. Run the script to test your compiler.
  8041. \end{exercise}
  8042. \fi}
  8043. \section{Remove Complex Operands}
  8044. \label{sec:remove-complex-opera-Lif}
  8045. The output language of \code{remove\_complex\_operands} is
  8046. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8047. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8048. but the \code{if} expression is not. All three subexpressions of an
  8049. \code{if} are allowed to be complex expressions, but the operands of
  8050. the \code{not} operator and comparison operators must be atomic.
  8051. %
  8052. \python{We add a new language form, the \code{Begin} expression, to aid
  8053. in the translation of \code{if} expressions. When we recursively
  8054. process the two branches of the \code{if}, we generate temporary
  8055. variables and their initializing expressions. However, these
  8056. expressions may contain side effects and should only be executed
  8057. when the condition of the \code{if} is true (for the ``then''
  8058. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8059. a way to initialize the temporary variables within the two branches
  8060. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8061. form execute the statements $ss$ and then returns the result of
  8062. expression $e$.}
  8063. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8064. the new features in \LangIf{}. In recursively processing
  8065. subexpressions, recall that you should invoke \code{rco\_atom} when
  8066. the output needs to be an \Atm{} (as specified in the grammar for
  8067. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8068. \Exp{}. Regarding \code{if}, it is particularly important
  8069. \textbf{not} to replace its condition with a temporary variable, because
  8070. that would interfere with the generation of high-quality output in the
  8071. upcoming \code{explicate\_control} pass.
  8072. \newcommand{\LifMonadASTRacket}{
  8073. \begin{array}{rcl}
  8074. \Atm &::=& \BOOL{\itm{bool}}\\
  8075. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8076. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8077. \MID \IF{\Exp}{\Exp}{\Exp}
  8078. \end{array}
  8079. }
  8080. \newcommand{\LifMonadASTPython}{
  8081. \begin{array}{rcl}
  8082. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8083. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8084. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8085. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8086. \Atm &::=& \BOOL{\itm{bool}}\\
  8087. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8088. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8089. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8090. \end{array}
  8091. }
  8092. \begin{figure}[tp]
  8093. \centering
  8094. \begin{tcolorbox}[colback=white]
  8095. {\if\edition\racketEd
  8096. \[
  8097. \begin{array}{l}
  8098. \gray{\LvarMonadASTRacket} \\ \hline
  8099. \LifMonadASTRacket \\
  8100. \begin{array}{rcl}
  8101. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8102. \end{array}
  8103. \end{array}
  8104. \]
  8105. \fi}
  8106. {\if\edition\pythonEd\pythonColor
  8107. \[
  8108. \begin{array}{l}
  8109. \gray{\LvarMonadASTPython} \\ \hline
  8110. \LifMonadASTPython \\
  8111. \begin{array}{rcl}
  8112. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8113. \end{array}
  8114. \end{array}
  8115. \]
  8116. \fi}
  8117. \end{tcolorbox}
  8118. \python{\index{subject}{Begin@\texttt{Begin}}}
  8119. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8120. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8121. \label{fig:Lif-anf-syntax}
  8122. \end{figure}
  8123. \begin{exercise}\normalfont\normalsize
  8124. %
  8125. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8126. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8127. %
  8128. Create three new \LangIf{} programs that exercise the interesting
  8129. code in this pass.
  8130. %
  8131. {\if\edition\racketEd
  8132. In the \code{run-tests.rkt} script, add the following entry to the
  8133. list of \code{passes} and then run the script to test your compiler.
  8134. \begin{lstlisting}
  8135. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8136. \end{lstlisting}
  8137. \fi}
  8138. \end{exercise}
  8139. \section{Explicate Control}
  8140. \label{sec:explicate-control-Lif}
  8141. \racket{Recall that the purpose of \code{explicate\_control} is to
  8142. make the order of evaluation explicit in the syntax of the program.
  8143. With the addition of \key{if}, this becomes more interesting.}
  8144. %
  8145. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8146. %
  8147. The main challenge to overcome is that the condition of an \key{if}
  8148. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8149. condition must be a comparison.
  8150. As a motivating example, consider the following program that has an
  8151. \key{if} expression nested in the condition of another \key{if}:%
  8152. \python{\footnote{Programmers rarely write nested \code{if}
  8153. expressions, but it is not uncommon for the condition of an
  8154. \code{if} statement to be a call of a function that also contains an
  8155. \code{if} statement. When such a function is inlined, the result is
  8156. a nested \code{if} that requires the techniques discussed in this
  8157. section.}}
  8158. % cond_test_41.rkt, if_lt_eq.py
  8159. \begin{center}
  8160. \begin{minipage}{0.96\textwidth}
  8161. {\if\edition\racketEd
  8162. \begin{lstlisting}
  8163. (let ([x (read)])
  8164. (let ([y (read)])
  8165. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8166. (+ y 2)
  8167. (+ y 10))))
  8168. \end{lstlisting}
  8169. \fi}
  8170. {\if\edition\pythonEd\pythonColor
  8171. \begin{lstlisting}
  8172. x = input_int()
  8173. y = input_int()
  8174. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8175. \end{lstlisting}
  8176. \fi}
  8177. \end{minipage}
  8178. \end{center}
  8179. %
  8180. The naive way to compile \key{if} and the comparison operations would
  8181. be to handle each of them in isolation, regardless of their context.
  8182. Each comparison would be translated into a \key{cmpq} instruction
  8183. followed by several instructions to move the result from the EFLAGS
  8184. register into a general purpose register or stack location. Each
  8185. \key{if} would be translated into a \key{cmpq} instruction followed by
  8186. a conditional jump. The generated code for the inner \key{if} in this
  8187. example would be as follows:
  8188. \begin{center}
  8189. \begin{minipage}{0.96\textwidth}
  8190. \begin{lstlisting}
  8191. cmpq $1, x
  8192. setl %al
  8193. movzbq %al, tmp
  8194. cmpq $1, tmp
  8195. je then_branch_1
  8196. jmp else_branch_1
  8197. \end{lstlisting}
  8198. \end{minipage}
  8199. \end{center}
  8200. Notice that the three instructions starting with \code{setl} are
  8201. redundant: the conditional jump could come immediately after the first
  8202. \code{cmpq}.
  8203. Our goal is to compile \key{if} expressions so that the relevant
  8204. comparison instruction appears directly before the conditional jump.
  8205. For example, we want to generate the following code for the inner
  8206. \code{if}:
  8207. \begin{center}
  8208. \begin{minipage}{0.96\textwidth}
  8209. \begin{lstlisting}
  8210. cmpq $1, x
  8211. jl then_branch_1
  8212. jmp else_branch_1
  8213. \end{lstlisting}
  8214. \end{minipage}
  8215. \end{center}
  8216. One way to achieve this goal is to reorganize the code at the level of
  8217. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8218. the following code:
  8219. \begin{center}
  8220. \begin{minipage}{0.96\textwidth}
  8221. {\if\edition\racketEd
  8222. \begin{lstlisting}
  8223. (let ([x (read)])
  8224. (let ([y (read)])
  8225. (if (< x 1)
  8226. (if (eq? x 0)
  8227. (+ y 2)
  8228. (+ y 10))
  8229. (if (eq? x 2)
  8230. (+ y 2)
  8231. (+ y 10)))))
  8232. \end{lstlisting}
  8233. \fi}
  8234. {\if\edition\pythonEd\pythonColor
  8235. \begin{lstlisting}
  8236. x = input_int()
  8237. y = input_int()
  8238. print(((y + 2) if x == 0 else (y + 10)) \
  8239. if (x < 1) \
  8240. else ((y + 2) if (x == 2) else (y + 10)))
  8241. \end{lstlisting}
  8242. \fi}
  8243. \end{minipage}
  8244. \end{center}
  8245. Unfortunately, this approach duplicates the two branches from the
  8246. outer \code{if}, and a compiler must never duplicate code! After all,
  8247. the two branches could be very large expressions.
  8248. How can we apply this transformation without duplicating code? In
  8249. other words, how can two different parts of a program refer to one
  8250. piece of code?
  8251. %
  8252. The answer is that we must move away from abstract syntax \emph{trees}
  8253. and instead use \emph{graphs}.
  8254. %
  8255. At the level of x86 assembly, this is straightforward because we can
  8256. label the code for each branch and insert jumps in all the places that
  8257. need to execute the branch. In this way, jump instructions are edges
  8258. in the graph and the basic blocks are the nodes.
  8259. %
  8260. Likewise, our language \LangCIf{} provides the ability to label a
  8261. sequence of statements and to jump to a label via \code{goto}.
  8262. As a preview of what \code{explicate\_control} will do,
  8263. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8264. \code{explicate\_control} on this example. Note how the condition of
  8265. every \code{if} is a comparison operation and that we have not
  8266. duplicated any code but instead have used labels and \code{goto} to
  8267. enable sharing of code.
  8268. \begin{figure}[tbp]
  8269. \begin{tcolorbox}[colback=white]
  8270. {\if\edition\racketEd
  8271. \begin{tabular}{lll}
  8272. \begin{minipage}{0.4\textwidth}
  8273. % cond_test_41.rkt
  8274. \begin{lstlisting}
  8275. (let ([x (read)])
  8276. (let ([y (read)])
  8277. (if (if (< x 1)
  8278. (eq? x 0)
  8279. (eq? x 2))
  8280. (+ y 2)
  8281. (+ y 10))))
  8282. \end{lstlisting}
  8283. \end{minipage}
  8284. &
  8285. $\Rightarrow$
  8286. &
  8287. \begin{minipage}{0.55\textwidth}
  8288. \begin{lstlisting}
  8289. start:
  8290. x = (read);
  8291. y = (read);
  8292. if (< x 1)
  8293. goto block_4;
  8294. else
  8295. goto block_5;
  8296. block_4:
  8297. if (eq? x 0)
  8298. goto block_2;
  8299. else
  8300. goto block_3;
  8301. block_5:
  8302. if (eq? x 2)
  8303. goto block_2;
  8304. else
  8305. goto block_3;
  8306. block_2:
  8307. return (+ y 2);
  8308. block_3:
  8309. return (+ y 10);
  8310. \end{lstlisting}
  8311. \end{minipage}
  8312. \end{tabular}
  8313. \fi}
  8314. {\if\edition\pythonEd\pythonColor
  8315. \begin{tabular}{lll}
  8316. \begin{minipage}{0.4\textwidth}
  8317. % cond_test_41.rkt
  8318. \begin{lstlisting}
  8319. x = input_int()
  8320. y = input_int()
  8321. print(y + 2 \
  8322. if (x == 0 \
  8323. if x < 1 \
  8324. else x == 2) \
  8325. else y + 10)
  8326. \end{lstlisting}
  8327. \end{minipage}
  8328. &
  8329. $\Rightarrow$
  8330. &
  8331. \begin{minipage}{0.55\textwidth}
  8332. \begin{lstlisting}
  8333. start:
  8334. x = input_int()
  8335. y = input_int()
  8336. if x < 1:
  8337. goto block_8
  8338. else:
  8339. goto block_9
  8340. block_8:
  8341. if x == 0:
  8342. goto block_4
  8343. else:
  8344. goto block_5
  8345. block_9:
  8346. if x == 2:
  8347. goto block_6
  8348. else:
  8349. goto block_7
  8350. block_4:
  8351. goto block_2
  8352. block_5:
  8353. goto block_3
  8354. block_6:
  8355. goto block_2
  8356. block_7:
  8357. goto block_3
  8358. block_2:
  8359. tmp_0 = y + 2
  8360. goto block_1
  8361. block_3:
  8362. tmp_0 = y + 10
  8363. goto block_1
  8364. block_1:
  8365. print(tmp_0)
  8366. return 0
  8367. \end{lstlisting}
  8368. \end{minipage}
  8369. \end{tabular}
  8370. \fi}
  8371. \end{tcolorbox}
  8372. \caption{Translation from \LangIf{} to \LangCIf{}
  8373. via the \code{explicate\_control}.}
  8374. \label{fig:explicate-control-s1-38}
  8375. \end{figure}
  8376. {\if\edition\racketEd
  8377. %
  8378. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8379. \code{explicate\_control} for \LangVar{} using two recursive
  8380. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8381. former function translates expressions in tail position, whereas the
  8382. latter function translates expressions on the right-hand side of a
  8383. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8384. have a new kind of position to deal with: the predicate position of
  8385. the \key{if}. We need another function, \code{explicate\_pred}, that
  8386. decides how to compile an \key{if} by analyzing its condition. So,
  8387. \code{explicate\_pred} takes an \LangIf{} expression and two
  8388. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8389. and outputs a tail. In the following paragraphs we discuss specific
  8390. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8391. \code{explicate\_pred} functions.
  8392. %
  8393. \fi}
  8394. %
  8395. {\if\edition\pythonEd\pythonColor
  8396. %
  8397. We recommend implementing \code{explicate\_control} using the
  8398. following four auxiliary functions.
  8399. \begin{description}
  8400. \item[\code{explicate\_effect}] generates code for expressions as
  8401. statements, so their result is ignored and only their side effects
  8402. matter.
  8403. \item[\code{explicate\_assign}] generates code for expressions
  8404. on the right-hand side of an assignment.
  8405. \item[\code{explicate\_pred}] generates code for an \code{if}
  8406. expression or statement by analyzing the condition expression.
  8407. \item[\code{explicate\_stmt}] generates code for statements.
  8408. \end{description}
  8409. These four functions should build the dictionary of basic blocks. The
  8410. following auxiliary function can be used to create a new basic block
  8411. from a list of statements. It returns a \code{goto} statement that
  8412. jumps to the new basic block.
  8413. \begin{center}
  8414. \begin{minipage}{\textwidth}
  8415. \begin{lstlisting}
  8416. def create_block(stmts, basic_blocks):
  8417. label = label_name(generate_name('block'))
  8418. basic_blocks[label] = stmts
  8419. return Goto(label)
  8420. \end{lstlisting}
  8421. \end{minipage}
  8422. \end{center}
  8423. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8424. \code{explicate\_control} pass.
  8425. The \code{explicate\_effect} function has three parameters: 1) the
  8426. expression to be compiled, 2) the already-compiled code for this
  8427. expression's \emph{continuation}, that is, the list of statements that
  8428. should execute after this expression, and 3) the dictionary of
  8429. generated basic blocks. The \code{explicate\_effect} function returns
  8430. a list of \LangCIf{} statements and it may add to the dictionary of
  8431. basic blocks.
  8432. %
  8433. Let's consider a few of the cases for the expression to be compiled.
  8434. If the expression to be compiled is a constant, then it can be
  8435. discarded because it has no side effects. If it's a \CREAD{}, then it
  8436. has a side-effect and should be preserved. So the expression should be
  8437. translated into a statement using the \code{Expr} AST class. If the
  8438. expression to be compiled is an \code{if} expression, we translate the
  8439. two branches using \code{explicate\_effect} and then translate the
  8440. condition expression using \code{explicate\_pred}, which generates
  8441. code for the entire \code{if}.
  8442. The \code{explicate\_assign} function has four parameters: 1) the
  8443. right-hand side of the assignment, 2) the left-hand side of the
  8444. assignment (the variable), 3) the continuation, and 4) the dictionary
  8445. of basic blocks. The \code{explicate\_assign} function returns a list
  8446. of \LangCIf{} statements and it may add to the dictionary of basic
  8447. blocks.
  8448. When the right-hand side is an \code{if} expression, there is some
  8449. work to do. In particular, the two branches should be translated using
  8450. \code{explicate\_assign} and the condition expression should be
  8451. translated using \code{explicate\_pred}. Otherwise we can simply
  8452. generate an assignment statement, with the given left and right-hand
  8453. sides, concatenated with its continuation.
  8454. \begin{figure}[tbp]
  8455. \begin{tcolorbox}[colback=white]
  8456. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8457. def explicate_effect(e, cont, basic_blocks):
  8458. match e:
  8459. case IfExp(test, body, orelse):
  8460. ...
  8461. case Call(func, args):
  8462. ...
  8463. case Begin(body, result):
  8464. ...
  8465. case _:
  8466. ...
  8467. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8468. match rhs:
  8469. case IfExp(test, body, orelse):
  8470. ...
  8471. case Begin(body, result):
  8472. ...
  8473. case _:
  8474. return [Assign([lhs], rhs)] + cont
  8475. def explicate_pred(cnd, thn, els, basic_blocks):
  8476. match cnd:
  8477. case Compare(left, [op], [right]):
  8478. goto_thn = create_block(thn, basic_blocks)
  8479. goto_els = create_block(els, basic_blocks)
  8480. return [If(cnd, [goto_thn], [goto_els])]
  8481. case Constant(True):
  8482. return thn;
  8483. case Constant(False):
  8484. return els;
  8485. case UnaryOp(Not(), operand):
  8486. ...
  8487. case IfExp(test, body, orelse):
  8488. ...
  8489. case Begin(body, result):
  8490. ...
  8491. case _:
  8492. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8493. [create_block(els, basic_blocks)],
  8494. [create_block(thn, basic_blocks)])]
  8495. def explicate_stmt(s, cont, basic_blocks):
  8496. match s:
  8497. case Assign([lhs], rhs):
  8498. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8499. case Expr(value):
  8500. return explicate_effect(value, cont, basic_blocks)
  8501. case If(test, body, orelse):
  8502. ...
  8503. def explicate_control(p):
  8504. match p:
  8505. case Module(body):
  8506. new_body = [Return(Constant(0))]
  8507. basic_blocks = {}
  8508. for s in reversed(body):
  8509. new_body = explicate_stmt(s, new_body, basic_blocks)
  8510. basic_blocks[label_name('start')] = new_body
  8511. return CProgram(basic_blocks)
  8512. \end{lstlisting}
  8513. \end{tcolorbox}
  8514. \caption{Skeleton for the \code{explicate\_control} pass.}
  8515. \label{fig:explicate-control-Lif}
  8516. \end{figure}
  8517. \fi}
  8518. {\if\edition\racketEd
  8519. \subsection{Explicate Tail and Assign}
  8520. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8521. additional cases for Boolean constants and \key{if}. The cases for
  8522. \code{if} should recursively compile the two branches using either
  8523. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8524. cases should then invoke \code{explicate\_pred} on the condition
  8525. expression, passing in the generated code for the two branches. For
  8526. example, consider the following program with an \code{if} in tail
  8527. position.
  8528. % cond_test_6.rkt
  8529. \begin{lstlisting}
  8530. (let ([x (read)])
  8531. (if (eq? x 0) 42 777))
  8532. \end{lstlisting}
  8533. The two branches are recursively compiled to return statements. We
  8534. then delegate to \code{explicate\_pred}, passing the condition
  8535. \code{(eq? x 0)} and the two return statements. We return to this
  8536. example shortly when we discuss \code{explicate\_pred}.
  8537. Next let us consider a program with an \code{if} on the right-hand
  8538. side of a \code{let}.
  8539. \begin{lstlisting}
  8540. (let ([y (read)])
  8541. (let ([x (if (eq? y 0) 40 777)])
  8542. (+ x 2)))
  8543. \end{lstlisting}
  8544. Note that the body of the inner \code{let} will have already been
  8545. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8546. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8547. to recursively process both branches of the \code{if}, and we do not
  8548. want to duplicate code, so we generate the following block using an
  8549. auxiliary function named \code{create\_block}, discussed in the next
  8550. section.
  8551. \begin{lstlisting}
  8552. block_6:
  8553. return (+ x 2)
  8554. \end{lstlisting}
  8555. We then use \code{goto block\_6;} as the \code{cont} argument for
  8556. compiling the branches. So the two branches compile to
  8557. \begin{center}
  8558. \begin{minipage}{0.2\textwidth}
  8559. \begin{lstlisting}
  8560. x = 40;
  8561. goto block_6;
  8562. \end{lstlisting}
  8563. \end{minipage}
  8564. \hspace{0.5in} and \hspace{0.5in}
  8565. \begin{minipage}{0.2\textwidth}
  8566. \begin{lstlisting}
  8567. x = 777;
  8568. goto block_6;
  8569. \end{lstlisting}
  8570. \end{minipage}
  8571. \end{center}
  8572. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8573. \code{(eq? y 0)} and the previously presented code for the branches.
  8574. \subsection{Create Block}
  8575. We recommend implementing the \code{create\_block} auxiliary function
  8576. as follows, using a global variable \code{basic-blocks} to store a
  8577. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8578. that \code{create\_block} generates a new label and then associates
  8579. the given \code{tail} with the new label in the \code{basic-blocks}
  8580. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8581. new label. However, if the given \code{tail} is already a \code{Goto},
  8582. then there is no need to generate a new label and entry in
  8583. \code{basic-blocks}; we can simply return that \code{Goto}.
  8584. %
  8585. \begin{lstlisting}
  8586. (define (create_block tail)
  8587. (match tail
  8588. [(Goto label) (Goto label)]
  8589. [else
  8590. (let ([label (gensym 'block)])
  8591. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8592. (Goto label))]))
  8593. \end{lstlisting}
  8594. \fi}
  8595. {\if\edition\racketEd
  8596. \subsection{Explicate Predicate}
  8597. \begin{figure}[tbp]
  8598. \begin{tcolorbox}[colback=white]
  8599. \begin{lstlisting}
  8600. (define (explicate_pred cnd thn els)
  8601. (match cnd
  8602. [(Var x) ___]
  8603. [(Let x rhs body) ___]
  8604. [(Prim 'not (list e)) ___]
  8605. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8606. (IfStmt (Prim op es) (create_block thn)
  8607. (create_block els))]
  8608. [(Bool b) (if b thn els)]
  8609. [(If cnd^ thn^ els^) ___]
  8610. [else (error "explicate_pred unhandled case" cnd)]))
  8611. \end{lstlisting}
  8612. \end{tcolorbox}
  8613. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8614. \label{fig:explicate-pred}
  8615. \end{figure}
  8616. \fi}
  8617. \racket{The skeleton for the \code{explicate\_pred} function is given
  8618. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  8619. (1) \code{cnd}, the condition expression of the \code{if};
  8620. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  8621. and (3) \code{els}, the code generated by
  8622. explicate for the \emph{else} branch. The \code{explicate\_pred}
  8623. function should match on \code{cnd} with a case for
  8624. every kind of expression that can have type \BOOLTY{}.}
  8625. %
  8626. \python{The \code{explicate\_pred} function has four parameters: 1)
  8627. the condition expression, 2) the generated statements for the
  8628. ``then'' branch, 3) the generated statements for the ``else''
  8629. branch, and 4) the dictionary of basic blocks. The
  8630. \code{explicate\_pred} function returns a list of \LangCIf{}
  8631. statements and it may add to the dictionary of basic blocks.}
  8632. Consider the case for comparison operators. We translate the
  8633. comparison to an \code{if} statement whose branches are \code{goto}
  8634. statements created by applying \code{create\_block} to the code
  8635. generated for the \code{thn} and \code{els} branches. Let us
  8636. illustrate this translation by returning to the program with an
  8637. \code{if} expression in tail position, shown next. We invoke
  8638. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  8639. \python{\code{x == 0}}.
  8640. %
  8641. {\if\edition\racketEd
  8642. \begin{lstlisting}
  8643. (let ([x (read)])
  8644. (if (eq? x 0) 42 777))
  8645. \end{lstlisting}
  8646. \fi}
  8647. %
  8648. {\if\edition\pythonEd\pythonColor
  8649. \begin{lstlisting}
  8650. x = input_int()
  8651. 42 if x == 0 else 777
  8652. \end{lstlisting}
  8653. \fi}
  8654. %
  8655. \noindent The two branches \code{42} and \code{777} were already
  8656. compiled to \code{return} statements, from which we now create the
  8657. following blocks:
  8658. %
  8659. \begin{center}
  8660. \begin{minipage}{\textwidth}
  8661. \begin{lstlisting}
  8662. block_1:
  8663. return 42;
  8664. block_2:
  8665. return 777;
  8666. \end{lstlisting}
  8667. \end{minipage}
  8668. \end{center}
  8669. %
  8670. After that, \code{explicate\_pred} compiles the comparison
  8671. \racket{\code{(eq? x 0)}}
  8672. \python{\code{x == 0}}
  8673. to the following \code{if} statement:
  8674. %
  8675. {\if\edition\racketEd
  8676. \begin{center}
  8677. \begin{minipage}{\textwidth}
  8678. \begin{lstlisting}
  8679. if (eq? x 0)
  8680. goto block_1;
  8681. else
  8682. goto block_2;
  8683. \end{lstlisting}
  8684. \end{minipage}
  8685. \end{center}
  8686. \fi}
  8687. {\if\edition\pythonEd\pythonColor
  8688. \begin{center}
  8689. \begin{minipage}{\textwidth}
  8690. \begin{lstlisting}
  8691. if x == 0:
  8692. goto block_1;
  8693. else
  8694. goto block_2;
  8695. \end{lstlisting}
  8696. \end{minipage}
  8697. \end{center}
  8698. \fi}
  8699. Next consider the case for Boolean constants. We perform a kind of
  8700. partial evaluation\index{subject}{partial evaluation} and output
  8701. either the \code{thn} or \code{els} branch, depending on whether the
  8702. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8703. following program:
  8704. {\if\edition\racketEd
  8705. \begin{lstlisting}
  8706. (if #t 42 777)
  8707. \end{lstlisting}
  8708. \fi}
  8709. {\if\edition\pythonEd\pythonColor
  8710. \begin{lstlisting}
  8711. 42 if True else 777
  8712. \end{lstlisting}
  8713. \fi}
  8714. %
  8715. \noindent Again, the two branches \code{42} and \code{777} were
  8716. compiled to \code{return} statements, so \code{explicate\_pred}
  8717. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8718. code for the \emph{then} branch.
  8719. \begin{lstlisting}
  8720. return 42;
  8721. \end{lstlisting}
  8722. This case demonstrates that we sometimes discard the \code{thn} or
  8723. \code{els} blocks that are input to \code{explicate\_pred}.
  8724. The case for \key{if} expressions in \code{explicate\_pred} is
  8725. particularly illuminating because it deals with the challenges
  8726. discussed previously regarding nested \key{if} expressions
  8727. (figure~\ref{fig:explicate-control-s1-38}). The
  8728. \racket{\lstinline{thn^}}\python{\code{body}} and
  8729. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8730. \key{if} inherit their context from the current one, that is,
  8731. predicate context. So, you should recursively apply
  8732. \code{explicate\_pred} to the
  8733. \racket{\lstinline{thn^}}\python{\code{body}} and
  8734. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8735. those recursive calls, pass \code{thn} and \code{els} as the extra
  8736. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8737. inside each recursive call. As discussed previously, to avoid
  8738. duplicating code, we need to add them to the dictionary of basic
  8739. blocks so that we can instead refer to them by name and execute them
  8740. with a \key{goto}.
  8741. {\if\edition\pythonEd\pythonColor
  8742. %
  8743. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8744. three parameters: 1) the statement to be compiled, 2) the code for its
  8745. continuation, and 3) the dictionary of basic blocks. The
  8746. \code{explicate\_stmt} returns a list of statements and it may add to
  8747. the dictionary of basic blocks. The cases for assignment and an
  8748. expression-statement are given in full in the skeleton code: they
  8749. simply dispatch to \code{explicate\_assign} and
  8750. \code{explicate\_effect}, respectively. The case for \code{if}
  8751. statements is not given, and is similar to the case for \code{if}
  8752. expressions.
  8753. The \code{explicate\_control} function itself is given in
  8754. figure~\ref{fig:explicate-control-Lif}. It applies
  8755. \code{explicate\_stmt} to each statement in the program, from back to
  8756. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8757. used as the continuation parameter in the next call to
  8758. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8759. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8760. the dictionary of basic blocks, labeling it as the ``start'' block.
  8761. %
  8762. \fi}
  8763. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8764. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8765. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8766. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8767. %% results from the two recursive calls. We complete the case for
  8768. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8769. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8770. %% the result $B_5$.
  8771. %% \[
  8772. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8773. %% \quad\Rightarrow\quad
  8774. %% B_5
  8775. %% \]
  8776. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8777. %% inherit the current context, so they are in tail position. Thus, the
  8778. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8779. %% \code{explicate\_tail}.
  8780. %% %
  8781. %% We need to pass $B_0$ as the accumulator argument for both of these
  8782. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8783. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8784. %% to the control-flow graph and obtain a promised goto $G_0$.
  8785. %% %
  8786. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8787. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8788. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8789. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8790. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8791. %% \[
  8792. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8793. %% \]
  8794. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8795. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8796. %% should not be confused with the labels for the blocks that appear in
  8797. %% the generated code. We initially construct unlabeled blocks; we only
  8798. %% attach labels to blocks when we add them to the control-flow graph, as
  8799. %% we see in the next case.
  8800. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8801. %% function. The context of the \key{if} is an assignment to some
  8802. %% variable $x$ and then the control continues to some promised block
  8803. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8804. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8805. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8806. %% branches of the \key{if} inherit the current context, so they are in
  8807. %% assignment positions. Let $B_2$ be the result of applying
  8808. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8809. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8810. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8811. %% the result of applying \code{explicate\_pred} to the predicate
  8812. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8813. %% translates to the promise $B_4$.
  8814. %% \[
  8815. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8816. %% \]
  8817. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8818. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8819. \code{remove\_complex\_operands} pass and then the
  8820. \code{explicate\_control} pass on the example program. We walk through
  8821. the output program.
  8822. %
  8823. Following the order of evaluation in the output of
  8824. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8825. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8826. in the predicate of the inner \key{if}. In the output of
  8827. \code{explicate\_control}, in the
  8828. block labeled \code{start}, two assignment statements are followed by an
  8829. \code{if} statement that branches to \code{block\_4} or
  8830. \code{block\_5}. The blocks associated with those labels contain the
  8831. translations of the code
  8832. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8833. and
  8834. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8835. respectively. In particular, we start \code{block\_4} with the
  8836. comparison
  8837. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8838. and then branch to \code{block\_2} or \code{block\_3},
  8839. which correspond to the two branches of the outer \key{if}, that is,
  8840. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8841. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8842. %
  8843. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8844. %
  8845. \python{The \code{block\_1} corresponds to the \code{print} statement
  8846. at the end of the program.}
  8847. {\if\edition\racketEd
  8848. \subsection{Interactions between Explicate and Shrink}
  8849. The way in which the \code{shrink} pass transforms logical operations
  8850. such as \code{and} and \code{or} can impact the quality of code
  8851. generated by \code{explicate\_control}. For example, consider the
  8852. following program:
  8853. % cond_test_21.rkt, and_eq_input.py
  8854. \begin{lstlisting}
  8855. (if (and (eq? (read) 0) (eq? (read) 1))
  8856. 0
  8857. 42)
  8858. \end{lstlisting}
  8859. The \code{and} operation should transform into something that the
  8860. \code{explicate\_pred} function can analyze and descend through to
  8861. reach the underlying \code{eq?} conditions. Ideally, for this program
  8862. your \code{explicate\_control} pass should generate code similar to
  8863. the following:
  8864. \begin{center}
  8865. \begin{minipage}{\textwidth}
  8866. \begin{lstlisting}
  8867. start:
  8868. tmp1 = (read);
  8869. if (eq? tmp1 0) goto block40;
  8870. else goto block39;
  8871. block40:
  8872. tmp2 = (read);
  8873. if (eq? tmp2 1) goto block38;
  8874. else goto block39;
  8875. block38:
  8876. return 0;
  8877. block39:
  8878. return 42;
  8879. \end{lstlisting}
  8880. \end{minipage}
  8881. \end{center}
  8882. \fi}
  8883. \begin{exercise}\normalfont\normalsize
  8884. \racket{
  8885. Implement the pass \code{explicate\_control} by adding the cases for
  8886. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8887. \code{explicate\_assign} functions. Implement the auxiliary function
  8888. \code{explicate\_pred} for predicate contexts.}
  8889. \python{Implement \code{explicate\_control} pass with its
  8890. four auxiliary functions.}
  8891. %
  8892. Create test cases that exercise all the new cases in the code for
  8893. this pass.
  8894. %
  8895. {\if\edition\racketEd
  8896. Add the following entry to the list of \code{passes} in
  8897. \code{run-tests.rkt}:
  8898. \begin{lstlisting}
  8899. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8900. \end{lstlisting}
  8901. and then run \code{run-tests.rkt} to test your compiler.
  8902. \fi}
  8903. \end{exercise}
  8904. \section{Select Instructions}
  8905. \label{sec:select-Lif}
  8906. \index{subject}{instruction selection}
  8907. The \code{select\_instructions} pass translates \LangCIf{} to
  8908. \LangXIfVar{}.
  8909. %
  8910. \racket{Recall that we implement this pass using three auxiliary
  8911. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8912. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8913. %
  8914. \racket{For $\Atm$, we have new cases for the Booleans.}
  8915. %
  8916. \python{We begin with the Boolean constants.}
  8917. We take the usual approach of encoding them as integers.
  8918. \[
  8919. \TRUE{} \quad\Rightarrow\quad \key{1}
  8920. \qquad\qquad
  8921. \FALSE{} \quad\Rightarrow\quad \key{0}
  8922. \]
  8923. For translating statements, we discuss some of the cases. The
  8924. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8925. discussed at the beginning of this section. Given an assignment, if
  8926. the left-hand-side variable is the same as the argument of \code{not},
  8927. then just the \code{xorq} instruction suffices.
  8928. \[
  8929. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8930. \quad\Rightarrow\quad
  8931. \key{xorq}~\key{\$}1\key{,}~\Var
  8932. \]
  8933. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8934. semantics of x86. In the following translation, let $\Arg$ be the
  8935. result of translating $\Atm$ to x86.
  8936. \[
  8937. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8938. \quad\Rightarrow\quad
  8939. \begin{array}{l}
  8940. \key{movq}~\Arg\key{,}~\Var\\
  8941. \key{xorq}~\key{\$}1\key{,}~\Var
  8942. \end{array}
  8943. \]
  8944. Next consider the cases for equality comparisons. Translating this
  8945. operation to x86 is slightly involved due to the unusual nature of the
  8946. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8947. We recommend translating an assignment with an equality on the
  8948. right-hand side into a sequence of three instructions. \\
  8949. \begin{tabular}{lll}
  8950. \begin{minipage}{0.4\textwidth}
  8951. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8952. \end{minipage}
  8953. &
  8954. $\Rightarrow$
  8955. &
  8956. \begin{minipage}{0.4\textwidth}
  8957. \begin{lstlisting}
  8958. cmpq |$\Arg_2$|, |$\Arg_1$|
  8959. sete %al
  8960. movzbq %al, |$\Var$|
  8961. \end{lstlisting}
  8962. \end{minipage}
  8963. \end{tabular} \\
  8964. The translations for the other comparison operators are similar to
  8965. this but use different condition codes for the \code{set} instruction.
  8966. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8967. \key{goto} and \key{if} statements. Both are straightforward to
  8968. translate to x86.}
  8969. %
  8970. A \key{goto} statement becomes a jump instruction.
  8971. \[
  8972. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8973. \]
  8974. %
  8975. An \key{if} statement becomes a compare instruction followed by a
  8976. conditional jump (for the \emph{then} branch), and the fall-through is to
  8977. a regular jump (for the \emph{else} branch).\\
  8978. \begin{tabular}{lll}
  8979. \begin{minipage}{0.4\textwidth}
  8980. \begin{lstlisting}
  8981. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8982. goto |$\ell_1$||$\racket{\key{;}}$|
  8983. else|$\python{\key{:}}$|
  8984. goto |$\ell_2$||$\racket{\key{;}}$|
  8985. \end{lstlisting}
  8986. \end{minipage}
  8987. &
  8988. $\Rightarrow$
  8989. &
  8990. \begin{minipage}{0.4\textwidth}
  8991. \begin{lstlisting}
  8992. cmpq |$\Arg_2$|, |$\Arg_1$|
  8993. je |$\ell_1$|
  8994. jmp |$\ell_2$|
  8995. \end{lstlisting}
  8996. \end{minipage}
  8997. \end{tabular} \\
  8998. Again, the translations for the other comparison operators are similar to this
  8999. but use different condition codes for the conditional jump instruction.
  9000. \python{Regarding the \key{return} statement, we recommend treating it
  9001. as an assignment to the \key{rax} register followed by a jump to the
  9002. conclusion of the \code{main} function.}
  9003. \begin{exercise}\normalfont\normalsize
  9004. Expand your \code{select\_instructions} pass to handle the new
  9005. features of the \LangCIf{} language.
  9006. %
  9007. {\if\edition\racketEd
  9008. Add the following entry to the list of \code{passes} in
  9009. \code{run-tests.rkt}
  9010. \begin{lstlisting}
  9011. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9012. \end{lstlisting}
  9013. \fi}
  9014. %
  9015. Run the script to test your compiler on all the test programs.
  9016. \end{exercise}
  9017. \section{Register Allocation}
  9018. \label{sec:register-allocation-Lif}
  9019. \index{subject}{register allocation}
  9020. The changes required for compiling \LangIf{} affect liveness analysis,
  9021. building the interference graph, and assigning homes, but the graph
  9022. coloring algorithm itself does not change.
  9023. \subsection{Liveness Analysis}
  9024. \label{sec:liveness-analysis-Lif}
  9025. \index{subject}{liveness analysis}
  9026. Recall that for \LangVar{} we implemented liveness analysis for a
  9027. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9028. the addition of \key{if} expressions to \LangIf{},
  9029. \code{explicate\_control} produces many basic blocks.
  9030. %% We recommend that you create a new auxiliary function named
  9031. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9032. %% control-flow graph.
  9033. The first question is, in what order should we process the basic blocks?
  9034. Recall that to perform liveness analysis on a basic block we need to
  9035. know the live-after set for the last instruction in the block. If a
  9036. basic block has no successors (i.e., contains no jumps to other
  9037. blocks), then it has an empty live-after set and we can immediately
  9038. apply liveness analysis to it. If a basic block has some successors,
  9039. then we need to complete liveness analysis on those blocks
  9040. first. These ordering constraints are the reverse of a
  9041. \emph{topological order}\index{subject}{topological order} on a graph
  9042. representation of the program. In particular, the \emph{control flow
  9043. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9044. of a program has a node for each basic block and an edge for each jump
  9045. from one block to another. It is straightforward to generate a CFG
  9046. from the dictionary of basic blocks. One then transposes the CFG and
  9047. applies the topological sort algorithm.
  9048. %
  9049. %
  9050. \racket{We recommend using the \code{tsort} and \code{transpose}
  9051. functions of the Racket \code{graph} package to accomplish this.}
  9052. %
  9053. \python{We provide implementations of \code{topological\_sort} and
  9054. \code{transpose} in the file \code{graph.py} of the support code.}
  9055. %
  9056. As an aside, a topological ordering is only guaranteed to exist if the
  9057. graph does not contain any cycles. This is the case for the
  9058. control-flow graphs that we generate from \LangIf{} programs.
  9059. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9060. and learn how to handle cycles in the control-flow graph.
  9061. \racket{You need to construct a directed graph to represent the
  9062. control-flow graph. Do not use the \code{directed-graph} of the
  9063. \code{graph} package because that allows at most one edge
  9064. between each pair of vertices, whereas a control-flow graph may have
  9065. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9066. file in the support code implements a graph representation that
  9067. allows multiple edges between a pair of vertices.}
  9068. {\if\edition\racketEd
  9069. The next question is how to analyze jump instructions. Recall that in
  9070. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9071. \code{label->live} that maps each label to the set of live locations
  9072. at the beginning of its block. We use \code{label->live} to determine
  9073. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9074. that we have many basic blocks, \code{label->live} needs to be updated
  9075. as we process the blocks. In particular, after performing liveness
  9076. analysis on a block, we take the live-before set of its first
  9077. instruction and associate that with the block's label in the
  9078. \code{label->live} alist.
  9079. \fi}
  9080. %
  9081. {\if\edition\pythonEd\pythonColor
  9082. %
  9083. The next question is how to analyze jump instructions. The locations
  9084. that are live before a \code{jmp} should be the locations in
  9085. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9086. maintaining a dictionary named \code{live\_before\_block} that maps each
  9087. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9088. block. After performing liveness analysis on each block, we take the
  9089. live-before set of its first instruction and associate that with the
  9090. block's label in the \code{live\_before\_block} dictionary.
  9091. %
  9092. \fi}
  9093. In \LangXIfVar{} we also have the conditional jump
  9094. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9095. this instruction is particularly interesting because during
  9096. compilation, we do not know which way a conditional jump will go. Thus
  9097. we do not know whether to use the live-before set for the block
  9098. associated with the $\itm{label}$ or the live-before set for the
  9099. following instruction. However, there is no harm to the correctness
  9100. of the generated code if we classify more locations as live than the
  9101. ones that are truly live during one particular execution of the
  9102. instruction. Thus, we can take the union of the live-before sets from
  9103. the following instruction and from the mapping for $\itm{label}$ in
  9104. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9105. The auxiliary functions for computing the variables in an
  9106. instruction's argument and for computing the variables read-from ($R$)
  9107. or written-to ($W$) by an instruction need to be updated to handle the
  9108. new kinds of arguments and instructions in \LangXIfVar{}.
  9109. \begin{exercise}\normalfont\normalsize
  9110. {\if\edition\racketEd
  9111. %
  9112. Update the \code{uncover\_live} pass to apply liveness analysis to
  9113. every basic block in the program.
  9114. %
  9115. Add the following entry to the list of \code{passes} in the
  9116. \code{run-tests.rkt} script:
  9117. \begin{lstlisting}
  9118. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9119. \end{lstlisting}
  9120. \fi}
  9121. {\if\edition\pythonEd\pythonColor
  9122. %
  9123. Update the \code{uncover\_live} function to perform liveness analysis,
  9124. in reverse topological order, on all the basic blocks in the
  9125. program.
  9126. %
  9127. \fi}
  9128. % Check that the live-after sets that you generate for
  9129. % example X matches the following... -Jeremy
  9130. \end{exercise}
  9131. \subsection{Build the Interference Graph}
  9132. \label{sec:build-interference-Lif}
  9133. Many of the new instructions in \LangXIfVar{} can be handled in the
  9134. same way as the instructions in \LangXVar{}.
  9135. % Thus, if your code was
  9136. % already quite general, it will not need to be changed to handle the
  9137. % new instructions. If your code is not general enough, we recommend that
  9138. % you change your code to be more general. For example, you can factor
  9139. % out the computing of the the read and write sets for each kind of
  9140. % instruction into auxiliary functions.
  9141. %
  9142. Some instructions, such as the \key{movzbq} instruction, require special care,
  9143. similar to the \key{movq} instruction. Refer to rule number 1 in
  9144. section~\ref{sec:build-interference}.
  9145. \begin{exercise}\normalfont\normalsize
  9146. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9147. {\if\edition\racketEd
  9148. Add the following entries to the list of \code{passes} in the
  9149. \code{run-tests.rkt} script:
  9150. \begin{lstlisting}
  9151. (list "build_interference" build_interference interp-pseudo-x86-1)
  9152. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9153. \end{lstlisting}
  9154. \fi}
  9155. % Check that the interference graph that you generate for
  9156. % example X matches the following graph G... -Jeremy
  9157. \end{exercise}
  9158. \section{Patch Instructions}
  9159. The new instructions \key{cmpq} and \key{movzbq} have some special
  9160. restrictions that need to be handled in the \code{patch\_instructions}
  9161. pass.
  9162. %
  9163. The second argument of the \key{cmpq} instruction must not be an
  9164. immediate value (such as an integer). So, if you are comparing two
  9165. immediates, we recommend inserting a \key{movq} instruction to put the
  9166. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9167. one memory reference.
  9168. %
  9169. The second argument of the \key{movzbq} must be a register.
  9170. \begin{exercise}\normalfont\normalsize
  9171. %
  9172. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9173. %
  9174. {\if\edition\racketEd
  9175. Add the following entry to the list of \code{passes} in
  9176. \code{run-tests.rkt}, and then run this script to test your compiler.
  9177. \begin{lstlisting}
  9178. (list "patch_instructions" patch_instructions interp-x86-1)
  9179. \end{lstlisting}
  9180. \fi}
  9181. \end{exercise}
  9182. {\if\edition\pythonEd\pythonColor
  9183. \section{Prelude and Conclusion}
  9184. \label{sec:prelude-conclusion-cond}
  9185. The generation of the \code{main} function with its prelude and
  9186. conclusion must change to accommodate how the program now consists of
  9187. one or more basic blocks. After the prelude in \code{main}, jump to
  9188. the \code{start} block. Place the conclusion in a basic block labeled
  9189. with \code{conclusion}.
  9190. \fi}
  9191. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9192. \LangIf{} translated to x86, showing the results of
  9193. \code{explicate\_control}, \code{select\_instructions}, and the final
  9194. x86 assembly.
  9195. \begin{figure}[tbp]
  9196. \begin{tcolorbox}[colback=white]
  9197. {\if\edition\racketEd
  9198. \begin{tabular}{lll}
  9199. \begin{minipage}{0.4\textwidth}
  9200. % cond_test_20.rkt, eq_input.py
  9201. \begin{lstlisting}
  9202. (if (eq? (read) 1) 42 0)
  9203. \end{lstlisting}
  9204. $\Downarrow$
  9205. \begin{lstlisting}
  9206. start:
  9207. tmp7951 = (read);
  9208. if (eq? tmp7951 1)
  9209. goto block7952;
  9210. else
  9211. goto block7953;
  9212. block7952:
  9213. return 42;
  9214. block7953:
  9215. return 0;
  9216. \end{lstlisting}
  9217. $\Downarrow$
  9218. \begin{lstlisting}
  9219. start:
  9220. callq read_int
  9221. movq %rax, tmp7951
  9222. cmpq $1, tmp7951
  9223. je block7952
  9224. jmp block7953
  9225. block7953:
  9226. movq $0, %rax
  9227. jmp conclusion
  9228. block7952:
  9229. movq $42, %rax
  9230. jmp conclusion
  9231. \end{lstlisting}
  9232. \end{minipage}
  9233. &
  9234. $\Rightarrow\qquad$
  9235. \begin{minipage}{0.4\textwidth}
  9236. \begin{lstlisting}
  9237. start:
  9238. callq read_int
  9239. movq %rax, %rcx
  9240. cmpq $1, %rcx
  9241. je block7952
  9242. jmp block7953
  9243. block7953:
  9244. movq $0, %rax
  9245. jmp conclusion
  9246. block7952:
  9247. movq $42, %rax
  9248. jmp conclusion
  9249. .globl main
  9250. main:
  9251. pushq %rbp
  9252. movq %rsp, %rbp
  9253. pushq %r13
  9254. pushq %r12
  9255. pushq %rbx
  9256. pushq %r14
  9257. subq $0, %rsp
  9258. jmp start
  9259. conclusion:
  9260. addq $0, %rsp
  9261. popq %r14
  9262. popq %rbx
  9263. popq %r12
  9264. popq %r13
  9265. popq %rbp
  9266. retq
  9267. \end{lstlisting}
  9268. \end{minipage}
  9269. \end{tabular}
  9270. \fi}
  9271. {\if\edition\pythonEd\pythonColor
  9272. \begin{tabular}{lll}
  9273. \begin{minipage}{0.4\textwidth}
  9274. % cond_test_20.rkt, eq_input.py
  9275. \begin{lstlisting}
  9276. print(42 if input_int() == 1 else 0)
  9277. \end{lstlisting}
  9278. $\Downarrow$
  9279. \begin{lstlisting}
  9280. start:
  9281. tmp_0 = input_int()
  9282. if tmp_0 == 1:
  9283. goto block_3
  9284. else:
  9285. goto block_4
  9286. block_3:
  9287. tmp_1 = 42
  9288. goto block_2
  9289. block_4:
  9290. tmp_1 = 0
  9291. goto block_2
  9292. block_2:
  9293. print(tmp_1)
  9294. return 0
  9295. \end{lstlisting}
  9296. $\Downarrow$
  9297. \begin{lstlisting}
  9298. start:
  9299. callq read_int
  9300. movq %rax, tmp_0
  9301. cmpq 1, tmp_0
  9302. je block_3
  9303. jmp block_4
  9304. block_3:
  9305. movq 42, tmp_1
  9306. jmp block_2
  9307. block_4:
  9308. movq 0, tmp_1
  9309. jmp block_2
  9310. block_2:
  9311. movq tmp_1, %rdi
  9312. callq print_int
  9313. movq 0, %rax
  9314. jmp conclusion
  9315. \end{lstlisting}
  9316. \end{minipage}
  9317. &
  9318. $\Rightarrow\qquad$
  9319. \begin{minipage}{0.4\textwidth}
  9320. \begin{lstlisting}
  9321. .globl main
  9322. main:
  9323. pushq %rbp
  9324. movq %rsp, %rbp
  9325. subq $0, %rsp
  9326. jmp start
  9327. start:
  9328. callq read_int
  9329. movq %rax, %rcx
  9330. cmpq $1, %rcx
  9331. je block_3
  9332. jmp block_4
  9333. block_3:
  9334. movq $42, %rcx
  9335. jmp block_2
  9336. block_4:
  9337. movq $0, %rcx
  9338. jmp block_2
  9339. block_2:
  9340. movq %rcx, %rdi
  9341. callq print_int
  9342. movq $0, %rax
  9343. jmp conclusion
  9344. conclusion:
  9345. addq $0, %rsp
  9346. popq %rbp
  9347. retq
  9348. \end{lstlisting}
  9349. \end{minipage}
  9350. \end{tabular}
  9351. \fi}
  9352. \end{tcolorbox}
  9353. \caption{Example compilation of an \key{if} expression to x86, showing
  9354. the results of \code{explicate\_control},
  9355. \code{select\_instructions}, and the final x86 assembly code. }
  9356. \label{fig:if-example-x86}
  9357. \end{figure}
  9358. \begin{figure}[tbp]
  9359. \begin{tcolorbox}[colback=white]
  9360. {\if\edition\racketEd
  9361. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9362. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9363. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9364. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9365. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9366. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9367. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9368. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9369. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9370. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9371. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9372. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9373. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9374. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9375. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9376. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  9377. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9378. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9379. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9380. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9381. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9382. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9383. \end{tikzpicture}
  9384. \fi}
  9385. {\if\edition\pythonEd\pythonColor
  9386. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9387. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9388. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9389. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9390. \node (C-1) at (0,0) {\large \LangCIf{}};
  9391. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9392. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9393. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9394. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9395. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9396. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9397. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  9398. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9399. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9400. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9401. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9402. \end{tikzpicture}
  9403. \fi}
  9404. \end{tcolorbox}
  9405. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9406. \label{fig:Lif-passes}
  9407. \end{figure}
  9408. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9409. compilation of \LangIf{}.
  9410. \section{Challenge: Optimize Blocks and Remove Jumps}
  9411. \label{sec:opt-jumps}
  9412. We discuss two optional challenges that involve optimizing the
  9413. control-flow of the program.
  9414. \subsection{Optimize Blocks}
  9415. The algorithm for \code{explicate\_control} that we discussed in
  9416. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9417. blocks. It creates a basic block whenever a continuation \emph{might}
  9418. get used more than once (e.g., whenever the \code{cont} parameter is
  9419. passed into two or more recursive calls). However, some continuation
  9420. arguments may not be used at all. For example, consider the case for
  9421. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9422. \code{els} continuation.
  9423. %
  9424. {\if\edition\racketEd
  9425. The following example program falls into this
  9426. case, and it creates two unused blocks.
  9427. \begin{center}
  9428. \begin{tabular}{lll}
  9429. \begin{minipage}{0.4\textwidth}
  9430. % cond_test_82.rkt
  9431. \begin{lstlisting}
  9432. (let ([y (if #t
  9433. (read)
  9434. (if (eq? (read) 0)
  9435. 777
  9436. (let ([x (read)])
  9437. (+ 1 x))))])
  9438. (+ y 2))
  9439. \end{lstlisting}
  9440. \end{minipage}
  9441. &
  9442. $\Rightarrow$
  9443. &
  9444. \begin{minipage}{0.55\textwidth}
  9445. \begin{lstlisting}
  9446. start:
  9447. y = (read);
  9448. goto block_5;
  9449. block_5:
  9450. return (+ y 2);
  9451. block_6:
  9452. y = 777;
  9453. goto block_5;
  9454. block_7:
  9455. x = (read);
  9456. y = (+ 1 x2);
  9457. goto block_5;
  9458. \end{lstlisting}
  9459. \end{minipage}
  9460. \end{tabular}
  9461. \end{center}
  9462. \fi}
  9463. The question is, how can we decide whether to create a basic block?
  9464. \emph{Lazy evaluation}\index{subject}{lazy
  9465. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9466. delaying the creation of a basic block until the point in time at which
  9467. we know that it will be used.
  9468. %
  9469. {\if\edition\racketEd
  9470. %
  9471. Racket provides support for
  9472. lazy evaluation with the
  9473. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9474. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9475. \index{subject}{delay} creates a
  9476. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9477. expressions is postponed. When \key{(force}
  9478. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9479. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9480. result of $e_n$ is cached in the promise and returned. If \code{force}
  9481. is applied again to the same promise, then the cached result is
  9482. returned. If \code{force} is applied to an argument that is not a
  9483. promise, \code{force} simply returns the argument.
  9484. %
  9485. \fi}
  9486. %
  9487. {\if\edition\pythonEd\pythonColor
  9488. %
  9489. While Python does not provide direct support for lazy evaluation, it
  9490. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9491. by wrapping it inside a function with no parameters. We can
  9492. \emph{force} its evaluation by calling the function. However, in some
  9493. cases of \code{explicate\_pred}, etc., we will return a list of
  9494. statements and in other cases we will return a function that computes
  9495. a list of statements. We use the term \emph{promise} to refer to a
  9496. value that may be delayed. To uniformly deal with
  9497. promises, we define the following \code{force} function that checks
  9498. whether its input is delayed (i.e., whether it is a function) and then
  9499. either 1) calls the function, or 2) returns the input.
  9500. \begin{lstlisting}
  9501. def force(promise):
  9502. if isinstance(promise, types.FunctionType):
  9503. return promise()
  9504. else:
  9505. return promise
  9506. \end{lstlisting}
  9507. %
  9508. \fi}
  9509. We use promises for the input and output of the functions
  9510. \code{explicate\_pred}, \code{explicate\_assign},
  9511. %
  9512. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9513. %
  9514. So, instead of taking and returning \racket{$\Tail$
  9515. expressions}\python{lists of statements}, they take and return
  9516. promises. Furthermore, when we come to a situation in which a
  9517. continuation might be used more than once, as in the case for
  9518. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9519. that creates a basic block for each continuation (if there is not
  9520. already one) and then returns a \code{goto} statement to that basic
  9521. block. When we come to a situation in which we have a promise but need an
  9522. actual piece of code, for example, to create a larger piece of code with a
  9523. constructor such as \code{Seq}, then insert a call to \code{force}.
  9524. %
  9525. {\if\edition\racketEd
  9526. %
  9527. Also, we must modify the \code{create\_block} function to begin with
  9528. \code{delay} to create a promise. When forced, this promise forces the
  9529. original promise. If that returns a \code{Goto} (because the block was
  9530. already added to \code{basic-blocks}), then we return the
  9531. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9532. return a \code{Goto} to the new label.
  9533. \begin{center}
  9534. \begin{minipage}{\textwidth}
  9535. \begin{lstlisting}
  9536. (define (create_block tail)
  9537. (delay
  9538. (define t (force tail))
  9539. (match t
  9540. [(Goto label) (Goto label)]
  9541. [else
  9542. (let ([label (gensym 'block)])
  9543. (set! basic-blocks (cons (cons label t) basic-blocks))
  9544. (Goto label))])))
  9545. \end{lstlisting}
  9546. \end{minipage}
  9547. \end{center}
  9548. \fi}
  9549. {\if\edition\pythonEd\pythonColor
  9550. %
  9551. Here is the new version of the \code{create\_block} auxiliary function
  9552. that works on promises and that checks whether the block consists of a
  9553. solitary \code{goto} statement.\\
  9554. \begin{minipage}{\textwidth}
  9555. \begin{lstlisting}
  9556. def create_block(promise, basic_blocks):
  9557. stmts = force(promise)
  9558. match stmts:
  9559. case [Goto(l)]:
  9560. return Goto(l)
  9561. case _:
  9562. label = label_name(generate_name('block'))
  9563. basic_blocks[label] = stmts
  9564. return Goto(label)
  9565. \end{lstlisting}
  9566. \end{minipage}
  9567. \fi}
  9568. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9569. improved \code{explicate\_control} on this example. As you can
  9570. see, the number of basic blocks has been reduced from four blocks (see
  9571. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9572. \begin{figure}[tbp]
  9573. \begin{tcolorbox}[colback=white]
  9574. {\if\edition\racketEd
  9575. \begin{tabular}{lll}
  9576. \begin{minipage}{0.4\textwidth}
  9577. % cond_test_82.rkt
  9578. \begin{lstlisting}
  9579. (let ([y (if #t
  9580. (read)
  9581. (if (eq? (read) 0)
  9582. 777
  9583. (let ([x (read)])
  9584. (+ 1 x))))])
  9585. (+ y 2))
  9586. \end{lstlisting}
  9587. \end{minipage}
  9588. &
  9589. $\Rightarrow$
  9590. &
  9591. \begin{minipage}{0.55\textwidth}
  9592. \begin{lstlisting}
  9593. start:
  9594. y = (read);
  9595. goto block_5;
  9596. block_5:
  9597. return (+ y 2);
  9598. \end{lstlisting}
  9599. \end{minipage}
  9600. \end{tabular}
  9601. \fi}
  9602. {\if\edition\pythonEd\pythonColor
  9603. \begin{tabular}{lll}
  9604. \begin{minipage}{0.4\textwidth}
  9605. % cond_test_41.rkt
  9606. \begin{lstlisting}
  9607. x = input_int()
  9608. y = input_int()
  9609. print(y + 2 \
  9610. if (x == 0 \
  9611. if x < 1 \
  9612. else x == 2) \
  9613. else y + 10)
  9614. \end{lstlisting}
  9615. \end{minipage}
  9616. &
  9617. $\Rightarrow$
  9618. &
  9619. \begin{minipage}{0.55\textwidth}
  9620. \begin{lstlisting}
  9621. start:
  9622. x = input_int()
  9623. y = input_int()
  9624. if x < 1:
  9625. goto block_4
  9626. else:
  9627. goto block_5
  9628. block_4:
  9629. if x == 0:
  9630. goto block_2
  9631. else:
  9632. goto block_3
  9633. block_5:
  9634. if x == 2:
  9635. goto block_2
  9636. else:
  9637. goto block_3
  9638. block_2:
  9639. tmp_0 = y + 2
  9640. goto block_1
  9641. block_3:
  9642. tmp_0 = y + 10
  9643. goto block_1
  9644. block_1:
  9645. print(tmp_0)
  9646. return 0
  9647. \end{lstlisting}
  9648. \end{minipage}
  9649. \end{tabular}
  9650. \fi}
  9651. \end{tcolorbox}
  9652. \caption{Translation from \LangIf{} to \LangCIf{}
  9653. via the improved \code{explicate\_control}.}
  9654. \label{fig:explicate-control-challenge}
  9655. \end{figure}
  9656. %% Recall that in the example output of \code{explicate\_control} in
  9657. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9658. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9659. %% block. The first goal of this challenge assignment is to remove those
  9660. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9661. %% \code{explicate\_control} on the left and shows the result of bypassing
  9662. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9663. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9664. %% \code{block55}. The optimized code on the right of
  9665. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9666. %% \code{then} branch jumping directly to \code{block55}. The story is
  9667. %% similar for the \code{else} branch, as well as for the two branches in
  9668. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9669. %% have been optimized in this way, there are no longer any jumps to
  9670. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9671. %% \begin{figure}[tbp]
  9672. %% \begin{tabular}{lll}
  9673. %% \begin{minipage}{0.4\textwidth}
  9674. %% \begin{lstlisting}
  9675. %% block62:
  9676. %% tmp54 = (read);
  9677. %% if (eq? tmp54 2) then
  9678. %% goto block59;
  9679. %% else
  9680. %% goto block60;
  9681. %% block61:
  9682. %% tmp53 = (read);
  9683. %% if (eq? tmp53 0) then
  9684. %% goto block57;
  9685. %% else
  9686. %% goto block58;
  9687. %% block60:
  9688. %% goto block56;
  9689. %% block59:
  9690. %% goto block55;
  9691. %% block58:
  9692. %% goto block56;
  9693. %% block57:
  9694. %% goto block55;
  9695. %% block56:
  9696. %% return (+ 700 77);
  9697. %% block55:
  9698. %% return (+ 10 32);
  9699. %% start:
  9700. %% tmp52 = (read);
  9701. %% if (eq? tmp52 1) then
  9702. %% goto block61;
  9703. %% else
  9704. %% goto block62;
  9705. %% \end{lstlisting}
  9706. %% \end{minipage}
  9707. %% &
  9708. %% $\Rightarrow$
  9709. %% &
  9710. %% \begin{minipage}{0.55\textwidth}
  9711. %% \begin{lstlisting}
  9712. %% block62:
  9713. %% tmp54 = (read);
  9714. %% if (eq? tmp54 2) then
  9715. %% goto block55;
  9716. %% else
  9717. %% goto block56;
  9718. %% block61:
  9719. %% tmp53 = (read);
  9720. %% if (eq? tmp53 0) then
  9721. %% goto block55;
  9722. %% else
  9723. %% goto block56;
  9724. %% block56:
  9725. %% return (+ 700 77);
  9726. %% block55:
  9727. %% return (+ 10 32);
  9728. %% start:
  9729. %% tmp52 = (read);
  9730. %% if (eq? tmp52 1) then
  9731. %% goto block61;
  9732. %% else
  9733. %% goto block62;
  9734. %% \end{lstlisting}
  9735. %% \end{minipage}
  9736. %% \end{tabular}
  9737. %% \caption{Optimize jumps by removing trivial blocks.}
  9738. %% \label{fig:optimize-jumps}
  9739. %% \end{figure}
  9740. %% The name of this pass is \code{optimize-jumps}. We recommend
  9741. %% implementing this pass in two phases. The first phrase builds a hash
  9742. %% table that maps labels to possibly improved labels. The second phase
  9743. %% changes the target of each \code{goto} to use the improved label. If
  9744. %% the label is for a trivial block, then the hash table should map the
  9745. %% label to the first non-trivial block that can be reached from this
  9746. %% label by jumping through trivial blocks. If the label is for a
  9747. %% non-trivial block, then the hash table should map the label to itself;
  9748. %% we do not want to change jumps to non-trivial blocks.
  9749. %% The first phase can be accomplished by constructing an empty hash
  9750. %% table, call it \code{short-cut}, and then iterating over the control
  9751. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9752. %% then update the hash table, mapping the block's source to the target
  9753. %% of the \code{goto}. Also, the hash table may already have mapped some
  9754. %% labels to the block's source, to you must iterate through the hash
  9755. %% table and update all of those so that they instead map to the target
  9756. %% of the \code{goto}.
  9757. %% For the second phase, we recommend iterating through the $\Tail$ of
  9758. %% each block in the program, updating the target of every \code{goto}
  9759. %% according to the mapping in \code{short-cut}.
  9760. \begin{exercise}\normalfont\normalsize
  9761. Implement the improvements to the \code{explicate\_control} pass.
  9762. Check that it removes trivial blocks in a few example programs. Then
  9763. check that your compiler still passes all your tests.
  9764. \end{exercise}
  9765. \subsection{Remove Jumps}
  9766. There is an opportunity for removing jumps that is apparent in the
  9767. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9768. ends with a jump to \code{block\_5}, and there are no other jumps to
  9769. \code{block\_5} in the rest of the program. In this situation we can
  9770. avoid the runtime overhead of this jump by merging \code{block\_5}
  9771. into the preceding block, which in this case is the \code{start} block.
  9772. Figure~\ref{fig:remove-jumps} shows the output of
  9773. \code{allocate\_registers} on the left and the result of this
  9774. optimization on the right.
  9775. \begin{figure}[tbp]
  9776. \begin{tcolorbox}[colback=white]
  9777. {\if\edition\racketEd
  9778. \begin{tabular}{lll}
  9779. \begin{minipage}{0.5\textwidth}
  9780. % cond_test_82.rkt
  9781. \begin{lstlisting}
  9782. start:
  9783. callq read_int
  9784. movq %rax, %rcx
  9785. jmp block_5
  9786. block_5:
  9787. movq %rcx, %rax
  9788. addq $2, %rax
  9789. jmp conclusion
  9790. \end{lstlisting}
  9791. \end{minipage}
  9792. &
  9793. $\Rightarrow\qquad$
  9794. \begin{minipage}{0.4\textwidth}
  9795. \begin{lstlisting}
  9796. start:
  9797. callq read_int
  9798. movq %rax, %rcx
  9799. movq %rcx, %rax
  9800. addq $2, %rax
  9801. jmp conclusion
  9802. \end{lstlisting}
  9803. \end{minipage}
  9804. \end{tabular}
  9805. \fi}
  9806. {\if\edition\pythonEd\pythonColor
  9807. \begin{tabular}{lll}
  9808. \begin{minipage}{0.5\textwidth}
  9809. % cond_test_20.rkt
  9810. \begin{lstlisting}
  9811. start:
  9812. callq read_int
  9813. movq %rax, tmp_0
  9814. cmpq 1, tmp_0
  9815. je block_3
  9816. jmp block_4
  9817. block_3:
  9818. movq 42, tmp_1
  9819. jmp block_2
  9820. block_4:
  9821. movq 0, tmp_1
  9822. jmp block_2
  9823. block_2:
  9824. movq tmp_1, %rdi
  9825. callq print_int
  9826. movq 0, %rax
  9827. jmp conclusion
  9828. \end{lstlisting}
  9829. \end{minipage}
  9830. &
  9831. $\Rightarrow\qquad$
  9832. \begin{minipage}{0.4\textwidth}
  9833. \begin{lstlisting}
  9834. start:
  9835. callq read_int
  9836. movq %rax, tmp_0
  9837. cmpq 1, tmp_0
  9838. je block_3
  9839. movq 0, tmp_1
  9840. jmp block_2
  9841. block_3:
  9842. movq 42, tmp_1
  9843. jmp block_2
  9844. block_2:
  9845. movq tmp_1, %rdi
  9846. callq print_int
  9847. movq 0, %rax
  9848. jmp conclusion
  9849. \end{lstlisting}
  9850. \end{minipage}
  9851. \end{tabular}
  9852. \fi}
  9853. \end{tcolorbox}
  9854. \caption{Merging basic blocks by removing unnecessary jumps.}
  9855. \label{fig:remove-jumps}
  9856. \end{figure}
  9857. \begin{exercise}\normalfont\normalsize
  9858. %
  9859. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9860. into their preceding basic block, when there is only one preceding
  9861. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9862. %
  9863. {\if\edition\racketEd
  9864. In the \code{run-tests.rkt} script, add the following entry to the
  9865. list of \code{passes} between \code{allocate\_registers}
  9866. and \code{patch\_instructions}:
  9867. \begin{lstlisting}
  9868. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9869. \end{lstlisting}
  9870. \fi}
  9871. %
  9872. Run the script to test your compiler.
  9873. %
  9874. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9875. blocks on several test programs.
  9876. \end{exercise}
  9877. \section{Further Reading}
  9878. \label{sec:cond-further-reading}
  9879. The algorithm for the \code{explicate\_control} pass is based on the
  9880. \code{expose-basic-blocks} pass in the course notes of
  9881. \citet{Dybvig:2010aa}.
  9882. %
  9883. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9884. \citet{Appel:2003fk}, and is related to translations into continuation
  9885. passing
  9886. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9887. %
  9888. The treatment of conditionals in the \code{explicate\_control} pass is
  9889. similar to short-cut boolean
  9890. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9891. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9892. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9893. \chapter{Loops and Dataflow Analysis}
  9894. \label{ch:Lwhile}
  9895. \setcounter{footnote}{0}
  9896. % TODO: define R'_8
  9897. % TODO: multi-graph
  9898. {\if\edition\racketEd
  9899. %
  9900. In this chapter we study two features that are the hallmarks of
  9901. imperative programming languages: loops and assignments to local
  9902. variables. The following example demonstrates these new features by
  9903. computing the sum of the first five positive integers:
  9904. % similar to loop_test_1.rkt
  9905. \begin{lstlisting}
  9906. (let ([sum 0])
  9907. (let ([i 5])
  9908. (begin
  9909. (while (> i 0)
  9910. (begin
  9911. (set! sum (+ sum i))
  9912. (set! i (- i 1))))
  9913. sum)))
  9914. \end{lstlisting}
  9915. The \code{while} loop consists of a condition and a
  9916. body.\footnote{The \code{while} loop is not a built-in
  9917. feature of the Racket language, but Racket includes many looping
  9918. constructs and it is straightforward to define \code{while} as a
  9919. macro.} The body is evaluated repeatedly so long as the condition
  9920. remains true.
  9921. %
  9922. The \code{set!} consists of a variable and a right-hand side
  9923. expression. The \code{set!} updates value of the variable to the
  9924. value of the right-hand side.
  9925. %
  9926. The primary purpose of both the \code{while} loop and \code{set!} is
  9927. to cause side effects, so they do not give a meaningful result
  9928. value. Instead, their result is the \code{\#<void>} value. The
  9929. expression \code{(void)} is an explicit way to create the
  9930. \code{\#<void>} value, and it has type \code{Void}. The
  9931. \code{\#<void>} value can be passed around just like other values
  9932. inside an \LangLoop{} program, and it can be compared for equality with
  9933. another \code{\#<void>} value. However, there are no other operations
  9934. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9935. Racket defines the \code{void?} predicate that returns \code{\#t}
  9936. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9937. %
  9938. \footnote{Racket's \code{Void} type corresponds to what is often
  9939. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9940. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9941. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9942. %
  9943. With the addition of side effect-producing features such as
  9944. \code{while} loop and \code{set!}, it is helpful to include a language
  9945. feature for sequencing side effects: the \code{begin} expression. It
  9946. consists of one or more subexpressions that are evaluated
  9947. left to right.
  9948. %
  9949. \fi}
  9950. {\if\edition\pythonEd\pythonColor
  9951. %
  9952. In this chapter we study loops, one of the hallmarks of imperative
  9953. programming languages. The following example demonstrates the
  9954. \code{while} loop by computing the sum of the first five positive
  9955. integers.
  9956. \begin{lstlisting}
  9957. sum = 0
  9958. i = 5
  9959. while i > 0:
  9960. sum = sum + i
  9961. i = i - 1
  9962. print(sum)
  9963. \end{lstlisting}
  9964. The \code{while} loop consists of a condition expression and a body (a
  9965. sequence of statements). The body is evaluated repeatedly so long as
  9966. the condition remains true.
  9967. %
  9968. \fi}
  9969. \section{The \LangLoop{} Language}
  9970. \newcommand{\LwhileGrammarRacket}{
  9971. \begin{array}{lcl}
  9972. \Type &::=& \key{Void}\\
  9973. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9974. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9975. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9976. \end{array}
  9977. }
  9978. \newcommand{\LwhileASTRacket}{
  9979. \begin{array}{lcl}
  9980. \Type &::=& \key{Void}\\
  9981. \Exp &::=& \SETBANG{\Var}{\Exp}
  9982. \MID \BEGIN{\Exp^{*}}{\Exp}
  9983. \MID \WHILE{\Exp}{\Exp}
  9984. \MID \VOID{}
  9985. \end{array}
  9986. }
  9987. \newcommand{\LwhileGrammarPython}{
  9988. \begin{array}{rcl}
  9989. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9990. \end{array}
  9991. }
  9992. \newcommand{\LwhileASTPython}{
  9993. \begin{array}{lcl}
  9994. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9995. \end{array}
  9996. }
  9997. \begin{figure}[tp]
  9998. \centering
  9999. \begin{tcolorbox}[colback=white]
  10000. \small
  10001. {\if\edition\racketEd
  10002. \[
  10003. \begin{array}{l}
  10004. \gray{\LintGrammarRacket{}} \\ \hline
  10005. \gray{\LvarGrammarRacket{}} \\ \hline
  10006. \gray{\LifGrammarRacket{}} \\ \hline
  10007. \LwhileGrammarRacket \\
  10008. \begin{array}{lcl}
  10009. \LangLoopM{} &::=& \Exp
  10010. \end{array}
  10011. \end{array}
  10012. \]
  10013. \fi}
  10014. {\if\edition\pythonEd\pythonColor
  10015. \[
  10016. \begin{array}{l}
  10017. \gray{\LintGrammarPython} \\ \hline
  10018. \gray{\LvarGrammarPython} \\ \hline
  10019. \gray{\LifGrammarPython} \\ \hline
  10020. \LwhileGrammarPython \\
  10021. \begin{array}{rcl}
  10022. \LangLoopM{} &::=& \Stmt^{*}
  10023. \end{array}
  10024. \end{array}
  10025. \]
  10026. \fi}
  10027. \end{tcolorbox}
  10028. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10029. \label{fig:Lwhile-concrete-syntax}
  10030. \end{figure}
  10031. \begin{figure}[tp]
  10032. \centering
  10033. \begin{tcolorbox}[colback=white]
  10034. \small
  10035. {\if\edition\racketEd
  10036. \[
  10037. \begin{array}{l}
  10038. \gray{\LintOpAST} \\ \hline
  10039. \gray{\LvarASTRacket{}} \\ \hline
  10040. \gray{\LifASTRacket{}} \\ \hline
  10041. \LwhileASTRacket{} \\
  10042. \begin{array}{lcl}
  10043. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10044. \end{array}
  10045. \end{array}
  10046. \]
  10047. \fi}
  10048. {\if\edition\pythonEd\pythonColor
  10049. \[
  10050. \begin{array}{l}
  10051. \gray{\LintASTPython} \\ \hline
  10052. \gray{\LvarASTPython} \\ \hline
  10053. \gray{\LifASTPython} \\ \hline
  10054. \LwhileASTPython \\
  10055. \begin{array}{lcl}
  10056. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10057. \end{array}
  10058. \end{array}
  10059. \]
  10060. \fi}
  10061. \end{tcolorbox}
  10062. \python{
  10063. \index{subject}{While@\texttt{While}}
  10064. }
  10065. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10066. \label{fig:Lwhile-syntax}
  10067. \end{figure}
  10068. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10069. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10070. shows the definition of its abstract syntax.
  10071. %
  10072. The definitional interpreter for \LangLoop{} is shown in
  10073. figure~\ref{fig:interp-Lwhile}.
  10074. %
  10075. {\if\edition\racketEd
  10076. %
  10077. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10078. and \code{Void}, and we make changes to the cases for \code{Var} and
  10079. \code{Let} regarding variables. To support assignment to variables and
  10080. to make their lifetimes indefinite (see the second example in
  10081. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10082. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10083. value.
  10084. %
  10085. Now we discuss the new cases. For \code{SetBang}, we find the
  10086. variable in the environment to obtain a boxed value, and then we change
  10087. it using \code{set-box!} to the result of evaluating the right-hand
  10088. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10089. %
  10090. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10091. if the result is true, (2) evaluate the body.
  10092. The result value of a \code{while} loop is also \code{\#<void>}.
  10093. %
  10094. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10095. subexpressions \itm{es} for their effects and then evaluates
  10096. and returns the result from \itm{body}.
  10097. %
  10098. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10099. %
  10100. \fi}
  10101. {\if\edition\pythonEd\pythonColor
  10102. %
  10103. We add a new case for \code{While} in the \code{interp\_stmts}
  10104. function, where we repeatedly interpret the \code{body} so long as the
  10105. \code{test} expression remains true.
  10106. %
  10107. \fi}
  10108. \begin{figure}[tbp]
  10109. \begin{tcolorbox}[colback=white]
  10110. {\if\edition\racketEd
  10111. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10112. (define interp-Lwhile-class
  10113. (class interp-Lif-class
  10114. (super-new)
  10115. (define/override ((interp-exp env) e)
  10116. (define recur (interp-exp env))
  10117. (match e
  10118. [(Let x e body)
  10119. (define new-env (dict-set env x (box (recur e))))
  10120. ((interp-exp new-env) body)]
  10121. [(Var x) (unbox (dict-ref env x))]
  10122. [(SetBang x rhs)
  10123. (set-box! (dict-ref env x) (recur rhs))]
  10124. [(WhileLoop cnd body)
  10125. (define (loop)
  10126. (cond [(recur cnd) (recur body) (loop)]
  10127. [else (void)]))
  10128. (loop)]
  10129. [(Begin es body)
  10130. (for ([e es]) (recur e))
  10131. (recur body)]
  10132. [(Void) (void)]
  10133. [else ((super interp-exp env) e)]))
  10134. ))
  10135. (define (interp-Lwhile p)
  10136. (send (new interp-Lwhile-class) interp-program p))
  10137. \end{lstlisting}
  10138. \fi}
  10139. {\if\edition\pythonEd\pythonColor
  10140. \begin{lstlisting}
  10141. class InterpLwhile(InterpLif):
  10142. def interp_stmts(self, ss, env):
  10143. if len(ss) == 0:
  10144. return
  10145. match ss[0]:
  10146. case While(test, body, []):
  10147. while self.interp_exp(test, env):
  10148. self.interp_stmts(body, env)
  10149. return self.interp_stmts(ss[1:], env)
  10150. case _:
  10151. return super().interp_stmts(ss, env)
  10152. \end{lstlisting}
  10153. \fi}
  10154. \end{tcolorbox}
  10155. \caption{Interpreter for \LangLoop{}.}
  10156. \label{fig:interp-Lwhile}
  10157. \end{figure}
  10158. The definition of the type checker for \LangLoop{} is shown in
  10159. figure~\ref{fig:type-check-Lwhile}.
  10160. %
  10161. {\if\edition\racketEd
  10162. %
  10163. The type checking of the \code{SetBang} expression requires the type
  10164. of the variable and the right-hand side to agree. The result type is
  10165. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10166. and the result type is \code{Void}. For \code{Begin}, the result type
  10167. is the type of its last subexpression.
  10168. %
  10169. \fi}
  10170. %
  10171. {\if\edition\pythonEd\pythonColor
  10172. %
  10173. A \code{while} loop is well typed if the type of the \code{test}
  10174. expression is \code{bool} and the statements in the \code{body} are
  10175. well typed.
  10176. %
  10177. \fi}
  10178. \begin{figure}[tbp]
  10179. \begin{tcolorbox}[colback=white]
  10180. {\if\edition\racketEd
  10181. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10182. (define type-check-Lwhile-class
  10183. (class type-check-Lif-class
  10184. (super-new)
  10185. (inherit check-type-equal?)
  10186. (define/override (type-check-exp env)
  10187. (lambda (e)
  10188. (define recur (type-check-exp env))
  10189. (match e
  10190. [(SetBang x rhs)
  10191. (define-values (rhs^ rhsT) (recur rhs))
  10192. (define varT (dict-ref env x))
  10193. (check-type-equal? rhsT varT e)
  10194. (values (SetBang x rhs^) 'Void)]
  10195. [(WhileLoop cnd body)
  10196. (define-values (cnd^ Tc) (recur cnd))
  10197. (check-type-equal? Tc 'Boolean e)
  10198. (define-values (body^ Tbody) ((type-check-exp env) body))
  10199. (values (WhileLoop cnd^ body^) 'Void)]
  10200. [(Begin es body)
  10201. (define-values (es^ ts)
  10202. (for/lists (l1 l2) ([e es]) (recur e)))
  10203. (define-values (body^ Tbody) (recur body))
  10204. (values (Begin es^ body^) Tbody)]
  10205. [else ((super type-check-exp env) e)])))
  10206. ))
  10207. (define (type-check-Lwhile p)
  10208. (send (new type-check-Lwhile-class) type-check-program p))
  10209. \end{lstlisting}
  10210. \fi}
  10211. {\if\edition\pythonEd\pythonColor
  10212. \begin{lstlisting}
  10213. class TypeCheckLwhile(TypeCheckLif):
  10214. def type_check_stmts(self, ss, env):
  10215. if len(ss) == 0:
  10216. return
  10217. match ss[0]:
  10218. case While(test, body, []):
  10219. test_t = self.type_check_exp(test, env)
  10220. check_type_equal(bool, test_t, test)
  10221. body_t = self.type_check_stmts(body, env)
  10222. return self.type_check_stmts(ss[1:], env)
  10223. case _:
  10224. return super().type_check_stmts(ss, env)
  10225. \end{lstlisting}
  10226. \fi}
  10227. \end{tcolorbox}
  10228. \caption{Type checker for the \LangLoop{} language.}
  10229. \label{fig:type-check-Lwhile}
  10230. \end{figure}
  10231. {\if\edition\racketEd
  10232. %
  10233. At first glance, the translation of these language features to x86
  10234. seems straightforward because the \LangCIf{} intermediate language
  10235. already supports all the ingredients that we need: assignment,
  10236. \code{goto}, conditional branching, and sequencing. However, there are
  10237. complications that arise, which we discuss in the next section. After
  10238. that we introduce the changes necessary to the existing passes.
  10239. %
  10240. \fi}
  10241. {\if\edition\pythonEd\pythonColor
  10242. %
  10243. At first glance, the translation of \code{while} loops to x86 seems
  10244. straightforward because the \LangCIf{} intermediate language already
  10245. supports \code{goto} and conditional branching. However, there are
  10246. complications that arise which we discuss in the next section. After
  10247. that we introduce the changes necessary to the existing passes.
  10248. %
  10249. \fi}
  10250. \section{Cyclic Control Flow and Dataflow Analysis}
  10251. \label{sec:dataflow-analysis}
  10252. Up until this point, the programs generated in
  10253. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10254. \code{while} loop introduces a cycle. Does that matter?
  10255. %
  10256. Indeed, it does. Recall that for register allocation, the compiler
  10257. performs liveness analysis to determine which variables can share the
  10258. same register. To accomplish this, we analyzed the control-flow graph
  10259. in reverse topological order
  10260. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10261. well defined only for acyclic graphs.
  10262. Let us return to the example of computing the sum of the first five
  10263. positive integers. Here is the program after instruction selection but
  10264. before register allocation.
  10265. \begin{center}
  10266. {\if\edition\racketEd
  10267. \begin{minipage}{0.45\textwidth}
  10268. \begin{lstlisting}
  10269. (define (main) : Integer
  10270. mainstart:
  10271. movq $0, sum
  10272. movq $5, i
  10273. jmp block5
  10274. block5:
  10275. movq i, tmp3
  10276. cmpq tmp3, $0
  10277. jl block7
  10278. jmp block8
  10279. \end{lstlisting}
  10280. \end{minipage}
  10281. \begin{minipage}{0.45\textwidth}
  10282. \begin{lstlisting}
  10283. block7:
  10284. addq i, sum
  10285. movq $1, tmp4
  10286. negq tmp4
  10287. addq tmp4, i
  10288. jmp block5
  10289. block8:
  10290. movq $27, %rax
  10291. addq sum, %rax
  10292. jmp mainconclusion
  10293. )
  10294. \end{lstlisting}
  10295. \end{minipage}
  10296. \fi}
  10297. {\if\edition\pythonEd\pythonColor
  10298. \begin{minipage}{0.45\textwidth}
  10299. \begin{lstlisting}
  10300. mainstart:
  10301. movq $0, sum
  10302. movq $5, i
  10303. jmp block5
  10304. block5:
  10305. cmpq $0, i
  10306. jg block7
  10307. jmp block8
  10308. \end{lstlisting}
  10309. \end{minipage}
  10310. \begin{minipage}{0.45\textwidth}
  10311. \begin{lstlisting}
  10312. block7:
  10313. addq i, sum
  10314. subq $1, i
  10315. jmp block5
  10316. block8:
  10317. movq sum, %rdi
  10318. callq print_int
  10319. movq $0, %rax
  10320. jmp mainconclusion
  10321. \end{lstlisting}
  10322. \end{minipage}
  10323. \fi}
  10324. \end{center}
  10325. Recall that liveness analysis works backward, starting at the end
  10326. of each function. For this example we could start with \code{block8}
  10327. because we know what is live at the beginning of the conclusion:
  10328. only \code{rax} and \code{rsp}. So the live-before set
  10329. for \code{block8} is \code{\{rsp,sum\}}.
  10330. %
  10331. Next we might try to analyze \code{block5} or \code{block7}, but
  10332. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10333. we are stuck.
  10334. The way out of this impasse is to realize that we can compute an
  10335. underapproximation of each live-before set by starting with empty
  10336. live-after sets. By \emph{underapproximation}, we mean that the set
  10337. contains only variables that are live for some execution of the
  10338. program, but the set may be missing some variables that are live.
  10339. Next, the underapproximations for each block can be improved by (1)
  10340. updating the live-after set for each block using the approximate
  10341. live-before sets from the other blocks, and (2) performing liveness
  10342. analysis again on each block. In fact, by iterating this process, the
  10343. underapproximations eventually become the correct solutions!
  10344. %
  10345. This approach of iteratively analyzing a control-flow graph is
  10346. applicable to many static analysis problems and goes by the name
  10347. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10348. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10349. Washington.
  10350. Let us apply this approach to the previously presented example. We use
  10351. the empty set for the initial live-before set for each block. Let
  10352. $m_0$ be the following mapping from label names to sets of locations
  10353. (variables and registers):
  10354. \begin{center}
  10355. \begin{lstlisting}
  10356. mainstart: {}, block5: {}, block7: {}, block8: {}
  10357. \end{lstlisting}
  10358. \end{center}
  10359. Using the above live-before approximations, we determine the
  10360. live-after for each block and then apply liveness analysis to each
  10361. block. This produces our next approximation $m_1$ of the live-before
  10362. sets.
  10363. \begin{center}
  10364. \begin{lstlisting}
  10365. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10366. \end{lstlisting}
  10367. \end{center}
  10368. For the second round, the live-after for \code{mainstart} is the
  10369. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10370. the liveness analysis for \code{mainstart} computes the empty set. The
  10371. live-after for \code{block5} is the union of the live-before sets for
  10372. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  10373. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  10374. sum\}}. The live-after for \code{block7} is the live-before for
  10375. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10376. So the liveness analysis for \code{block7} remains \code{\{i,
  10377. sum\}}. Together these yield the following approximation $m_2$ of
  10378. the live-before sets:
  10379. \begin{center}
  10380. \begin{lstlisting}
  10381. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10382. \end{lstlisting}
  10383. \end{center}
  10384. In the preceding iteration, only \code{block5} changed, so we can
  10385. limit our attention to \code{mainstart} and \code{block7}, the two
  10386. blocks that jump to \code{block5}. As a result, the live-before sets
  10387. for \code{mainstart} and \code{block7} are updated to include
  10388. \code{rsp}, yielding the following approximation $m_3$:
  10389. \begin{center}
  10390. \begin{lstlisting}
  10391. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10392. \end{lstlisting}
  10393. \end{center}
  10394. Because \code{block7} changed, we analyze \code{block5} once more, but
  10395. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10396. our approximations have converged, so $m_3$ is the solution.
  10397. This iteration process is guaranteed to converge to a solution by the
  10398. Kleene fixed-point theorem, a general theorem about functions on
  10399. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10400. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10401. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10402. join operator
  10403. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10404. ordering}\index{subject}{join}\footnote{Technically speaking, we
  10405. will be working with join semilattices.} When two elements are
  10406. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10407. as much information as $m_i$, so we can think of $m_j$ as a
  10408. better-than-or-equal-to approximation in relation to $m_i$. The
  10409. bottom element $\bot$ represents the complete lack of information,
  10410. that is, the worst approximation. The join operator takes two lattice
  10411. elements and combines their information; that is, it produces the
  10412. least upper bound of the two.\index{subject}{least upper bound}
  10413. A dataflow analysis typically involves two lattices: one lattice to
  10414. represent abstract states and another lattice that aggregates the
  10415. abstract states of all the blocks in the control-flow graph. For
  10416. liveness analysis, an abstract state is a set of locations. We form
  10417. the lattice $L$ by taking its elements to be sets of locations, the
  10418. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10419. set, and the join operator to be set union.
  10420. %
  10421. We form a second lattice $M$ by taking its elements to be mappings
  10422. from the block labels to sets of locations (elements of $L$). We
  10423. order the mappings point-wise, using the ordering of $L$. So, given any
  10424. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10425. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10426. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10427. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10428. We can think of one iteration of liveness analysis applied to the
  10429. whole program as being a function $f$ on the lattice $M$. It takes a
  10430. mapping as input and computes a new mapping.
  10431. \[
  10432. f(m_i) = m_{i+1}
  10433. \]
  10434. Next let us think for a moment about what a final solution $m_s$
  10435. should look like. If we perform liveness analysis using the solution
  10436. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10437. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10438. \[
  10439. f(m_s) = m_s
  10440. \]
  10441. Furthermore, the solution should include only locations that are
  10442. forced to be there by performing liveness analysis on the program, so
  10443. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10444. The Kleene fixed-point theorem states that if a function $f$ is
  10445. monotone (better inputs produce better outputs), then the least fixed
  10446. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10447. chain} obtained by starting at $\bot$ and iterating $f$, as
  10448. follows:\index{subject}{Kleene fixed-point theorem}
  10449. \[
  10450. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10451. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10452. \]
  10453. When a lattice contains only finitely long ascending chains, then
  10454. every Kleene chain tops out at some fixed point after some number of
  10455. iterations of $f$.
  10456. \[
  10457. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10458. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10459. \]
  10460. The liveness analysis is indeed a monotone function and the lattice
  10461. $M$ has finitely long ascending chains because there are only a
  10462. finite number of variables and blocks in the program. Thus we are
  10463. guaranteed that iteratively applying liveness analysis to all blocks
  10464. in the program will eventually produce the least fixed point solution.
  10465. Next let us consider dataflow analysis in general and discuss the
  10466. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10467. %
  10468. The algorithm has four parameters: the control-flow graph \code{G}, a
  10469. function \code{transfer} that applies the analysis to one block, and the
  10470. \code{bottom} and \code{join} operators for the lattice of abstract
  10471. states. The \code{analyze\_dataflow} function is formulated as a
  10472. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10473. function come from the predecessor nodes in the control-flow
  10474. graph. However, liveness analysis is a \emph{backward} dataflow
  10475. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10476. function with the transpose of the control-flow graph.
  10477. The algorithm begins by creating the bottom mapping, represented by a
  10478. hash table. It then pushes all the nodes in the control-flow graph
  10479. onto the work list (a queue). The algorithm repeats the \code{while}
  10480. loop as long as there are items in the work list. In each iteration, a
  10481. node is popped from the work list and processed. The \code{input} for
  10482. the node is computed by taking the join of the abstract states of all
  10483. the predecessor nodes. The \code{transfer} function is then applied to
  10484. obtain the \code{output} abstract state. If the output differs from
  10485. the previous state for this block, the mapping for this block is
  10486. updated and its successor nodes are pushed onto the work list.
  10487. \begin{figure}[tb]
  10488. \begin{tcolorbox}[colback=white]
  10489. {\if\edition\racketEd
  10490. \begin{lstlisting}
  10491. (define (analyze_dataflow G transfer bottom join)
  10492. (define mapping (make-hash))
  10493. (for ([v (in-vertices G)])
  10494. (dict-set! mapping v bottom))
  10495. (define worklist (make-queue))
  10496. (for ([v (in-vertices G)])
  10497. (enqueue! worklist v))
  10498. (define trans-G (transpose G))
  10499. (while (not (queue-empty? worklist))
  10500. (define node (dequeue! worklist))
  10501. (define input (for/fold ([state bottom])
  10502. ([pred (in-neighbors trans-G node)])
  10503. (join state (dict-ref mapping pred))))
  10504. (define output (transfer node input))
  10505. (cond [(not (equal? output (dict-ref mapping node)))
  10506. (dict-set! mapping node output)
  10507. (for ([v (in-neighbors G node)])
  10508. (enqueue! worklist v))]))
  10509. mapping)
  10510. \end{lstlisting}
  10511. \fi}
  10512. {\if\edition\pythonEd\pythonColor
  10513. \begin{lstlisting}
  10514. def analyze_dataflow(G, transfer, bottom, join):
  10515. trans_G = transpose(G)
  10516. mapping = dict((v, bottom) for v in G.vertices())
  10517. worklist = deque(G.vertices)
  10518. while worklist:
  10519. node = worklist.pop()
  10520. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10521. input = reduce(join, inputs, bottom)
  10522. output = transfer(node, input)
  10523. if output != mapping[node]:
  10524. mapping[node] = output
  10525. worklist.extend(G.adjacent(node))
  10526. \end{lstlisting}
  10527. \fi}
  10528. \end{tcolorbox}
  10529. \caption{Generic work list algorithm for dataflow analysis}
  10530. \label{fig:generic-dataflow}
  10531. \end{figure}
  10532. {\if\edition\racketEd
  10533. \section{Mutable Variables and Remove Complex Operands}
  10534. There is a subtle interaction between the
  10535. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10536. and the left-to-right order of evaluation of Racket. Consider the
  10537. following example:
  10538. \begin{lstlisting}
  10539. (let ([x 2])
  10540. (+ x (begin (set! x 40) x)))
  10541. \end{lstlisting}
  10542. The result of this program is \code{42} because the first read from
  10543. \code{x} produces \code{2} and the second produces \code{40}. However,
  10544. if we naively apply the \code{remove\_complex\_operands} pass to this
  10545. example we obtain the following program whose result is \code{80}!
  10546. \begin{lstlisting}
  10547. (let ([x 2])
  10548. (let ([tmp (begin (set! x 40) x)])
  10549. (+ x tmp)))
  10550. \end{lstlisting}
  10551. The problem is that with mutable variables, the ordering between
  10552. reads and writes is important, and the
  10553. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10554. before the first read of \code{x}.
  10555. We recommend solving this problem by giving special treatment to reads
  10556. from mutable variables, that is, variables that occur on the left-hand
  10557. side of a \code{set!}. We mark each read from a mutable variable with
  10558. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10559. that the read operation is effectful in that it can produce different
  10560. results at different points in time. Let's apply this idea to the
  10561. following variation that also involves a variable that is not mutated:
  10562. % loop_test_24.rkt
  10563. \begin{lstlisting}
  10564. (let ([x 2])
  10565. (let ([y 0])
  10566. (+ y (+ x (begin (set! x 40) x)))))
  10567. \end{lstlisting}
  10568. We first analyze this program to discover that variable \code{x}
  10569. is mutable but \code{y} is not. We then transform the program as
  10570. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10571. \begin{lstlisting}
  10572. (let ([x 2])
  10573. (let ([y 0])
  10574. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10575. \end{lstlisting}
  10576. Now that we have a clear distinction between reads from mutable and
  10577. immutable variables, we can apply the \code{remove\_complex\_operands}
  10578. pass, where reads from immutable variables are still classified as
  10579. atomic expressions but reads from mutable variables are classified as
  10580. complex. Thus, \code{remove\_complex\_operands} yields the following
  10581. program:\\
  10582. \begin{minipage}{\textwidth}
  10583. \begin{lstlisting}
  10584. (let ([x 2])
  10585. (let ([y 0])
  10586. (+ y (let ([t1 (get! x)])
  10587. (let ([t2 (begin (set! x 40) (get! x))])
  10588. (+ t1 t2))))))
  10589. \end{lstlisting}
  10590. \end{minipage}
  10591. The temporary variable \code{t1} gets the value of \code{x} before the
  10592. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10593. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10594. do not generate a temporary variable for the occurrence of \code{y}
  10595. because it's an immutable variable. We want to avoid such unnecessary
  10596. extra temporaries because they would needless increase the number of
  10597. variables, making it more likely for some of them to be spilled. The
  10598. result of this program is \code{42}, the same as the result prior to
  10599. \code{remove\_complex\_operands}.
  10600. The approach that we've sketched requires only a small
  10601. modification to \code{remove\_complex\_operands} to handle
  10602. \code{get!}. However, it requires a new pass, called
  10603. \code{uncover-get!}, that we discuss in
  10604. section~\ref{sec:uncover-get-bang}.
  10605. As an aside, this problematic interaction between \code{set!} and the
  10606. pass \code{remove\_complex\_operands} is particular to Racket and not
  10607. its predecessor, the Scheme language. The key difference is that
  10608. Scheme does not specify an order of evaluation for the arguments of an
  10609. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10610. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10611. would be correct results for the example program. Interestingly,
  10612. Racket is implemented on top of the Chez Scheme
  10613. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10614. presented in this section (using extra \code{let} bindings to control
  10615. the order of evaluation) is used in the translation from Racket to
  10616. Scheme~\citep{Flatt:2019tb}.
  10617. \fi} % racket
  10618. Having discussed the complications that arise from adding support for
  10619. assignment and loops, we turn to discussing the individual compilation
  10620. passes.
  10621. {\if\edition\racketEd
  10622. \section{Uncover \texttt{get!}}
  10623. \label{sec:uncover-get-bang}
  10624. The goal of this pass is to mark uses of mutable variables so that
  10625. \code{remove\_complex\_operands} can treat them as complex expressions
  10626. and thereby preserve their ordering relative to the side effects in
  10627. other operands. So, the first step is to collect all the mutable
  10628. variables. We recommend creating an auxiliary function for this,
  10629. named \code{collect-set!}, that recursively traverses expressions,
  10630. returning the set of all variables that occur on the left-hand side of a
  10631. \code{set!}. Here's an excerpt of its implementation.
  10632. \begin{center}
  10633. \begin{minipage}{\textwidth}
  10634. \begin{lstlisting}
  10635. (define (collect-set! e)
  10636. (match e
  10637. [(Var x) (set)]
  10638. [(Int n) (set)]
  10639. [(Let x rhs body)
  10640. (set-union (collect-set! rhs) (collect-set! body))]
  10641. [(SetBang var rhs)
  10642. (set-union (set var) (collect-set! rhs))]
  10643. ...))
  10644. \end{lstlisting}
  10645. \end{minipage}
  10646. \end{center}
  10647. By placing this pass after \code{uniquify}, we need not worry about
  10648. variable shadowing, and our logic for \code{Let} can remain simple, as
  10649. in this excerpt.
  10650. The second step is to mark the occurrences of the mutable variables
  10651. with the new \code{GetBang} AST node (\code{get!} in concrete
  10652. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10653. function, which takes two parameters: the set of mutable variables
  10654. \code{set!-vars} and the expression \code{e} to be processed. The
  10655. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10656. mutable variable or leaves it alone if not.
  10657. \begin{center}
  10658. \begin{minipage}{\textwidth}
  10659. \begin{lstlisting}
  10660. (define ((uncover-get!-exp set!-vars) e)
  10661. (match e
  10662. [(Var x)
  10663. (if (set-member? set!-vars x)
  10664. (GetBang x)
  10665. (Var x))]
  10666. ...))
  10667. \end{lstlisting}
  10668. \end{minipage}
  10669. \end{center}
  10670. To wrap things up, define the \code{uncover-get!} function for
  10671. processing a whole program, using \code{collect-set!} to obtain the
  10672. set of mutable variables and then \code{uncover-get!-exp} to replace
  10673. their occurrences with \code{GetBang}.
  10674. \fi}
  10675. \section{Remove Complex Operands}
  10676. \label{sec:rco-loop}
  10677. {\if\edition\racketEd
  10678. %
  10679. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10680. \code{while} are all complex expressions. The subexpressions of
  10681. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10682. %
  10683. \fi}
  10684. {\if\edition\pythonEd\pythonColor
  10685. %
  10686. The change needed for this pass is to add a case for the \code{while}
  10687. statement. The condition of a \code{while} loop is allowed to be a
  10688. complex expression, just like the condition of the \code{if}
  10689. statement.
  10690. %
  10691. \fi}
  10692. %
  10693. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10694. \LangLoopANF{} of this pass.
  10695. \newcommand{\LwhileMonadASTRacket}{
  10696. \begin{array}{rcl}
  10697. \Atm &::=& \VOID{} \\
  10698. \Exp &::=& \GETBANG{\Var}
  10699. \MID \SETBANG{\Var}{\Exp}
  10700. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10701. &\MID& \WHILE{\Exp}{\Exp}
  10702. \end{array}
  10703. }
  10704. \newcommand{\LwhileMonadASTPython}{
  10705. \begin{array}{rcl}
  10706. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10707. \end{array}
  10708. }
  10709. \begin{figure}[tp]
  10710. \centering
  10711. \begin{tcolorbox}[colback=white]
  10712. \small
  10713. {\if\edition\racketEd
  10714. \[
  10715. \begin{array}{l}
  10716. \gray{\LvarMonadASTRacket} \\ \hline
  10717. \gray{\LifMonadASTRacket} \\ \hline
  10718. \LwhileMonadASTRacket \\
  10719. \begin{array}{rcl}
  10720. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10721. \end{array}
  10722. \end{array}
  10723. \]
  10724. \fi}
  10725. {\if\edition\pythonEd\pythonColor
  10726. \[
  10727. \begin{array}{l}
  10728. \gray{\LvarMonadASTPython} \\ \hline
  10729. \gray{\LifMonadASTPython} \\ \hline
  10730. \LwhileMonadASTPython \\
  10731. \begin{array}{rcl}
  10732. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10733. \end{array}
  10734. \end{array}
  10735. %% \begin{array}{rcl}
  10736. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10737. %% \Exp &::=& \Atm \MID \READ{} \\
  10738. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10739. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10740. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10741. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10742. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10743. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10744. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10745. %% \end{array}
  10746. \]
  10747. \fi}
  10748. \end{tcolorbox}
  10749. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10750. \label{fig:Lwhile-anf-syntax}
  10751. \end{figure}
  10752. {\if\edition\racketEd
  10753. %
  10754. As usual, when a complex expression appears in a grammar position that
  10755. needs to be atomic, such as the argument of a primitive operator, we
  10756. must introduce a temporary variable and bind it to the complex
  10757. expression. This approach applies, unchanged, to handle the new
  10758. language forms. For example, in the following code there are two
  10759. \code{begin} expressions appearing as arguments to the \code{+}
  10760. operator. The output of \code{rco\_exp} is then shown, in which the
  10761. \code{begin} expressions have been bound to temporary
  10762. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10763. allowed to have arbitrary expressions in their right-hand side
  10764. expression, so it is fine to place \code{begin} there.
  10765. %
  10766. \begin{center}
  10767. \begin{tabular}{lcl}
  10768. \begin{minipage}{0.4\textwidth}
  10769. \begin{lstlisting}
  10770. (let ([x2 10])
  10771. (let ([y3 0])
  10772. (+ (+ (begin
  10773. (set! y3 (read))
  10774. (get! x2))
  10775. (begin
  10776. (set! x2 (read))
  10777. (get! y3)))
  10778. (get! x2))))
  10779. \end{lstlisting}
  10780. \end{minipage}
  10781. &
  10782. $\Rightarrow$
  10783. &
  10784. \begin{minipage}{0.4\textwidth}
  10785. \begin{lstlisting}
  10786. (let ([x2 10])
  10787. (let ([y3 0])
  10788. (let ([tmp4 (begin
  10789. (set! y3 (read))
  10790. x2)])
  10791. (let ([tmp5 (begin
  10792. (set! x2 (read))
  10793. y3)])
  10794. (let ([tmp6 (+ tmp4 tmp5)])
  10795. (let ([tmp7 x2])
  10796. (+ tmp6 tmp7)))))))
  10797. \end{lstlisting}
  10798. \end{minipage}
  10799. \end{tabular}
  10800. \end{center}
  10801. \fi}
  10802. \section{Explicate Control \racket{and \LangCLoop{}}}
  10803. \label{sec:explicate-loop}
  10804. \newcommand{\CloopASTRacket}{
  10805. \begin{array}{lcl}
  10806. \Atm &::=& \VOID \\
  10807. \Stmt &::=& \READ{}
  10808. \end{array}
  10809. }
  10810. {\if\edition\racketEd
  10811. Recall that in the \code{explicate\_control} pass we define one helper
  10812. function for each kind of position in the program. For the \LangVar{}
  10813. language of integers and variables, we needed assignment and tail
  10814. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10815. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10816. another kind of position: effect position. Except for the last
  10817. subexpression, the subexpressions inside a \code{begin} are evaluated
  10818. only for their effect. Their result values are discarded. We can
  10819. generate better code by taking this fact into account.
  10820. The output language of \code{explicate\_control} is \LangCLoop{}
  10821. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10822. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10823. and that \code{read} may appear as a statement. The most significant
  10824. difference between the programs generated by \code{explicate\_control}
  10825. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10826. chapter is that the control-flow graphs of the latter may contain
  10827. cycles.
  10828. \begin{figure}[tp]
  10829. \begin{tcolorbox}[colback=white]
  10830. \small
  10831. \[
  10832. \begin{array}{l}
  10833. \gray{\CvarASTRacket} \\ \hline
  10834. \gray{\CifASTRacket} \\ \hline
  10835. \CloopASTRacket \\
  10836. \begin{array}{lcl}
  10837. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10838. \end{array}
  10839. \end{array}
  10840. \]
  10841. \end{tcolorbox}
  10842. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10843. \label{fig:c7-syntax}
  10844. \end{figure}
  10845. The new auxiliary function \code{explicate\_effect} takes an
  10846. expression (in an effect position) and the code for its
  10847. continuation. The function returns a $\Tail$ that includes the
  10848. generated code for the input expression followed by the
  10849. continuation. If the expression is obviously pure, that is, never
  10850. causes side effects, then the expression can be removed, so the result
  10851. is just the continuation.
  10852. %
  10853. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10854. interesting; the generated code is depicted in the following diagram:
  10855. \begin{center}
  10856. \begin{minipage}{0.3\textwidth}
  10857. \xymatrix{
  10858. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10859. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10860. & *+[F]{\txt{\itm{cont}}} \\
  10861. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10862. }
  10863. \end{minipage}
  10864. \end{center}
  10865. We start by creating a fresh label $\itm{loop}$ for the top of the
  10866. loop. Next, recursively process the \itm{body} (in effect position)
  10867. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10868. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10869. \itm{body'} as the \emph{then} branch and the continuation block as the
  10870. \emph{else} branch. The result should be added to the dictionary of
  10871. \code{basic-blocks} with the label \itm{loop}. The result for the
  10872. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10873. The auxiliary functions for tail, assignment, and predicate positions
  10874. need to be updated. The three new language forms, \code{while},
  10875. \code{set!}, and \code{begin}, can appear in assignment and tail
  10876. positions. Only \code{begin} may appear in predicate positions; the
  10877. other two have result type \code{Void}.
  10878. \fi}
  10879. %
  10880. {\if\edition\pythonEd\pythonColor
  10881. %
  10882. The output of this pass is the language \LangCIf{}. No new language
  10883. features are needed in the output because a \code{while} loop can be
  10884. expressed in terms of \code{goto} and \code{if} statements, which are
  10885. already in \LangCIf{}.
  10886. %
  10887. Add a case for the \code{while} statement to the
  10888. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10889. the condition expression.
  10890. %
  10891. \fi}
  10892. {\if\edition\racketEd
  10893. \section{Select Instructions}
  10894. \label{sec:select-instructions-loop}
  10895. Only two small additions are needed in the \code{select\_instructions}
  10896. pass to handle the changes to \LangCLoop{}. First, to handle the
  10897. addition of \VOID{} we simply translate it to \code{0}. Second,
  10898. \code{read} may appear as a stand-alone statement instead of
  10899. appearing only on the right-hand side of an assignment statement. The code
  10900. generation is nearly identical to the one for assignment; just leave
  10901. off the instruction for moving the result into the left-hand side.
  10902. \fi}
  10903. \section{Register Allocation}
  10904. \label{sec:register-allocation-loop}
  10905. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10906. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10907. which complicates the liveness analysis needed for register
  10908. allocation.
  10909. %
  10910. We recommend using the generic \code{analyze\_dataflow} function that
  10911. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10912. perform liveness analysis, replacing the code in
  10913. \code{uncover\_live} that processed the basic blocks in topological
  10914. order (section~\ref{sec:liveness-analysis-Lif}).
  10915. The \code{analyze\_dataflow} function has the following four parameters.
  10916. \begin{enumerate}
  10917. \item The first parameter \code{G} should be passed the transpose
  10918. of the control-flow graph.
  10919. \item The second parameter \code{transfer} should be passed a function
  10920. that applies liveness analysis to a basic block. It takes two
  10921. parameters: the label for the block to analyze and the live-after
  10922. set for that block. The transfer function should return the
  10923. live-before set for the block.
  10924. %
  10925. \racket{Also, as a side effect, it should update the block's
  10926. $\itm{info}$ with the liveness information for each instruction.}
  10927. %
  10928. \python{Also, as a side-effect, it should update the live-before and
  10929. live-after sets for each instruction.}
  10930. %
  10931. To implement the \code{transfer} function, you should be able to
  10932. reuse the code you already have for analyzing basic blocks.
  10933. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10934. \code{bottom} and \code{join} for the lattice of abstract states,
  10935. that is, sets of locations. For liveness analysis, the bottom of the
  10936. lattice is the empty set, and the join operator is set union.
  10937. \end{enumerate}
  10938. \begin{figure}[p]
  10939. \begin{tcolorbox}[colback=white]
  10940. {\if\edition\racketEd
  10941. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10942. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10943. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10944. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10945. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10946. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10947. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10948. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10949. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10950. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10951. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10952. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10953. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10954. \path[->,bend left=15] (Lfun) edge [above] node
  10955. {\ttfamily\footnotesize shrink} (Lfun-2);
  10956. \path[->,bend left=15] (Lfun-2) edge [above] node
  10957. {\ttfamily\footnotesize uniquify} (F1-4);
  10958. \path[->,bend left=15] (F1-4) edge [above] node
  10959. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10960. \path[->,bend left=15] (F1-5) edge [left] node
  10961. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10962. \path[->,bend left=10] (F1-6) edge [above] node
  10963. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10964. \path[->,bend left=15] (C3-2) edge [right] node
  10965. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10966. \path[->,bend right=15] (x86-2) edge [right] node
  10967. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10968. \path[->,bend right=15] (x86-2-1) edge [below] node
  10969. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10970. \path[->,bend right=15] (x86-2-2) edge [right] node
  10971. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10972. \path[->,bend left=15] (x86-3) edge [above] node
  10973. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10974. \path[->,bend left=15] (x86-4) edge [right] node
  10975. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10976. \end{tikzpicture}
  10977. \fi}
  10978. {\if\edition\pythonEd\pythonColor
  10979. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10980. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10981. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10982. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10983. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10984. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10985. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10986. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10987. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10988. \path[->,bend left=15] (Lfun) edge [above] node
  10989. {\ttfamily\footnotesize shrink} (Lfun-2);
  10990. \path[->,bend left=15] (Lfun-2) edge [above] node
  10991. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10992. \path[->,bend left=10] (F1-6) edge [right] node
  10993. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10994. \path[->,bend right=15] (C3-2) edge [right] node
  10995. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10996. \path[->,bend right=15] (x86-2) edge [below] node
  10997. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10998. \path[->,bend left=15] (x86-3) edge [above] node
  10999. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11000. \path[->,bend right=15] (x86-4) edge [below] node
  11001. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11002. \end{tikzpicture}
  11003. \fi}
  11004. \end{tcolorbox}
  11005. \caption{Diagram of the passes for \LangLoop{}.}
  11006. \label{fig:Lwhile-passes}
  11007. \end{figure}
  11008. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11009. for the compilation of \LangLoop{}.
  11010. % Further Reading: dataflow analysis
  11011. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11012. \chapter{Tuples and Garbage Collection}
  11013. \label{ch:Lvec}
  11014. \index{subject}{tuple}
  11015. \index{subject}{vector}
  11016. \index{subject}{allocate}
  11017. \index{subject}{heap allocate}
  11018. \setcounter{footnote}{0}
  11019. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11020. %% all the IR grammars are spelled out! \\ --Jeremy}
  11021. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11022. %% the root stack. \\ --Jeremy}
  11023. In this chapter we study the implementation of tuples\racket{, called
  11024. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11025. in which each element may have a different type.
  11026. %
  11027. This language feature is the first to use the computer's
  11028. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11029. indefinite; that is, a tuple lives forever from the programmer's
  11030. viewpoint. Of course, from an implementer's viewpoint, it is important
  11031. to reclaim the space associated with a tuple when it is no longer
  11032. needed, which is why we also study \emph{garbage collection}
  11033. \index{subject}{garbage collection} techniques in this chapter.
  11034. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11035. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11036. language (chapter~\ref{ch:Lwhile}) with tuples.
  11037. %
  11038. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11039. copying live tuples back and forth between two halves of the heap. The
  11040. garbage collector requires coordination with the compiler so that it
  11041. can find all the live tuples.
  11042. %
  11043. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11044. discuss the necessary changes and additions to the compiler passes,
  11045. including a new compiler pass named \code{expose\_allocation}.
  11046. \section{The \LangVec{} Language}
  11047. \label{sec:r3}
  11048. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11049. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11050. the definition of the abstract syntax.
  11051. %
  11052. \racket{The \LangVec{} language includes the forms: \code{vector} for
  11053. creating a tuple, \code{vector-ref} for reading an element of a
  11054. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11055. \code{vector-length} for obtaining the number of elements of a
  11056. tuple.}
  11057. %
  11058. \python{The \LangVec{} language adds 1) tuple creation via a
  11059. comma-separated list of expressions, 2) accessing an element of a
  11060. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11061. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11062. operator, and 4) obtaining the number of elements (the length) of a
  11063. tuple. In this chapter, we restrict access indices to constant
  11064. integers.}
  11065. %
  11066. The following program shows an example use of tuples. It creates a tuple
  11067. \code{t} containing the elements \code{40},
  11068. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11069. contains just \code{2}. The element at index $1$ of \code{t} is
  11070. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11071. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11072. to which we add \code{2}, the element at index $0$ of the tuple.
  11073. The result of the program is \code{42}.
  11074. %
  11075. {\if\edition\racketEd
  11076. \begin{lstlisting}
  11077. (let ([t (vector 40 #t (vector 2))])
  11078. (if (vector-ref t 1)
  11079. (+ (vector-ref t 0)
  11080. (vector-ref (vector-ref t 2) 0))
  11081. 44))
  11082. \end{lstlisting}
  11083. \fi}
  11084. {\if\edition\pythonEd\pythonColor
  11085. \begin{lstlisting}
  11086. t = 40, True, (2,)
  11087. print( t[0] + t[2][0] if t[1] else 44 )
  11088. \end{lstlisting}
  11089. \fi}
  11090. \newcommand{\LtupGrammarRacket}{
  11091. \begin{array}{lcl}
  11092. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11093. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11094. \MID \LP\key{vector-length}\;\Exp\RP \\
  11095. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11096. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11097. \end{array}
  11098. }
  11099. \newcommand{\LtupASTRacket}{
  11100. \begin{array}{lcl}
  11101. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11102. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11103. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11104. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11105. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11106. \end{array}
  11107. }
  11108. \newcommand{\LtupGrammarPython}{
  11109. \begin{array}{rcl}
  11110. \itm{cmp} &::= & \key{is} \\
  11111. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11112. \end{array}
  11113. }
  11114. \newcommand{\LtupASTPython}{
  11115. \begin{array}{lcl}
  11116. \itm{cmp} &::= & \code{Is()} \\
  11117. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11118. &\MID& \LEN{\Exp}
  11119. \end{array}
  11120. }
  11121. \begin{figure}[tbp]
  11122. \centering
  11123. \begin{tcolorbox}[colback=white]
  11124. \small
  11125. {\if\edition\racketEd
  11126. \[
  11127. \begin{array}{l}
  11128. \gray{\LintGrammarRacket{}} \\ \hline
  11129. \gray{\LvarGrammarRacket{}} \\ \hline
  11130. \gray{\LifGrammarRacket{}} \\ \hline
  11131. \gray{\LwhileGrammarRacket} \\ \hline
  11132. \LtupGrammarRacket \\
  11133. \begin{array}{lcl}
  11134. \LangVecM{} &::=& \Exp
  11135. \end{array}
  11136. \end{array}
  11137. \]
  11138. \fi}
  11139. {\if\edition\pythonEd\pythonColor
  11140. \[
  11141. \begin{array}{l}
  11142. \gray{\LintGrammarPython{}} \\ \hline
  11143. \gray{\LvarGrammarPython{}} \\ \hline
  11144. \gray{\LifGrammarPython{}} \\ \hline
  11145. \gray{\LwhileGrammarPython} \\ \hline
  11146. \LtupGrammarPython \\
  11147. \begin{array}{rcl}
  11148. \LangVecM{} &::=& \Stmt^{*}
  11149. \end{array}
  11150. \end{array}
  11151. \]
  11152. \fi}
  11153. \end{tcolorbox}
  11154. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11155. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11156. \label{fig:Lvec-concrete-syntax}
  11157. \end{figure}
  11158. \begin{figure}[tp]
  11159. \centering
  11160. \begin{tcolorbox}[colback=white]
  11161. \small
  11162. {\if\edition\racketEd
  11163. \[
  11164. \begin{array}{l}
  11165. \gray{\LintOpAST} \\ \hline
  11166. \gray{\LvarASTRacket{}} \\ \hline
  11167. \gray{\LifASTRacket{}} \\ \hline
  11168. \gray{\LwhileASTRacket{}} \\ \hline
  11169. \LtupASTRacket{} \\
  11170. \begin{array}{lcl}
  11171. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11172. \end{array}
  11173. \end{array}
  11174. \]
  11175. \fi}
  11176. {\if\edition\pythonEd\pythonColor
  11177. \[
  11178. \begin{array}{l}
  11179. \gray{\LintASTPython} \\ \hline
  11180. \gray{\LvarASTPython} \\ \hline
  11181. \gray{\LifASTPython} \\ \hline
  11182. \gray{\LwhileASTPython} \\ \hline
  11183. \LtupASTPython \\
  11184. \begin{array}{lcl}
  11185. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11186. \end{array}
  11187. \end{array}
  11188. \]
  11189. \fi}
  11190. \end{tcolorbox}
  11191. \caption{The abstract syntax of \LangVec{}.}
  11192. \label{fig:Lvec-syntax}
  11193. \end{figure}
  11194. Tuples raise several interesting new issues. First, variable binding
  11195. performs a shallow copy in dealing with tuples, which means that
  11196. different variables can refer to the same tuple; that is, two
  11197. variables can be \emph{aliases}\index{subject}{alias} for the same
  11198. entity. Consider the following example, in which \code{t1} and
  11199. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11200. different tuple value with equal elements. The result of the
  11201. program is \code{42}.
  11202. \begin{center}
  11203. \begin{minipage}{0.96\textwidth}
  11204. {\if\edition\racketEd
  11205. \begin{lstlisting}
  11206. (let ([t1 (vector 3 7)])
  11207. (let ([t2 t1])
  11208. (let ([t3 (vector 3 7)])
  11209. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11210. 42
  11211. 0))))
  11212. \end{lstlisting}
  11213. \fi}
  11214. {\if\edition\pythonEd\pythonColor
  11215. \begin{lstlisting}
  11216. t1 = 3, 7
  11217. t2 = t1
  11218. t3 = 3, 7
  11219. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11220. \end{lstlisting}
  11221. \fi}
  11222. \end{minipage}
  11223. \end{center}
  11224. {\if\edition\racketEd
  11225. Whether two variables are aliased or not affects what happens
  11226. when the underlying tuple is mutated\index{subject}{mutation}.
  11227. Consider the following example in which \code{t1} and \code{t2}
  11228. again refer to the same tuple value.
  11229. \begin{center}
  11230. \begin{minipage}{0.96\textwidth}
  11231. \begin{lstlisting}
  11232. (let ([t1 (vector 3 7)])
  11233. (let ([t2 t1])
  11234. (let ([_ (vector-set! t2 0 42)])
  11235. (vector-ref t1 0))))
  11236. \end{lstlisting}
  11237. \end{minipage}
  11238. \end{center}
  11239. The mutation through \code{t2} is visible in referencing the tuple
  11240. from \code{t1}, so the result of this program is \code{42}.
  11241. \fi}
  11242. The next issue concerns the lifetime of tuples. When does a tuple's
  11243. lifetime end? Notice that \LangVec{} does not include an operation
  11244. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11245. to any notion of static scoping.
  11246. %
  11247. {\if\edition\racketEd
  11248. %
  11249. For example, the following program returns \code{42} even though the
  11250. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11251. that reads from the vector to which it was bound.
  11252. \begin{center}
  11253. \begin{minipage}{0.96\textwidth}
  11254. \begin{lstlisting}
  11255. (let ([v (vector (vector 44))])
  11256. (let ([x (let ([w (vector 42)])
  11257. (let ([_ (vector-set! v 0 w)])
  11258. 0))])
  11259. (+ x (vector-ref (vector-ref v 0) 0))))
  11260. \end{lstlisting}
  11261. \end{minipage}
  11262. \end{center}
  11263. \fi}
  11264. %
  11265. {\if\edition\pythonEd\pythonColor
  11266. %
  11267. For example, the following program returns \code{42} even though the
  11268. variable \code{x} goes out of scope when the function returns, prior
  11269. to reading the tuple element at index zero. (We study the compilation
  11270. of functions in chapter~\ref{ch:Lfun}.)
  11271. %
  11272. \begin{center}
  11273. \begin{minipage}{0.96\textwidth}
  11274. \begin{lstlisting}
  11275. def f():
  11276. x = 42, 43
  11277. return x
  11278. t = f()
  11279. print( t[0] )
  11280. \end{lstlisting}
  11281. \end{minipage}
  11282. \end{center}
  11283. \fi}
  11284. %
  11285. From the perspective of programmer-observable behavior, tuples live
  11286. forever. However, if they really lived forever then many long-running
  11287. programs would run out of memory. To solve this problem, the
  11288. language's runtime system performs automatic garbage collection.
  11289. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11290. \LangVec{} language.
  11291. %
  11292. \racket{We define the \code{vector}, \code{vector-ref},
  11293. \code{vector-set!}, and \code{vector-length} operations for
  11294. \LangVec{} in terms of the corresponding operations in Racket. One
  11295. subtle point is that the \code{vector-set!} operation returns the
  11296. \code{\#<void>} value.}
  11297. %
  11298. \python{We represent tuples with Python lists in the interpreter
  11299. because we need to write to them
  11300. (section~\ref{sec:expose-allocation}). (Python tuples are
  11301. immutable.) We define element access, the \code{is} operator, and
  11302. the \code{len} operator for \LangVec{} in terms of the corresponding
  11303. operations in Python.}
  11304. \begin{figure}[tbp]
  11305. \begin{tcolorbox}[colback=white]
  11306. {\if\edition\racketEd
  11307. \begin{lstlisting}
  11308. (define interp-Lvec-class
  11309. (class interp-Lwhile-class
  11310. (super-new)
  11311. (define/override (interp-op op)
  11312. (match op
  11313. ['eq? (lambda (v1 v2)
  11314. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11315. (and (boolean? v1) (boolean? v2))
  11316. (and (vector? v1) (vector? v2))
  11317. (and (void? v1) (void? v2)))
  11318. (eq? v1 v2)]))]
  11319. ['vector vector]
  11320. ['vector-length vector-length]
  11321. ['vector-ref vector-ref]
  11322. ['vector-set! vector-set!]
  11323. [else (super interp-op op)]
  11324. ))
  11325. (define/override ((interp-exp env) e)
  11326. (match e
  11327. [(HasType e t) ((interp-exp env) e)]
  11328. [else ((super interp-exp env) e)]
  11329. ))
  11330. ))
  11331. (define (interp-Lvec p)
  11332. (send (new interp-Lvec-class) interp-program p))
  11333. \end{lstlisting}
  11334. \fi}
  11335. %
  11336. {\if\edition\pythonEd\pythonColor
  11337. \begin{lstlisting}
  11338. class InterpLtup(InterpLwhile):
  11339. def interp_cmp(self, cmp):
  11340. match cmp:
  11341. case Is():
  11342. return lambda x, y: x is y
  11343. case _:
  11344. return super().interp_cmp(cmp)
  11345. def interp_exp(self, e, env):
  11346. match e:
  11347. case Tuple(es, Load()):
  11348. return tuple([self.interp_exp(e, env) for e in es])
  11349. case Subscript(tup, index, Load()):
  11350. t = self.interp_exp(tup, env)
  11351. n = self.interp_exp(index, env)
  11352. return t[n]
  11353. case _:
  11354. return super().interp_exp(e, env)
  11355. \end{lstlisting}
  11356. \fi}
  11357. \end{tcolorbox}
  11358. \caption{Interpreter for the \LangVec{} language.}
  11359. \label{fig:interp-Lvec}
  11360. \end{figure}
  11361. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11362. \LangVec{}.
  11363. %
  11364. The type of a tuple is a
  11365. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11366. type for each of its elements.
  11367. %
  11368. \racket{To create the s-expression for the \code{Vector} type, we use the
  11369. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11370. operator} \code{,@} to insert the list \code{t*} without its usual
  11371. start and end parentheses. \index{subject}{unquote-splicing}}
  11372. %
  11373. The type of accessing the ith element of a tuple is the ith element
  11374. type of the tuple's type, if there is one. If not, an error is
  11375. signaled. Note that the index \code{i} is required to be a constant
  11376. integer (and not, for example, a call to
  11377. \racket{\code{read}}\python{input\_int}) so that the type checker
  11378. can determine the element's type given the tuple type.
  11379. %
  11380. \racket{
  11381. Regarding writing an element to a tuple, the element's type must
  11382. be equal to the ith element type of the tuple's type.
  11383. The result type is \code{Void}.}
  11384. %% When allocating a tuple,
  11385. %% we need to know which elements of the tuple are themselves tuples for
  11386. %% the purposes of garbage collection. We can obtain this information
  11387. %% during type checking. The type checker shown in
  11388. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11389. %% expression; it also
  11390. %% %
  11391. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11392. %% where $T$ is the tuple's type.
  11393. %
  11394. %records the type of each tuple expression in a new field named \code{has\_type}.
  11395. \begin{figure}[tp]
  11396. \begin{tcolorbox}[colback=white]
  11397. {\if\edition\racketEd
  11398. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11399. (define type-check-Lvec-class
  11400. (class type-check-Lif-class
  11401. (super-new)
  11402. (inherit check-type-equal?)
  11403. (define/override (type-check-exp env)
  11404. (lambda (e)
  11405. (define recur (type-check-exp env))
  11406. (match e
  11407. [(Prim 'vector es)
  11408. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11409. (define t `(Vector ,@t*))
  11410. (values (Prim 'vector e*) t)]
  11411. [(Prim 'vector-ref (list e1 (Int i)))
  11412. (define-values (e1^ t) (recur e1))
  11413. (match t
  11414. [`(Vector ,ts ...)
  11415. (unless (and (0 . <= . i) (i . < . (length ts)))
  11416. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11417. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11418. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11419. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11420. (define-values (e-vec t-vec) (recur e1))
  11421. (define-values (e-elt^ t-elt) (recur elt))
  11422. (match t-vec
  11423. [`(Vector ,ts ...)
  11424. (unless (and (0 . <= . i) (i . < . (length ts)))
  11425. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11426. (check-type-equal? (list-ref ts i) t-elt e)
  11427. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11428. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11429. [(Prim 'vector-length (list e))
  11430. (define-values (e^ t) (recur e))
  11431. (match t
  11432. [`(Vector ,ts ...)
  11433. (values (Prim 'vector-length (list e^)) 'Integer)]
  11434. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11435. [(Prim 'eq? (list arg1 arg2))
  11436. (define-values (e1 t1) (recur arg1))
  11437. (define-values (e2 t2) (recur arg2))
  11438. (match* (t1 t2)
  11439. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11440. [(other wise) (check-type-equal? t1 t2 e)])
  11441. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11442. [else ((super type-check-exp env) e)]
  11443. )))
  11444. ))
  11445. (define (type-check-Lvec p)
  11446. (send (new type-check-Lvec-class) type-check-program p))
  11447. \end{lstlisting}
  11448. \fi}
  11449. {\if\edition\pythonEd\pythonColor
  11450. \begin{lstlisting}
  11451. class TypeCheckLtup(TypeCheckLwhile):
  11452. def type_check_exp(self, e, env):
  11453. match e:
  11454. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11455. l = self.type_check_exp(left, env)
  11456. r = self.type_check_exp(right, env)
  11457. check_type_equal(l, r, e)
  11458. return bool
  11459. case Tuple(es, Load()):
  11460. ts = [self.type_check_exp(e, env) for e in es]
  11461. e.has_type = TupleType(ts)
  11462. return e.has_type
  11463. case Subscript(tup, Constant(i), Load()):
  11464. tup_ty = self.type_check_exp(tup, env)
  11465. i_ty = self.type_check_exp(Constant(i), env)
  11466. check_type_equal(i_ty, int, i)
  11467. match tup_ty:
  11468. case TupleType(ts):
  11469. return ts[i]
  11470. case _:
  11471. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11472. case _:
  11473. return super().type_check_exp(e, env)
  11474. \end{lstlisting}
  11475. \fi}
  11476. \end{tcolorbox}
  11477. \caption{Type checker for the \LangVec{} language.}
  11478. \label{fig:type-check-Lvec}
  11479. \end{figure}
  11480. \section{Garbage Collection}
  11481. \label{sec:GC}
  11482. Garbage collection is a runtime technique for reclaiming space on the
  11483. heap that will not be used in the future of the running program. We
  11484. use the term \emph{object}\index{subject}{object} to refer to any
  11485. value that is stored in the heap, which for now includes only
  11486. tuples.%
  11487. %
  11488. \footnote{The term \emph{object} as it is used in the context of
  11489. object-oriented programming has a more specific meaning than the
  11490. way in which we use the term here.}
  11491. %
  11492. Unfortunately, it is impossible to know precisely which objects will
  11493. be accessed in the future and which will not. Instead, garbage
  11494. collectors overapproximate the set of objects that will be accessed by
  11495. identifying which objects can possibly be accessed. The running
  11496. program can directly access objects that are in registers and on the
  11497. procedure call stack. It can also transitively access the elements of
  11498. tuples, starting with a tuple whose address is in a register or on the
  11499. procedure call stack. We define the \emph{root
  11500. set}\index{subject}{root set} to be all the tuple addresses that are
  11501. in registers or on the procedure call stack. We define the \emph{live
  11502. objects}\index{subject}{live objects} to be the objects that are
  11503. reachable from the root set. Garbage collectors reclaim the space that
  11504. is allocated to objects that are no longer live. That means that some
  11505. objects may not get reclaimed as soon as they could be, but at least
  11506. garbage collectors do not reclaim the space dedicated to objects that
  11507. will be accessed in the future! The programmer can influence which
  11508. objects get reclaimed by causing them to become unreachable.
  11509. So the goal of the garbage collector is twofold:
  11510. \begin{enumerate}
  11511. \item to preserve all the live objects, and
  11512. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11513. \end{enumerate}
  11514. \subsection{Two-Space Copying Collector}
  11515. Here we study a relatively simple algorithm for garbage collection
  11516. that is the basis of many state-of-the-art garbage
  11517. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11518. particular, we describe a two-space copying
  11519. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11520. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11521. collector} \index{subject}{two-space copying collector}
  11522. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11523. what happens in a two-space collector, showing two time steps, prior
  11524. to garbage collection (on the top) and after garbage collection (on
  11525. the bottom). In a two-space collector, the heap is divided into two
  11526. parts named the FromSpace\index{subject}{FromSpace} and the
  11527. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11528. FromSpace until there is not enough room for the next allocation
  11529. request. At that point, the garbage collector goes to work to make
  11530. room for the next allocation.
  11531. A copying collector makes more room by copying all the live objects
  11532. from the FromSpace into the ToSpace and then performs a sleight of
  11533. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11534. as the new ToSpace. In the example shown in
  11535. figure~\ref{fig:copying-collector}, the root set consists of three
  11536. pointers, one in a register and two on the stack. All the live
  11537. objects have been copied to the ToSpace (the right-hand side of
  11538. figure~\ref{fig:copying-collector}) in a way that preserves the
  11539. pointer relationships. For example, the pointer in the register still
  11540. points to a tuple that in turn points to two other tuples. There are
  11541. four tuples that are not reachable from the root set and therefore do
  11542. not get copied into the ToSpace.
  11543. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11544. created by a well-typed program in \LangVec{} because it contains a
  11545. cycle. However, creating cycles will be possible once we get to
  11546. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11547. to deal with cycles to begin with, so we will not need to revisit this
  11548. issue.
  11549. \begin{figure}[tbp]
  11550. \centering
  11551. \begin{tcolorbox}[colback=white]
  11552. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11553. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11554. \\[5ex]
  11555. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11556. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11557. \end{tcolorbox}
  11558. \caption{A copying collector in action.}
  11559. \label{fig:copying-collector}
  11560. \end{figure}
  11561. \subsection{Graph Copying via Cheney's Algorithm}
  11562. \label{sec:cheney}
  11563. \index{subject}{Cheney's algorithm}
  11564. Let us take a closer look at the copying of the live objects. The
  11565. allocated objects and pointers can be viewed as a graph, and we need to
  11566. copy the part of the graph that is reachable from the root set. To
  11567. make sure that we copy all the reachable vertices in the graph, we need
  11568. an exhaustive graph traversal algorithm, such as depth-first search or
  11569. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  11570. such algorithms take into account the possibility of cycles by marking
  11571. which vertices have already been visited, so to ensure termination
  11572. of the algorithm. These search algorithms also use a data structure
  11573. such as a stack or queue as a to-do list to keep track of the vertices
  11574. that need to be visited. We use breadth-first search and a trick
  11575. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  11576. and copying tuples into the ToSpace.
  11577. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11578. copy progresses. The queue is represented by a chunk of contiguous
  11579. memory at the beginning of the ToSpace, using two pointers to track
  11580. the front and the back of the queue, called the \emph{free pointer}
  11581. and the \emph{scan pointer}, respectively. The algorithm starts by
  11582. copying all tuples that are immediately reachable from the root set
  11583. into the ToSpace to form the initial queue. When we copy a tuple, we
  11584. mark the old tuple to indicate that it has been visited. We discuss
  11585. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11586. that any pointers inside the copied tuples in the queue still point
  11587. back to the FromSpace. Once the initial queue has been created, the
  11588. algorithm enters a loop in which it repeatedly processes the tuple at
  11589. the front of the queue and pops it off the queue. To process a tuple,
  11590. the algorithm copies all the objects that are directly reachable from it
  11591. to the ToSpace, placing them at the back of the queue. The algorithm
  11592. then updates the pointers in the popped tuple so that they point to the
  11593. newly copied objects.
  11594. \begin{figure}[tbp]
  11595. \centering
  11596. \begin{tcolorbox}[colback=white]
  11597. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11598. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11599. \end{tcolorbox}
  11600. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11601. \label{fig:cheney}
  11602. \end{figure}
  11603. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11604. tuple whose second element is $42$ to the back of the queue. The other
  11605. pointer goes to a tuple that has already been copied, so we do not
  11606. need to copy it again, but we do need to update the pointer to the new
  11607. location. This can be accomplished by storing a \emph{forwarding
  11608. pointer}\index{subject}{forwarding pointer} to the new location in the
  11609. old tuple, when we initially copied the tuple into the
  11610. ToSpace. This completes one step of the algorithm. The algorithm
  11611. continues in this way until the queue is empty; that is, when the scan
  11612. pointer catches up with the free pointer.
  11613. \subsection{Data Representation}
  11614. \label{sec:data-rep-gc}
  11615. The garbage collector places some requirements on the data
  11616. representations used by our compiler. First, the garbage collector
  11617. needs to distinguish between pointers and other kinds of data such as
  11618. integers. The following are several ways to accomplish this:
  11619. \begin{enumerate}
  11620. \item Attach a tag to each object that identifies what type of
  11621. object it is~\citep{McCarthy:1960dz}.
  11622. \item Store different types of objects in different
  11623. regions~\citep{Steele:1977ab}.
  11624. \item Use type information from the program to either (a) generate
  11625. type-specific code for collecting, or (b) generate tables that
  11626. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11627. \end{enumerate}
  11628. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11629. need to tag objects in any case, so option 1 is a natural choice for those
  11630. languages. However, \LangVec{} is a statically typed language, so it
  11631. would be unfortunate to require tags on every object, especially small
  11632. and pervasive objects like integers and Booleans. Option 3 is the
  11633. best-performing choice for statically typed languages, but it comes with
  11634. a relatively high implementation complexity. To keep this chapter
  11635. within a reasonable scope of complexity, we recommend a combination of options
  11636. 1 and 2, using separate strategies for the stack and the heap.
  11637. Regarding the stack, we recommend using a separate stack for pointers,
  11638. which we call the \emph{root stack}\index{subject}{root stack}
  11639. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11640. That is, when a local variable needs to be spilled and is of type
  11641. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11642. root stack instead of putting it on the procedure call
  11643. stack. Furthermore, we always spill tuple-typed variables if they are
  11644. live during a call to the collector, thereby ensuring that no pointers
  11645. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11646. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11647. contrasts it with the data layout using a root stack. The root stack
  11648. contains the two pointers from the regular stack and also the pointer
  11649. in the second register.
  11650. \begin{figure}[tbp]
  11651. \centering
  11652. \begin{tcolorbox}[colback=white]
  11653. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11654. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11655. \end{tcolorbox}
  11656. \caption{Maintaining a root stack to facilitate garbage collection.}
  11657. \label{fig:shadow-stack}
  11658. \end{figure}
  11659. The problem of distinguishing between pointers and other kinds of data
  11660. also arises inside each tuple on the heap. We solve this problem by
  11661. attaching a tag, an extra 64 bits, to each
  11662. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11663. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11664. Note that we have drawn the bits in a big-endian way, from right to left,
  11665. with bit location 0 (the least significant bit) on the far right,
  11666. which corresponds to the direction of the x86 shifting instructions
  11667. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11668. is dedicated to specifying which elements of the tuple are pointers,
  11669. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11670. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11671. data. The pointer mask starts at bit location 7. We limit tuples to a
  11672. maximum size of fifty elements, so we need 50 bits for the pointer
  11673. mask.%
  11674. %
  11675. \footnote{A production-quality compiler would handle
  11676. arbitrarily sized tuples and use a more complex approach.}
  11677. %
  11678. The tag also contains two other pieces of information. The length of
  11679. the tuple (number of elements) is stored in bits at locations 1 through
  11680. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11681. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11682. has not yet been copied. If the bit has value 0, then the entire tag
  11683. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11684. zero in any case, because our tuples are 8-byte aligned.)
  11685. \begin{figure}[tbp]
  11686. \centering
  11687. \begin{tcolorbox}[colback=white]
  11688. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11689. \end{tcolorbox}
  11690. \caption{Representation of tuples in the heap.}
  11691. \label{fig:tuple-rep}
  11692. \end{figure}
  11693. \subsection{Implementation of the Garbage Collector}
  11694. \label{sec:organize-gz}
  11695. \index{subject}{prelude}
  11696. An implementation of the copying collector is provided in the
  11697. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11698. interface to the garbage collector that is used by the compiler. The
  11699. \code{initialize} function creates the FromSpace, ToSpace, and root
  11700. stack and should be called in the prelude of the \code{main}
  11701. function. The arguments of \code{initialize} are the root stack size
  11702. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11703. good choice for both. The \code{initialize} function puts the address
  11704. of the beginning of the FromSpace into the global variable
  11705. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11706. the address that is one past the last element of the FromSpace. We use
  11707. half-open intervals to represent chunks of
  11708. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11709. points to the first element of the root stack.
  11710. As long as there is room left in the FromSpace, your generated code
  11711. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11712. %
  11713. The amount of room left in the FromSpace is the difference between the
  11714. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11715. function should be called when there is not enough room left in the
  11716. FromSpace for the next allocation. The \code{collect} function takes
  11717. a pointer to the current top of the root stack (one past the last item
  11718. that was pushed) and the number of bytes that need to be
  11719. allocated. The \code{collect} function performs the copying collection
  11720. and leaves the heap in a state such that there is enough room for the
  11721. next allocation.
  11722. \begin{figure}[tbp]
  11723. \begin{tcolorbox}[colback=white]
  11724. \begin{lstlisting}
  11725. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11726. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11727. int64_t* free_ptr;
  11728. int64_t* fromspace_begin;
  11729. int64_t* fromspace_end;
  11730. int64_t** rootstack_begin;
  11731. \end{lstlisting}
  11732. \end{tcolorbox}
  11733. \caption{The compiler's interface to the garbage collector.}
  11734. \label{fig:gc-header}
  11735. \end{figure}
  11736. %% \begin{exercise}
  11737. %% In the file \code{runtime.c} you will find the implementation of
  11738. %% \code{initialize} and a partial implementation of \code{collect}.
  11739. %% The \code{collect} function calls another function, \code{cheney},
  11740. %% to perform the actual copy, and that function is left to the reader
  11741. %% to implement. The following is the prototype for \code{cheney}.
  11742. %% \begin{lstlisting}
  11743. %% static void cheney(int64_t** rootstack_ptr);
  11744. %% \end{lstlisting}
  11745. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11746. %% rootstack (which is an array of pointers). The \code{cheney} function
  11747. %% also communicates with \code{collect} through the global
  11748. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11749. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11750. %% the ToSpace:
  11751. %% \begin{lstlisting}
  11752. %% static int64_t* tospace_begin;
  11753. %% static int64_t* tospace_end;
  11754. %% \end{lstlisting}
  11755. %% The job of the \code{cheney} function is to copy all the live
  11756. %% objects (reachable from the root stack) into the ToSpace, update
  11757. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11758. %% update the root stack so that it points to the objects in the
  11759. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11760. %% and ToSpace.
  11761. %% \end{exercise}
  11762. The introduction of garbage collection has a nontrivial impact on our
  11763. compiler passes. We introduce a new compiler pass named
  11764. \code{expose\_allocation} that elaborates the code for allocating
  11765. tuples. We also make significant changes to
  11766. \code{select\_instructions}, \code{build\_interference},
  11767. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11768. make minor changes in several more passes.
  11769. The following program serves as our running example. It creates
  11770. two tuples, one nested inside the other. Both tuples have length
  11771. one. The program accesses the element in the inner tuple.
  11772. % tests/vectors_test_17.rkt
  11773. {\if\edition\racketEd
  11774. \begin{lstlisting}
  11775. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11776. \end{lstlisting}
  11777. \fi}
  11778. {\if\edition\pythonEd\pythonColor
  11779. \begin{lstlisting}
  11780. print( ((42,),)[0][0] )
  11781. \end{lstlisting}
  11782. \fi}
  11783. %% {\if\edition\racketEd
  11784. %% \section{Shrink}
  11785. %% \label{sec:shrink-Lvec}
  11786. %% Recall that the \code{shrink} pass translates the primitives operators
  11787. %% into a smaller set of primitives.
  11788. %% %
  11789. %% This pass comes after type checking, and the type checker adds a
  11790. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11791. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11792. %% \fi}
  11793. \section{Expose Allocation}
  11794. \label{sec:expose-allocation}
  11795. The pass \code{expose\_allocation} lowers tuple creation into making a
  11796. conditional call to the collector followed by allocating the
  11797. appropriate amount of memory and initializing it. We choose to place
  11798. the \code{expose\_allocation} pass before
  11799. \code{remove\_complex\_operands} because it generates
  11800. code that contains complex operands.
  11801. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11802. that replaces tuple creation with new lower-level forms that we use in the
  11803. translation of tuple creation.
  11804. %
  11805. {\if\edition\racketEd
  11806. \[
  11807. \begin{array}{lcl}
  11808. \Exp &::=& \cdots
  11809. \MID (\key{collect} \,\itm{int})
  11810. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11811. \MID (\key{global-value} \,\itm{name})
  11812. \end{array}
  11813. \]
  11814. \fi}
  11815. {\if\edition\pythonEd\pythonColor
  11816. \[
  11817. \begin{array}{lcl}
  11818. \Exp &::=& \cdots\\
  11819. &\MID& \key{collect}(\itm{int})
  11820. \MID \key{allocate}(\itm{int},\itm{type})
  11821. \MID \key{global\_value}(\itm{name}) \\
  11822. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11823. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11824. \end{array}
  11825. \]
  11826. \fi}
  11827. %
  11828. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11829. make sure that there are $n$ bytes ready to be allocated. During
  11830. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11831. the \code{collect} function in \code{runtime.c}.
  11832. %
  11833. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11834. space at the front for the 64-bit tag), but the elements are not
  11835. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11836. of the tuple:
  11837. %
  11838. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11839. %
  11840. where $\Type_i$ is the type of the $i$th element.
  11841. %
  11842. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11843. variable, such as \code{free\_ptr}.
  11844. %
  11845. \python{The \code{begin} form is an expression that executes a
  11846. sequence of statements and then produces the value of the expression
  11847. at the end.}
  11848. \racket{
  11849. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11850. can be obtained by running the
  11851. \code{type-check-Lvec-has-type} type checker immediately before the
  11852. \code{expose\_allocation} pass. This version of the type checker
  11853. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11854. around each tuple creation. The concrete syntax
  11855. for \code{HasType} is \code{has-type}.}
  11856. The following shows the transformation of tuple creation into (1) a
  11857. sequence of temporary variable bindings for the initializing
  11858. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11859. \code{allocate}, and (4) the initialization of the tuple. The
  11860. \itm{len} placeholder refers to the length of the tuple, and
  11861. \itm{bytes} is the total number of bytes that need to be allocated for
  11862. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11863. %
  11864. \python{The \itm{type} needed for the second argument of the
  11865. \code{allocate} form can be obtained from the \code{has\_type} field
  11866. of the tuple AST node, which is stored there by running the type
  11867. checker for \LangVec{} immediately before this pass.}
  11868. %
  11869. \begin{center}
  11870. \begin{minipage}{\textwidth}
  11871. {\if\edition\racketEd
  11872. \begin{lstlisting}
  11873. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11874. |$\Longrightarrow$|
  11875. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11876. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11877. (global-value fromspace_end))
  11878. (void)
  11879. (collect |\itm{bytes}|))])
  11880. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11881. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11882. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11883. |$v$|) ... )))) ...)
  11884. \end{lstlisting}
  11885. \fi}
  11886. {\if\edition\pythonEd\pythonColor
  11887. \begin{lstlisting}
  11888. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11889. |$\Longrightarrow$|
  11890. begin:
  11891. |$x_0$| = |$e_0$|
  11892. |$\vdots$|
  11893. |$x_{n-1}$| = |$e_{n-1}$|
  11894. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11895. 0
  11896. else:
  11897. collect(|\itm{bytes}|)
  11898. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11899. |$v$|[0] = |$x_0$|
  11900. |$\vdots$|
  11901. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11902. |$v$|
  11903. \end{lstlisting}
  11904. \fi}
  11905. \end{minipage}
  11906. \end{center}
  11907. %
  11908. \noindent The sequencing of the initializing expressions
  11909. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11910. they may trigger garbage collection and we cannot have an allocated
  11911. but uninitialized tuple on the heap during a collection.
  11912. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11913. \code{expose\_allocation} pass on our running example.
  11914. \begin{figure}[tbp]
  11915. \begin{tcolorbox}[colback=white]
  11916. % tests/s2_17.rkt
  11917. {\if\edition\racketEd
  11918. \begin{lstlisting}
  11919. (vector-ref
  11920. (vector-ref
  11921. (let ([vecinit6
  11922. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11923. (global-value fromspace_end))
  11924. (void)
  11925. (collect 16))])
  11926. (let ([alloc2 (allocate 1 (Vector Integer))])
  11927. (let ([_3 (vector-set! alloc2 0 42)])
  11928. alloc2)))])
  11929. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11930. (global-value fromspace_end))
  11931. (void)
  11932. (collect 16))])
  11933. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11934. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11935. alloc5))))
  11936. 0)
  11937. 0)
  11938. \end{lstlisting}
  11939. \fi}
  11940. {\if\edition\pythonEd\pythonColor
  11941. \begin{lstlisting}
  11942. print( |$T_1$|[0][0] )
  11943. \end{lstlisting}
  11944. where $T_1$ is
  11945. \begin{lstlisting}
  11946. begin:
  11947. tmp.1 = |$T_2$|
  11948. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11949. 0
  11950. else:
  11951. collect(16)
  11952. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11953. tmp.2[0] = tmp.1
  11954. tmp.2
  11955. \end{lstlisting}
  11956. and $T_2$ is
  11957. \begin{lstlisting}
  11958. begin:
  11959. tmp.3 = 42
  11960. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11961. 0
  11962. else:
  11963. collect(16)
  11964. tmp.4 = allocate(1, TupleType([int]))
  11965. tmp.4[0] = tmp.3
  11966. tmp.4
  11967. \end{lstlisting}
  11968. \fi}
  11969. \end{tcolorbox}
  11970. \caption{Output of the \code{expose\_allocation} pass.}
  11971. \label{fig:expose-alloc-output}
  11972. \end{figure}
  11973. \section{Remove Complex Operands}
  11974. \label{sec:remove-complex-opera-Lvec}
  11975. {\if\edition\racketEd
  11976. %
  11977. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11978. should be treated as complex operands.
  11979. %
  11980. \fi}
  11981. %
  11982. {\if\edition\pythonEd\pythonColor
  11983. %
  11984. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11985. and tuple access should be treated as complex operands. The
  11986. sub-expressions of tuple access must be atomic.
  11987. %
  11988. \fi}
  11989. %% A new case for
  11990. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11991. %% handled carefully to prevent the \code{Prim} node from being separated
  11992. %% from its enclosing \code{HasType}.
  11993. Figure~\ref{fig:Lvec-anf-syntax}
  11994. shows the grammar for the output language \LangAllocANF{} of this
  11995. pass, which is \LangAlloc{} in monadic normal form.
  11996. \newcommand{\LtupMonadASTRacket}{
  11997. \begin{array}{rcl}
  11998. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11999. \MID \GLOBALVALUE{\Var}
  12000. \end{array}
  12001. }
  12002. \newcommand{\LtupMonadASTPython}{
  12003. \begin{array}{rcl}
  12004. \Exp &::=& \GET{\Atm}{\Atm} \\
  12005. &\MID& \LEN{\Atm}\\
  12006. &\MID& \ALLOCATE{\Int}{\Type}
  12007. \MID \GLOBALVALUE{\Var} \\
  12008. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12009. &\MID& \COLLECT{\Int}
  12010. \end{array}
  12011. }
  12012. \begin{figure}[tp]
  12013. \centering
  12014. \begin{tcolorbox}[colback=white]
  12015. \small
  12016. {\if\edition\racketEd
  12017. \[
  12018. \begin{array}{l}
  12019. \gray{\LvarMonadASTRacket} \\ \hline
  12020. \gray{\LifMonadASTRacket} \\ \hline
  12021. \gray{\LwhileMonadASTRacket} \\ \hline
  12022. \LtupMonadASTRacket \\
  12023. \begin{array}{rcl}
  12024. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12025. \end{array}
  12026. \end{array}
  12027. \]
  12028. \fi}
  12029. {\if\edition\pythonEd\pythonColor
  12030. \[
  12031. \begin{array}{l}
  12032. \gray{\LvarMonadASTPython} \\ \hline
  12033. \gray{\LifMonadASTPython} \\ \hline
  12034. \gray{\LwhileMonadASTPython} \\ \hline
  12035. \LtupMonadASTPython \\
  12036. \begin{array}{rcl}
  12037. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12038. \end{array}
  12039. \end{array}
  12040. \]
  12041. \fi}
  12042. \end{tcolorbox}
  12043. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12044. \label{fig:Lvec-anf-syntax}
  12045. \end{figure}
  12046. \section{Explicate Control and the \LangCVec{} language}
  12047. \label{sec:explicate-control-r3}
  12048. \newcommand{\CtupASTRacket}{
  12049. \begin{array}{lcl}
  12050. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12051. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12052. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12053. &\MID& \VECLEN{\Atm} \\
  12054. &\MID& \GLOBALVALUE{\Var} \\
  12055. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12056. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12057. \end{array}
  12058. }
  12059. \newcommand{\CtupASTPython}{
  12060. \begin{array}{lcl}
  12061. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12062. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12063. \Stmt &::=& \COLLECT{\Int} \\
  12064. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12065. \end{array}
  12066. }
  12067. \begin{figure}[tp]
  12068. \begin{tcolorbox}[colback=white]
  12069. \small
  12070. {\if\edition\racketEd
  12071. \[
  12072. \begin{array}{l}
  12073. \gray{\CvarASTRacket} \\ \hline
  12074. \gray{\CifASTRacket} \\ \hline
  12075. \gray{\CloopASTRacket} \\ \hline
  12076. \CtupASTRacket \\
  12077. \begin{array}{lcl}
  12078. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12079. \end{array}
  12080. \end{array}
  12081. \]
  12082. \fi}
  12083. {\if\edition\pythonEd\pythonColor
  12084. \[
  12085. \begin{array}{l}
  12086. \gray{\CifASTPython} \\ \hline
  12087. \CtupASTPython \\
  12088. \begin{array}{lcl}
  12089. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12090. \end{array}
  12091. \end{array}
  12092. \]
  12093. \fi}
  12094. \end{tcolorbox}
  12095. \caption{The abstract syntax of \LangCVec{}, extending
  12096. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12097. (figure~\ref{fig:c1-syntax})}.}
  12098. \label{fig:c2-syntax}
  12099. \end{figure}
  12100. The output of \code{explicate\_control} is a program in the
  12101. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12102. shows the definition of the abstract syntax.
  12103. %
  12104. %% \racket{(The concrete syntax is defined in
  12105. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12106. %
  12107. The new expressions of \LangCVec{} include \key{allocate},
  12108. %
  12109. \racket{\key{vector-ref}, and \key{vector-set!},}
  12110. %
  12111. \python{accessing tuple elements,}
  12112. %
  12113. and \key{global\_value}.
  12114. %
  12115. \python{\LangCVec{} also includes the \code{collect} statement and
  12116. assignment to a tuple element.}
  12117. %
  12118. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12119. %
  12120. The \code{explicate\_control} pass can treat these new forms much like
  12121. the other forms that we've already encountered. The output of the
  12122. \code{explicate\_control} pass on the running example is shown on the
  12123. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12124. section.
  12125. \section{Select Instructions and the \LangXGlobal{} Language}
  12126. \label{sec:select-instructions-gc}
  12127. \index{subject}{instruction selection}
  12128. %% void (rep as zero)
  12129. %% allocate
  12130. %% collect (callq collect)
  12131. %% vector-ref
  12132. %% vector-set!
  12133. %% vector-length
  12134. %% global (postpone)
  12135. In this pass we generate x86 code for most of the new operations that
  12136. were needed to compile tuples, including \code{Allocate},
  12137. \code{Collect}, and accessing tuple elements.
  12138. %
  12139. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12140. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12141. \ref{fig:x86-2}). \index{subject}{x86}
  12142. The tuple read and write forms translate into \code{movq}
  12143. instructions. (The $+1$ in the offset serves to move past the tag at the
  12144. beginning of the tuple representation.)
  12145. %
  12146. \begin{center}
  12147. \begin{minipage}{\textwidth}
  12148. {\if\edition\racketEd
  12149. \begin{lstlisting}
  12150. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12151. |$\Longrightarrow$|
  12152. movq |$\itm{tup}'$|, %r11
  12153. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12154. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12155. |$\Longrightarrow$|
  12156. movq |$\itm{tup}'$|, %r11
  12157. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12158. movq $0, |$\itm{lhs'}$|
  12159. \end{lstlisting}
  12160. \fi}
  12161. {\if\edition\pythonEd\pythonColor
  12162. \begin{lstlisting}
  12163. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12164. |$\Longrightarrow$|
  12165. movq |$\itm{tup}'$|, %r11
  12166. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12167. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12168. |$\Longrightarrow$|
  12169. movq |$\itm{tup}'$|, %r11
  12170. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12171. \end{lstlisting}
  12172. \fi}
  12173. \end{minipage}
  12174. \end{center}
  12175. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12176. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12177. are obtained by translating from \LangCVec{} to x86.
  12178. %
  12179. The move of $\itm{tup}'$ to
  12180. register \code{r11} ensures that offset expression
  12181. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12182. removing \code{r11} from consideration by the register allocating.
  12183. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12184. \code{rax}. Then the generated code for tuple assignment would be
  12185. \begin{lstlisting}
  12186. movq |$\itm{tup}'$|, %rax
  12187. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12188. \end{lstlisting}
  12189. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12190. \code{patch\_instructions} would insert a move through \code{rax}
  12191. as follows:
  12192. \begin{lstlisting}
  12193. movq |$\itm{tup}'$|, %rax
  12194. movq |$\itm{rhs}'$|, %rax
  12195. movq %rax, |$8(n+1)$|(%rax)
  12196. \end{lstlisting}
  12197. However, this sequence of instructions does not work, because we're
  12198. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12199. $\itm{rhs}'$) at the same time!
  12200. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12201. be translated into a sequence of instructions that read the tag of the
  12202. tuple and extract the 6 bits that represent the tuple length, which
  12203. are the bits starting at index 1 and going up to and including bit 6.
  12204. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12205. (shift right) can be used to accomplish this.
  12206. We compile the \code{allocate} form to operations on the
  12207. \code{free\_ptr}, as shown next. This approach is called
  12208. \emph{inline allocation} because it implements allocation without a
  12209. function call by simply incrementing the allocation pointer. It is much
  12210. more efficient than calling a function for each allocation. The
  12211. address in the \code{free\_ptr} is the next free address in the
  12212. FromSpace, so we copy it into \code{r11} and then move it forward by
  12213. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12214. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12215. the tag. We then initialize the \itm{tag} and finally copy the
  12216. address in \code{r11} to the left-hand side. Refer to
  12217. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12218. %
  12219. \racket{We recommend using the Racket operations
  12220. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12221. during compilation.}
  12222. %
  12223. \python{We recommend using the bitwise-or operator \code{|} and the
  12224. shift-left operator \code{<<} to compute the tag during
  12225. compilation.}
  12226. %
  12227. The type annotation in the \code{allocate} form is used to determine
  12228. the pointer mask region of the tag.
  12229. %
  12230. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12231. address of the \code{free\_ptr} global variable using a special
  12232. instruction-pointer-relative addressing mode of the x86-64 processor.
  12233. In particular, the assembler computes the distance $d$ between the
  12234. address of \code{free\_ptr} and where the \code{rip} would be at that
  12235. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12236. \code{$d$(\%rip)}, which at runtime will compute the address of
  12237. \code{free\_ptr}.
  12238. %
  12239. {\if\edition\racketEd
  12240. \begin{lstlisting}
  12241. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12242. |$\Longrightarrow$|
  12243. movq free_ptr(%rip), %r11
  12244. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12245. movq $|$\itm{tag}$|, 0(%r11)
  12246. movq %r11, |$\itm{lhs}'$|
  12247. \end{lstlisting}
  12248. \fi}
  12249. {\if\edition\pythonEd\pythonColor
  12250. \begin{lstlisting}
  12251. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12252. |$\Longrightarrow$|
  12253. movq free_ptr(%rip), %r11
  12254. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12255. movq $|$\itm{tag}$|, 0(%r11)
  12256. movq %r11, |$\itm{lhs}'$|
  12257. \end{lstlisting}
  12258. \fi}
  12259. %
  12260. The \code{collect} form is compiled to a call to the \code{collect}
  12261. function in the runtime. The arguments to \code{collect} are (1) the
  12262. top of the root stack, and (2) the number of bytes that need to be
  12263. allocated. We use another dedicated register, \code{r15}, to store
  12264. the pointer to the top of the root stack. Therefore \code{r15} is not
  12265. available for use by the register allocator.
  12266. %
  12267. {\if\edition\racketEd
  12268. \begin{lstlisting}
  12269. (collect |$\itm{bytes}$|)
  12270. |$\Longrightarrow$|
  12271. movq %r15, %rdi
  12272. movq $|\itm{bytes}|, %rsi
  12273. callq collect
  12274. \end{lstlisting}
  12275. \fi}
  12276. {\if\edition\pythonEd\pythonColor
  12277. \begin{lstlisting}
  12278. collect(|$\itm{bytes}$|)
  12279. |$\Longrightarrow$|
  12280. movq %r15, %rdi
  12281. movq $|\itm{bytes}|, %rsi
  12282. callq collect
  12283. \end{lstlisting}
  12284. \fi}
  12285. \newcommand{\GrammarXGlobal}{
  12286. \begin{array}{lcl}
  12287. \Arg &::=& \itm{label} \key{(\%rip)}
  12288. \end{array}
  12289. }
  12290. \newcommand{\ASTXGlobalRacket}{
  12291. \begin{array}{lcl}
  12292. \Arg &::=& \GLOBAL{\itm{label}}
  12293. \end{array}
  12294. }
  12295. \begin{figure}[tp]
  12296. \begin{tcolorbox}[colback=white]
  12297. \[
  12298. \begin{array}{l}
  12299. \gray{\GrammarXInt} \\ \hline
  12300. \gray{\GrammarXIf} \\ \hline
  12301. \GrammarXGlobal \\
  12302. \begin{array}{lcl}
  12303. \LangXGlobalM{} &::= & \key{.globl main} \\
  12304. & & \key{main:} \; \Instr^{*}
  12305. \end{array}
  12306. \end{array}
  12307. \]
  12308. \end{tcolorbox}
  12309. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12310. \label{fig:x86-2-concrete}
  12311. \end{figure}
  12312. \begin{figure}[tp]
  12313. \begin{tcolorbox}[colback=white]
  12314. \small
  12315. \[
  12316. \begin{array}{l}
  12317. \gray{\ASTXIntRacket} \\ \hline
  12318. \gray{\ASTXIfRacket} \\ \hline
  12319. \ASTXGlobalRacket \\
  12320. \begin{array}{lcl}
  12321. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12322. \end{array}
  12323. \end{array}
  12324. \]
  12325. \end{tcolorbox}
  12326. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12327. \label{fig:x86-2}
  12328. \end{figure}
  12329. The definitions of the concrete and abstract syntax of the
  12330. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12331. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12332. of global variables.
  12333. %
  12334. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12335. \code{select\_instructions} pass on the running example.
  12336. \begin{figure}[tbp]
  12337. \centering
  12338. \begin{tcolorbox}[colback=white]
  12339. % tests/s2_17.rkt
  12340. \begin{tabular}{lll}
  12341. \begin{minipage}{0.5\textwidth}
  12342. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12343. start:
  12344. tmp9 = (global-value free_ptr);
  12345. tmp0 = (+ tmp9 16);
  12346. tmp1 = (global-value fromspace_end);
  12347. if (< tmp0 tmp1)
  12348. goto block0;
  12349. else
  12350. goto block1;
  12351. block0:
  12352. _4 = (void);
  12353. goto block9;
  12354. block1:
  12355. (collect 16)
  12356. goto block9;
  12357. block9:
  12358. alloc2 = (allocate 1 (Vector Integer));
  12359. _3 = (vector-set! alloc2 0 42);
  12360. vecinit6 = alloc2;
  12361. tmp2 = (global-value free_ptr);
  12362. tmp3 = (+ tmp2 16);
  12363. tmp4 = (global-value fromspace_end);
  12364. if (< tmp3 tmp4)
  12365. goto block7;
  12366. else
  12367. goto block8;
  12368. block7:
  12369. _8 = (void);
  12370. goto block6;
  12371. block8:
  12372. (collect 16)
  12373. goto block6;
  12374. block6:
  12375. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12376. _7 = (vector-set! alloc5 0 vecinit6);
  12377. tmp5 = (vector-ref alloc5 0);
  12378. return (vector-ref tmp5 0);
  12379. \end{lstlisting}
  12380. \end{minipage}
  12381. &$\Rightarrow$&
  12382. \begin{minipage}{0.4\textwidth}
  12383. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12384. start:
  12385. movq free_ptr(%rip), tmp9
  12386. movq tmp9, tmp0
  12387. addq $16, tmp0
  12388. movq fromspace_end(%rip), tmp1
  12389. cmpq tmp1, tmp0
  12390. jl block0
  12391. jmp block1
  12392. block0:
  12393. movq $0, _4
  12394. jmp block9
  12395. block1:
  12396. movq %r15, %rdi
  12397. movq $16, %rsi
  12398. callq collect
  12399. jmp block9
  12400. block9:
  12401. movq free_ptr(%rip), %r11
  12402. addq $16, free_ptr(%rip)
  12403. movq $3, 0(%r11)
  12404. movq %r11, alloc2
  12405. movq alloc2, %r11
  12406. movq $42, 8(%r11)
  12407. movq $0, _3
  12408. movq alloc2, vecinit6
  12409. movq free_ptr(%rip), tmp2
  12410. movq tmp2, tmp3
  12411. addq $16, tmp3
  12412. movq fromspace_end(%rip), tmp4
  12413. cmpq tmp4, tmp3
  12414. jl block7
  12415. jmp block8
  12416. block7:
  12417. movq $0, _8
  12418. jmp block6
  12419. block8:
  12420. movq %r15, %rdi
  12421. movq $16, %rsi
  12422. callq collect
  12423. jmp block6
  12424. block6:
  12425. movq free_ptr(%rip), %r11
  12426. addq $16, free_ptr(%rip)
  12427. movq $131, 0(%r11)
  12428. movq %r11, alloc5
  12429. movq alloc5, %r11
  12430. movq vecinit6, 8(%r11)
  12431. movq $0, _7
  12432. movq alloc5, %r11
  12433. movq 8(%r11), tmp5
  12434. movq tmp5, %r11
  12435. movq 8(%r11), %rax
  12436. jmp conclusion
  12437. \end{lstlisting}
  12438. \end{minipage}
  12439. \end{tabular}
  12440. \end{tcolorbox}
  12441. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12442. \code{select\_instructions} (\emph{right}) passes on the running
  12443. example.}
  12444. \label{fig:select-instr-output-gc}
  12445. \end{figure}
  12446. \clearpage
  12447. \section{Register Allocation}
  12448. \label{sec:reg-alloc-gc}
  12449. \index{subject}{register allocation}
  12450. As discussed previously in this chapter, the garbage collector needs to
  12451. access all the pointers in the root set, that is, all variables that
  12452. are tuples. It will be the responsibility of the register allocator
  12453. to make sure that
  12454. \begin{enumerate}
  12455. \item the root stack is used for spilling tuple-typed variables, and
  12456. \item if a tuple-typed variable is live during a call to the
  12457. collector, it must be spilled to ensure that it is visible to the
  12458. collector.
  12459. \end{enumerate}
  12460. The latter responsibility can be handled during construction of the
  12461. interference graph, by adding interference edges between the call-live
  12462. tuple-typed variables and all the callee-saved registers. (They
  12463. already interfere with the caller-saved registers.)
  12464. %
  12465. \racket{The type information for variables is in the \code{Program}
  12466. form, so we recommend adding another parameter to the
  12467. \code{build\_interference} function to communicate this alist.}
  12468. %
  12469. \python{The type information for variables is generated by the type
  12470. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12471. the \code{CProgram} AST mode. You'll need to propagate that
  12472. information so that it is available in this pass.}
  12473. The spilling of tuple-typed variables to the root stack can be handled
  12474. after graph coloring, in choosing how to assign the colors
  12475. (integers) to registers and stack locations. The
  12476. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12477. changes to also record the number of spills to the root stack.
  12478. % build-interference
  12479. %
  12480. % callq
  12481. % extra parameter for var->type assoc. list
  12482. % update 'program' and 'if'
  12483. % allocate-registers
  12484. % allocate spilled vectors to the rootstack
  12485. % don't change color-graph
  12486. % TODO:
  12487. %\section{Patch Instructions}
  12488. %[mention that global variables are memory references]
  12489. \section{Prelude and Conclusion}
  12490. \label{sec:print-x86-gc}
  12491. \label{sec:prelude-conclusion-x86-gc}
  12492. \index{subject}{prelude}\index{subject}{conclusion}
  12493. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12494. \code{prelude\_and\_conclusion} pass on the running example. In the
  12495. prelude of the \code{main} function, we allocate space
  12496. on the root stack to make room for the spills of tuple-typed
  12497. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12498. taking care that the root stack grows up instead of down. For the
  12499. running example, there was just one spill, so we increment \code{r15}
  12500. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12501. One issue that deserves special care is that there may be a call to
  12502. \code{collect} prior to the initializing assignments for all the
  12503. variables in the root stack. We do not want the garbage collector to
  12504. mistakenly determine that some uninitialized variable is a pointer that
  12505. needs to be followed. Thus, we zero out all locations on the root
  12506. stack in the prelude of \code{main}. In
  12507. figure~\ref{fig:print-x86-output-gc}, the instruction
  12508. %
  12509. \lstinline{movq $0, 0(%r15)}
  12510. %
  12511. is sufficient to accomplish this task because there is only one spill.
  12512. In general, we have to clear as many words as there are spills of
  12513. tuple-typed variables. The garbage collector tests each root to see
  12514. if it is null prior to dereferencing it.
  12515. \begin{figure}[htbp]
  12516. % TODO: Python Version -Jeremy
  12517. \begin{tcolorbox}[colback=white]
  12518. \begin{minipage}[t]{0.5\textwidth}
  12519. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12520. .globl main
  12521. main:
  12522. pushq %rbp
  12523. movq %rsp, %rbp
  12524. subq $0, %rsp
  12525. movq $65536, %rdi
  12526. movq $65536, %rsi
  12527. callq initialize
  12528. movq rootstack_begin(%rip), %r15
  12529. movq $0, 0(%r15)
  12530. addq $8, %r15
  12531. jmp start
  12532. conclusion:
  12533. subq $8, %r15
  12534. addq $0, %rsp
  12535. popq %rbp
  12536. retq
  12537. \end{lstlisting}
  12538. \end{minipage}
  12539. \end{tcolorbox}
  12540. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12541. \label{fig:print-x86-output-gc}
  12542. \end{figure}
  12543. \begin{figure}[tbp]
  12544. \begin{tcolorbox}[colback=white]
  12545. {\if\edition\racketEd
  12546. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12547. \node (Lvec) at (0,2) {\large \LangVec{}};
  12548. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12549. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12550. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12551. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12552. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12553. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12554. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12555. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12556. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12557. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12558. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12559. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12560. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12561. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12562. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12563. \path[->,bend left=15] (Lvec-4) edge [right] node
  12564. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12565. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12566. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12567. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12568. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12569. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12570. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12571. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12572. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12573. \end{tikzpicture}
  12574. \fi}
  12575. {\if\edition\pythonEd\pythonColor
  12576. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12577. \node (Lvec) at (0,2) {\large \LangVec{}};
  12578. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12579. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12580. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12581. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12582. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12583. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12584. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12585. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12586. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12587. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12588. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12589. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12590. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12591. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12592. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12593. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12594. \end{tikzpicture}
  12595. \fi}
  12596. \end{tcolorbox}
  12597. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12598. \label{fig:Lvec-passes}
  12599. \end{figure}
  12600. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12601. for the compilation of \LangVec{}.
  12602. \clearpage
  12603. {\if\edition\racketEd
  12604. \section{Challenge: Simple Structures}
  12605. \label{sec:simple-structures}
  12606. \index{subject}{struct}
  12607. \index{subject}{structure}
  12608. The language \LangStruct{} extends \LangVec{} with support for simple
  12609. structures. The definition of its concrete syntax is shown in
  12610. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12611. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12612. in Typed Racket is a user-defined data type that contains named fields
  12613. and that is heap allocated, similarly to a vector. The following is an
  12614. example of a structure definition, in this case the definition of a
  12615. \code{point} type:
  12616. \begin{lstlisting}
  12617. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12618. \end{lstlisting}
  12619. \newcommand{\LstructGrammarRacket}{
  12620. \begin{array}{lcl}
  12621. \Type &::=& \Var \\
  12622. \Exp &::=& (\Var\;\Exp \ldots)\\
  12623. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12624. \end{array}
  12625. }
  12626. \newcommand{\LstructASTRacket}{
  12627. \begin{array}{lcl}
  12628. \Type &::=& \VAR{\Var} \\
  12629. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12630. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12631. \end{array}
  12632. }
  12633. \begin{figure}[tbp]
  12634. \centering
  12635. \begin{tcolorbox}[colback=white]
  12636. \[
  12637. \begin{array}{l}
  12638. \gray{\LintGrammarRacket{}} \\ \hline
  12639. \gray{\LvarGrammarRacket{}} \\ \hline
  12640. \gray{\LifGrammarRacket{}} \\ \hline
  12641. \gray{\LwhileGrammarRacket} \\ \hline
  12642. \gray{\LtupGrammarRacket} \\ \hline
  12643. \LstructGrammarRacket \\
  12644. \begin{array}{lcl}
  12645. \LangStruct{} &::=& \Def \ldots \; \Exp
  12646. \end{array}
  12647. \end{array}
  12648. \]
  12649. \end{tcolorbox}
  12650. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12651. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12652. \label{fig:Lstruct-concrete-syntax}
  12653. \end{figure}
  12654. \begin{figure}[tbp]
  12655. \centering
  12656. \begin{tcolorbox}[colback=white]
  12657. \small
  12658. \[
  12659. \begin{array}{l}
  12660. \gray{\LintASTRacket{}} \\ \hline
  12661. \gray{\LvarASTRacket{}} \\ \hline
  12662. \gray{\LifASTRacket{}} \\ \hline
  12663. \gray{\LwhileASTRacket} \\ \hline
  12664. \gray{\LtupASTRacket} \\ \hline
  12665. \LstructASTRacket \\
  12666. \begin{array}{lcl}
  12667. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12668. \end{array}
  12669. \end{array}
  12670. \]
  12671. \end{tcolorbox}
  12672. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12673. (figure~\ref{fig:Lvec-syntax}).}
  12674. \label{fig:Lstruct-syntax}
  12675. \end{figure}
  12676. An instance of a structure is created using function-call syntax, with
  12677. the name of the structure in the function position, as follows:
  12678. \begin{lstlisting}
  12679. (point 7 12)
  12680. \end{lstlisting}
  12681. Function-call syntax is also used to read a field of a structure. The
  12682. function name is formed by the structure name, a dash, and the field
  12683. name. The following example uses \code{point-x} and \code{point-y} to
  12684. access the \code{x} and \code{y} fields of two point instances:
  12685. \begin{center}
  12686. \begin{lstlisting}
  12687. (let ([pt1 (point 7 12)])
  12688. (let ([pt2 (point 4 3)])
  12689. (+ (- (point-x pt1) (point-x pt2))
  12690. (- (point-y pt1) (point-y pt2)))))
  12691. \end{lstlisting}
  12692. \end{center}
  12693. Similarly, to write to a field of a structure, use its set function,
  12694. whose name starts with \code{set-}, followed by the structure name,
  12695. then a dash, then the field name, and finally with an exclamation
  12696. mark. The following example uses \code{set-point-x!} to change the
  12697. \code{x} field from \code{7} to \code{42}:
  12698. \begin{center}
  12699. \begin{lstlisting}
  12700. (let ([pt (point 7 12)])
  12701. (let ([_ (set-point-x! pt 42)])
  12702. (point-x pt)))
  12703. \end{lstlisting}
  12704. \end{center}
  12705. \begin{exercise}\normalfont\normalsize
  12706. Create a type checker for \LangStruct{} by extending the type
  12707. checker for \LangVec{}. Extend your compiler with support for simple
  12708. structures, compiling \LangStruct{} to x86 assembly code. Create
  12709. five new test cases that use structures and, test your compiler.
  12710. \end{exercise}
  12711. % TODO: create an interpreter for L_struct
  12712. \clearpage
  12713. \fi}
  12714. \section{Challenge: Arrays}
  12715. \label{sec:arrays}
  12716. % TODO mention trapped-error
  12717. In this chapter we have studied tuples, that is, heterogeneous
  12718. sequences of elements whose length is determined at compile time. This
  12719. challenge is also about sequences, but this time the length is
  12720. determined at runtime and all the elements have the same type (they
  12721. are homogeneous). We use the term \emph{array} for this latter kind of
  12722. sequence.
  12723. %
  12724. \racket{
  12725. The Racket language does not distinguish between tuples and arrays;
  12726. they are both represented by vectors. However, Typed Racket
  12727. distinguishes between tuples and arrays: the \code{Vector} type is for
  12728. tuples, and the \code{Vectorof} type is for arrays.}
  12729. \python{
  12730. Arrays correspond to the \code{list} type in Python language.
  12731. }
  12732. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12733. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12734. presents the definition of the abstract syntax, extending \LangVec{}
  12735. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12736. %
  12737. \racket{\code{make-vector} primitive operator for creating an array,
  12738. whose arguments are the length of the array and an initial value for
  12739. all the elements in the array.}
  12740. \python{bracket notation for creating an array literal.}
  12741. \racket{
  12742. The \code{vector-length},
  12743. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12744. for tuples become overloaded for use with arrays.}
  12745. \python{
  12746. The subscript operator becomes overloaded for use with arrays and tuples
  12747. and now may appear on the left-hand side of an assignment.
  12748. Note that the index of the subscript, when applied to an array, may be an
  12749. arbitrary expression and not just a constant integer.
  12750. The \code{len} function is also applicable to arrays.
  12751. }
  12752. %
  12753. We include integer multiplication in \LangArray{}, because it is
  12754. useful in many examples involving arrays such as computing the
  12755. inner product of two arrays (figure~\ref{fig:inner_product}).
  12756. \newcommand{\LarrayGrammarRacket}{
  12757. \begin{array}{lcl}
  12758. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12759. \Exp &::=& \CMUL{\Exp}{\Exp}
  12760. \MID \CMAKEVEC{\Exp}{\Exp}
  12761. \end{array}
  12762. }
  12763. \newcommand{\LarrayASTRacket}{
  12764. \begin{array}{lcl}
  12765. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12766. \Exp &::=& \MUL{\Exp}{\Exp}
  12767. \MID \MAKEVEC{\Exp}{\Exp}
  12768. \end{array}
  12769. }
  12770. \newcommand{\LarrayGrammarPython}{
  12771. \begin{array}{lcl}
  12772. \Type &::=& \key{list}\LS\Type\RS \\
  12773. \Exp &::=& \CMUL{\Exp}{\Exp}
  12774. \MID \CGET{\Exp}{\Exp}
  12775. \MID \LS \Exp \code{,} \ldots \RS \\
  12776. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12777. \end{array}
  12778. }
  12779. \newcommand{\LarrayASTPython}{
  12780. \begin{array}{lcl}
  12781. \Type &::=& \key{ListType}\LP\Type\RP \\
  12782. \Exp &::=& \MUL{\Exp}{\Exp}
  12783. \MID \GET{\Exp}{\Exp} \\
  12784. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12785. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12786. \end{array}
  12787. }
  12788. \begin{figure}[tp]
  12789. \centering
  12790. \begin{tcolorbox}[colback=white]
  12791. \small
  12792. {\if\edition\racketEd
  12793. \[
  12794. \begin{array}{l}
  12795. \gray{\LintGrammarRacket{}} \\ \hline
  12796. \gray{\LvarGrammarRacket{}} \\ \hline
  12797. \gray{\LifGrammarRacket{}} \\ \hline
  12798. \gray{\LwhileGrammarRacket} \\ \hline
  12799. \gray{\LtupGrammarRacket} \\ \hline
  12800. \LarrayGrammarRacket \\
  12801. \begin{array}{lcl}
  12802. \LangArray{} &::=& \Exp
  12803. \end{array}
  12804. \end{array}
  12805. \]
  12806. \fi}
  12807. {\if\edition\pythonEd\pythonColor
  12808. \[
  12809. \begin{array}{l}
  12810. \gray{\LintGrammarPython{}} \\ \hline
  12811. \gray{\LvarGrammarPython{}} \\ \hline
  12812. \gray{\LifGrammarPython{}} \\ \hline
  12813. \gray{\LwhileGrammarPython} \\ \hline
  12814. \gray{\LtupGrammarPython} \\ \hline
  12815. \LarrayGrammarPython \\
  12816. \begin{array}{rcl}
  12817. \LangArrayM{} &::=& \Stmt^{*}
  12818. \end{array}
  12819. \end{array}
  12820. \]
  12821. \fi}
  12822. \end{tcolorbox}
  12823. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12824. \label{fig:Lvecof-concrete-syntax}
  12825. \end{figure}
  12826. \begin{figure}[tp]
  12827. \centering
  12828. \begin{tcolorbox}[colback=white]
  12829. \small
  12830. {\if\edition\racketEd
  12831. \[
  12832. \begin{array}{l}
  12833. \gray{\LintASTRacket{}} \\ \hline
  12834. \gray{\LvarASTRacket{}} \\ \hline
  12835. \gray{\LifASTRacket{}} \\ \hline
  12836. \gray{\LwhileASTRacket} \\ \hline
  12837. \gray{\LtupASTRacket} \\ \hline
  12838. \LarrayASTRacket \\
  12839. \begin{array}{lcl}
  12840. \LangArray{} &::=& \Exp
  12841. \end{array}
  12842. \end{array}
  12843. \]
  12844. \fi}
  12845. {\if\edition\pythonEd\pythonColor
  12846. \[
  12847. \begin{array}{l}
  12848. \gray{\LintASTPython{}} \\ \hline
  12849. \gray{\LvarASTPython{}} \\ \hline
  12850. \gray{\LifASTPython{}} \\ \hline
  12851. \gray{\LwhileASTPython} \\ \hline
  12852. \gray{\LtupASTPython} \\ \hline
  12853. \LarrayASTPython \\
  12854. \begin{array}{rcl}
  12855. \LangArrayM{} &::=& \Stmt^{*}
  12856. \end{array}
  12857. \end{array}
  12858. \]
  12859. \fi}
  12860. \end{tcolorbox}
  12861. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12862. \label{fig:Lvecof-syntax}
  12863. \end{figure}
  12864. \begin{figure}[tp]
  12865. \begin{tcolorbox}[colback=white]
  12866. {\if\edition\racketEd
  12867. % TODO: remove the function from the following example, like the python version -Jeremy
  12868. \begin{lstlisting}
  12869. (let ([A (make-vector 2 2)])
  12870. (let ([B (make-vector 2 3)])
  12871. (let ([i 0])
  12872. (let ([prod 0])
  12873. (begin
  12874. (while (< i n)
  12875. (begin
  12876. (set! prod (+ prod (* (vector-ref A i)
  12877. (vector-ref B i))))
  12878. (set! i (+ i 1))))
  12879. prod)))))
  12880. \end{lstlisting}
  12881. \fi}
  12882. {\if\edition\pythonEd\pythonColor
  12883. \begin{lstlisting}
  12884. A = [2, 2]
  12885. B = [3, 3]
  12886. i = 0
  12887. prod = 0
  12888. while i != len(A):
  12889. prod = prod + A[i] * B[i]
  12890. i = i + 1
  12891. print( prod )
  12892. \end{lstlisting}
  12893. \fi}
  12894. \end{tcolorbox}
  12895. \caption{Example program that computes the inner product.}
  12896. \label{fig:inner_product}
  12897. \end{figure}
  12898. {\if\edition\racketEd
  12899. %
  12900. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12901. checker for \LangArray{}. The result type of
  12902. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12903. of the initializing expression. The length expression is required to
  12904. have type \code{Integer}. The type checking of the operators
  12905. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12906. updated to handle the situation in which the vector has type
  12907. \code{Vectorof}. In these cases we translate the operators to their
  12908. \code{vectorof} form so that later passes can easily distinguish
  12909. between operations on tuples versus arrays. We override the
  12910. \code{operator-types} method to provide the type signature for
  12911. multiplication: it takes two integers and returns an integer. \fi}
  12912. {\if\edition\pythonEd\pythonColor
  12913. %
  12914. The type checker for \LangArray{} is defined in
  12915. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12916. is \code{list[T]} where \code{T} is the type of the initializing
  12917. expressions. The type checking of the \code{len} function and the
  12918. subscript operator is updated to handle lists. The type checker now
  12919. also handles a subscript on the left-hand side of an assignment.
  12920. Regarding multiplication, it takes two integers and returns an
  12921. integer.
  12922. %
  12923. \fi}
  12924. \begin{figure}[tbp]
  12925. \begin{tcolorbox}[colback=white]
  12926. {\if\edition\racketEd
  12927. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12928. (define type-check-Lvecof-class
  12929. (class type-check-Lvec-class
  12930. (super-new)
  12931. (inherit check-type-equal?)
  12932. (define/override (operator-types)
  12933. (append '((* . ((Integer Integer) . Integer)))
  12934. (super operator-types)))
  12935. (define/override (type-check-exp env)
  12936. (lambda (e)
  12937. (define recur (type-check-exp env))
  12938. (match e
  12939. [(Prim 'make-vector (list e1 e2))
  12940. (define-values (e1^ t1) (recur e1))
  12941. (define-values (e2^ elt-type) (recur e2))
  12942. (define vec-type `(Vectorof ,elt-type))
  12943. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12944. [(Prim 'vector-ref (list e1 e2))
  12945. (define-values (e1^ t1) (recur e1))
  12946. (define-values (e2^ t2) (recur e2))
  12947. (match* (t1 t2)
  12948. [(`(Vectorof ,elt-type) 'Integer)
  12949. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12950. [(other wise) ((super type-check-exp env) e)])]
  12951. [(Prim 'vector-set! (list e1 e2 e3) )
  12952. (define-values (e-vec t-vec) (recur e1))
  12953. (define-values (e2^ t2) (recur e2))
  12954. (define-values (e-arg^ t-arg) (recur e3))
  12955. (match t-vec
  12956. [`(Vectorof ,elt-type)
  12957. (check-type-equal? elt-type t-arg e)
  12958. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12959. [else ((super type-check-exp env) e)])]
  12960. [(Prim 'vector-length (list e1))
  12961. (define-values (e1^ t1) (recur e1))
  12962. (match t1
  12963. [`(Vectorof ,t)
  12964. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12965. [else ((super type-check-exp env) e)])]
  12966. [else ((super type-check-exp env) e)])))
  12967. ))
  12968. (define (type-check-Lvecof p)
  12969. (send (new type-check-Lvecof-class) type-check-program p))
  12970. \end{lstlisting}
  12971. \fi}
  12972. {\if\edition\pythonEd\pythonColor
  12973. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12974. class TypeCheckLarray(TypeCheckLtup):
  12975. def type_check_exp(self, e, env):
  12976. match e:
  12977. case ast.List(es, Load()):
  12978. ts = [self.type_check_exp(e, env) for e in es]
  12979. elt_ty = ts[0]
  12980. for (ty, elt) in zip(ts, es):
  12981. self.check_type_equal(elt_ty, ty, elt)
  12982. e.has_type = ListType(elt_ty)
  12983. return e.has_type
  12984. case Call(Name('len'), [tup]):
  12985. tup_t = self.type_check_exp(tup, env)
  12986. tup.has_type = tup_t
  12987. match tup_t:
  12988. case TupleType(ts):
  12989. return IntType()
  12990. case ListType(ty):
  12991. return IntType()
  12992. case _:
  12993. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12994. case Subscript(tup, index, Load()):
  12995. tup_ty = self.type_check_exp(tup, env)
  12996. index_ty = self.type_check_exp(index, env)
  12997. self.check_type_equal(index_ty, IntType(), index)
  12998. match tup_ty:
  12999. case TupleType(ts):
  13000. match index:
  13001. case Constant(i):
  13002. return ts[i]
  13003. case _:
  13004. raise Exception('subscript required constant integer index')
  13005. case ListType(ty):
  13006. return ty
  13007. case _:
  13008. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13009. case BinOp(left, Mult(), right):
  13010. l = self.type_check_exp(left, env)
  13011. self.check_type_equal(l, IntType(), left)
  13012. r = self.type_check_exp(right, env)
  13013. self.check_type_equal(r, IntType(), right)
  13014. return IntType()
  13015. case _:
  13016. return super().type_check_exp(e, env)
  13017. def type_check_stmts(self, ss, env):
  13018. if len(ss) == 0:
  13019. return VoidType()
  13020. match ss[0]:
  13021. case Assign([Subscript(tup, index, Store())], value):
  13022. tup_t = self.type_check_exp(tup, env)
  13023. value_t = self.type_check_exp(value, env)
  13024. index_ty = self.type_check_exp(index, env)
  13025. self.check_type_equal(index_ty, IntType(), index)
  13026. match tup_t:
  13027. case ListType(ty):
  13028. self.check_type_equal(ty, value_t, ss[0])
  13029. case TupleType(ts):
  13030. return self.type_check_stmts(ss, env)
  13031. case _:
  13032. raise Exception('type_check_stmts: '
  13033. 'expected tuple or list, not ' + repr(tup_t))
  13034. return self.type_check_stmts(ss[1:], env)
  13035. case _:
  13036. return super().type_check_stmts(ss, env)
  13037. \end{lstlisting}
  13038. \fi}
  13039. \end{tcolorbox}
  13040. \caption{Type checker for the \LangArray{} language.}
  13041. \label{fig:type-check-Lvecof}
  13042. \end{figure}
  13043. The definition of the interpreter for \LangArray{} is shown in
  13044. figure~\ref{fig:interp-Lvecof}.
  13045. \racket{The \code{make-vector} operator is
  13046. interpreted using Racket's \code{make-vector} function,
  13047. and multiplication is interpreted using \code{fx*},
  13048. which is multiplication for \code{fixnum} integers.
  13049. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  13050. we translate array access operations
  13051. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13052. which we interpret using \code{vector} operations with additional
  13053. bounds checks that signal a \code{trapped-error}.
  13054. }
  13055. %
  13056. \python{We implement list creation with a Python list comprehension
  13057. and multiplication is implemented with Python multiplication. We
  13058. add a case to handle a subscript on the left-hand side of
  13059. assignment. Other uses of subscript can be handled by the existing
  13060. code for tuples.}
  13061. \begin{figure}[tbp]
  13062. \begin{tcolorbox}[colback=white]
  13063. {\if\edition\racketEd
  13064. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13065. (define interp-Lvecof-class
  13066. (class interp-Lvec-class
  13067. (super-new)
  13068. (define/override (interp-op op)
  13069. (match op
  13070. ['make-vector make-vector]
  13071. ['vectorof-length vector-length]
  13072. ['vectorof-ref
  13073. (lambda (v i)
  13074. (if (< i (vector-length v))
  13075. (vector-ref v i)
  13076. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13077. ['vectorof-set!
  13078. (lambda (v i e)
  13079. (if (< i (vector-length v))
  13080. (vector-set! v i e)
  13081. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13082. [else (super interp-op op)]))
  13083. ))
  13084. (define (interp-Lvecof p)
  13085. (send (new interp-Lvecof-class) interp-program p))
  13086. \end{lstlisting}
  13087. \fi}
  13088. {\if\edition\pythonEd\pythonColor
  13089. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13090. class InterpLarray(InterpLtup):
  13091. def interp_exp(self, e, env):
  13092. match e:
  13093. case ast.List(es, Load()):
  13094. return [self.interp_exp(e, env) for e in es]
  13095. case BinOp(left, Mult(), right):
  13096. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13097. return l * r
  13098. case _:
  13099. return super().interp_exp(e, env)
  13100. def interp_stmts(self, ss, env):
  13101. if len(ss) == 0:
  13102. return
  13103. match ss[0]:
  13104. case Assign([Subscript(lst, index)], value):
  13105. lst = self.interp_exp(lst, env)
  13106. index = self.interp_exp(index, env)
  13107. lst[index] = self.interp_exp(value, env)
  13108. return self.interp_stmts(ss[1:], env)
  13109. case _:
  13110. return super().interp_stmts(ss, env)
  13111. \end{lstlisting}
  13112. \fi}
  13113. \end{tcolorbox}
  13114. \caption{Interpreter for \LangArray{}.}
  13115. \label{fig:interp-Lvecof}
  13116. \end{figure}
  13117. \subsection{Data Representation}
  13118. \label{sec:array-rep}
  13119. Just as with tuples, we store arrays on the heap, which means that the
  13120. garbage collector will need to inspect arrays. An immediate thought is
  13121. to use the same representation for arrays that we use for tuples.
  13122. However, we limit tuples to a length of fifty so that their length and
  13123. pointer mask can fit into the 64-bit tag at the beginning of each
  13124. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13125. millions of elements, so we need more bits to store the length.
  13126. However, because arrays are homogeneous, we need only 1 bit for the
  13127. pointer mask instead of 1 bit per array element. Finally, the
  13128. garbage collector must be able to distinguish between tuples
  13129. and arrays, so we need to reserve one bit for that purpose. We
  13130. arrive at the following layout for the 64-bit tag at the beginning of
  13131. an array:
  13132. \begin{itemize}
  13133. \item The right-most bit is the forwarding bit, just as in a tuple.
  13134. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13135. that it is not.
  13136. \item The next bit to the left is the pointer mask. A $0$ indicates
  13137. that none of the elements are pointers to the heap, and a $1$
  13138. indicates that all the elements are pointers.
  13139. \item The next $60$ bits store the length of the array.
  13140. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13141. and an array ($1$).
  13142. \item The left-most bit is reserved as explained in
  13143. chapter~\ref{ch:Lgrad}.
  13144. \end{itemize}
  13145. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13146. %% differentiate the kinds of values that have been injected into the
  13147. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13148. %% to indicate that the value is an array.
  13149. In the following subsections we provide hints regarding how to update
  13150. the passes to handle arrays.
  13151. \subsection{Overload Resolution}
  13152. \label{sec:array-resolution}
  13153. As noted previously, with the addition of arrays, several operators
  13154. have become \emph{overloaded}; that is, they can be applied to values
  13155. of more than one type. In this case, the element access and length
  13156. operators can be applied to both tuples and arrays. This kind of
  13157. overloading is quite common in programming languages, so many
  13158. compilers perform \emph{overload resolution}\index{subject}{overload
  13159. resolution} to handle it. The idea is to translate each overloaded
  13160. operator into different operators for the different types.
  13161. Implement a new pass named \code{resolve}.
  13162. Translate the reading of an array element
  13163. into a call to
  13164. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13165. and the writing of an array element to
  13166. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13167. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13168. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13169. When these operators are applied to tuples, leave them as is.
  13170. %
  13171. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13172. field which can be inspected to determine whether the operator
  13173. is applied to a tuple or an array.}
  13174. \subsection{Bounds Checking}
  13175. Recall that the interpreter for \LangArray{} signals a
  13176. \code{trapped-error} when there is an array access that is out of
  13177. bounds. Therefore your compiler is obliged to also catch these errors
  13178. during execution and halt, signaling an error. We recommend inserting
  13179. a new pass named \code{check\_bounds} that inserts code around each
  13180. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13181. \python{subscript} operation to ensure that the index is greater than
  13182. or equal to zero and less than the array's length. If not, the program
  13183. should halt, for which we recommend using a new primitive operation
  13184. named \code{exit}.
  13185. %% \subsection{Reveal Casts}
  13186. %% The array-access operators \code{vectorof-ref} and
  13187. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13188. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13189. %% that the type checker cannot tell whether the index will be in bounds,
  13190. %% so the bounds check must be performed at run time. Recall that the
  13191. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13192. %% an \code{If} around a vector reference for update to check whether
  13193. %% the index is less than the length. You should do the same for
  13194. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13195. %% In addition, the handling of the \code{any-vector} operators in
  13196. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13197. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13198. %% generated code should test whether the tag is for tuples (\code{010})
  13199. %% or arrays (\code{110}) and then dispatch to either
  13200. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13201. %% we add a case in \code{select\_instructions} to generate the
  13202. %% appropriate instructions for accessing the array length from the
  13203. %% header of an array.
  13204. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13205. %% the generated code needs to check that the index is less than the
  13206. %% vector length, so like the code for \code{any-vector-length}, check
  13207. %% the tag to determine whether to use \code{any-vector-length} or
  13208. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13209. %% is complete, the generated code can use \code{any-vector-ref} and
  13210. %% \code{any-vector-set!} for both tuples and arrays because the
  13211. %% instructions used for those operators do not look at the tag at the
  13212. %% front of the tuple or array.
  13213. \subsection{Expose Allocation}
  13214. This pass should translate array creation into lower-level
  13215. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13216. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13217. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13218. array. The \code{AllocateArray} AST node allocates an array of the
  13219. length specified by the $\Exp$ (of type \INTTY), but does not
  13220. initialize the elements of the array. Generate code in this pass to
  13221. initialize the elements analogous to the case for tuples.
  13222. {\if\edition\racketEd
  13223. \section{Uncover \texttt{get!}}
  13224. \label{sec:uncover-get-bang-vecof}
  13225. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13226. \code{uncover-get!-exp}.
  13227. \fi}
  13228. \subsection{Remove Complex Operands}
  13229. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13230. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13231. complex, and its subexpression must be atomic.
  13232. \subsection{Explicate Control}
  13233. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13234. \code{explicate\_assign}.
  13235. \subsection{Select Instructions}
  13236. Generate instructions for \code{AllocateArray} similar to those for
  13237. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13238. except that the tag at the front of the array should instead use the
  13239. representation discussed in section~\ref{sec:array-rep}.
  13240. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13241. extract the length from the tag.
  13242. The instructions generated for accessing an element of an array differ
  13243. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13244. that the index is not a constant so you need to generate instructions
  13245. that compute the offset at runtime.
  13246. Compile the \code{exit} primitive into a call to the \code{exit}
  13247. function of the C standard library, with an argument of $255$.
  13248. %% Also, note that assignment to an array element may appear in
  13249. %% as a stand-alone statement, so make sure to handle that situation in
  13250. %% this pass.
  13251. %% Finally, the instructions for \code{any-vectorof-length} should be
  13252. %% similar to those for \code{vectorof-length}, except that one must
  13253. %% first project the array by writing zeroes into the $3$-bit tag
  13254. \begin{exercise}\normalfont\normalsize
  13255. Implement a compiler for the \LangArray{} language by extending your
  13256. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13257. programs, including the one shown in figure~\ref{fig:inner_product}
  13258. and also a program that multiplies two matrices. Note that although
  13259. matrices are two-dimensional arrays, they can be encoded into
  13260. one-dimensional arrays by laying out each row in the array, one after
  13261. the next.
  13262. \end{exercise}
  13263. {\if\edition\racketEd
  13264. \section{Challenge: Generational Collection}
  13265. The copying collector described in section~\ref{sec:GC} can incur
  13266. significant runtime overhead because the call to \code{collect} takes
  13267. time proportional to all the live data. One way to reduce this
  13268. overhead is to reduce how much data is inspected in each call to
  13269. \code{collect}. In particular, researchers have observed that recently
  13270. allocated data is more likely to become garbage then data that has
  13271. survived one or more previous calls to \code{collect}. This insight
  13272. motivated the creation of \emph{generational garbage collectors}
  13273. \index{subject}{generational garbage collector} that
  13274. (1) segregate data according to its age into two or more generations;
  13275. (2) allocate less space for younger generations, so collecting them is
  13276. faster, and more space for the older generations; and (3) perform
  13277. collection on the younger generations more frequently than on older
  13278. generations~\citep{Wilson:1992fk}.
  13279. For this challenge assignment, the goal is to adapt the copying
  13280. collector implemented in \code{runtime.c} to use two generations, one
  13281. for young data and one for old data. Each generation consists of a
  13282. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13283. \code{collect} function to use the two generations:
  13284. \begin{enumerate}
  13285. \item Copy the young generation's FromSpace to its ToSpace and then
  13286. switch the role of the ToSpace and FromSpace
  13287. \item If there is enough space for the requested number of bytes in
  13288. the young FromSpace, then return from \code{collect}.
  13289. \item If there is not enough space in the young FromSpace for the
  13290. requested bytes, then move the data from the young generation to the
  13291. old one with the following steps:
  13292. \begin{enumerate}
  13293. \item[a.] If there is enough room in the old FromSpace, copy the young
  13294. FromSpace to the old FromSpace and then return.
  13295. \item[b.] If there is not enough room in the old FromSpace, then collect
  13296. the old generation by copying the old FromSpace to the old ToSpace
  13297. and swap the roles of the old FromSpace and ToSpace.
  13298. \item[c.] If there is enough room now, copy the young FromSpace to the
  13299. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13300. and ToSpace for the old generation. Copy the young FromSpace and
  13301. the old FromSpace into the larger FromSpace for the old
  13302. generation and then return.
  13303. \end{enumerate}
  13304. \end{enumerate}
  13305. We recommend that you generalize the \code{cheney} function so that it
  13306. can be used for all the copies mentioned: between the young FromSpace
  13307. and ToSpace, between the old FromSpace and ToSpace, and between the
  13308. young FromSpace and old FromSpace. This can be accomplished by adding
  13309. parameters to \code{cheney} that replace its use of the global
  13310. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13311. \code{tospace\_begin}, and \code{tospace\_end}.
  13312. Note that the collection of the young generation does not traverse the
  13313. old generation. This introduces a potential problem: there may be
  13314. young data that is reachable only through pointers in the old
  13315. generation. If these pointers are not taken into account, the
  13316. collector could throw away young data that is live! One solution,
  13317. called \emph{pointer recording}, is to maintain a set of all the
  13318. pointers from the old generation into the new generation and consider
  13319. this set as part of the root set. To maintain this set, the compiler
  13320. must insert extra instructions around every \code{vector-set!}. If the
  13321. vector being modified is in the old generation, and if the value being
  13322. written is a pointer into the new generation, then that pointer must
  13323. be added to the set. Also, if the value being overwritten was a
  13324. pointer into the new generation, then that pointer should be removed
  13325. from the set.
  13326. \begin{exercise}\normalfont\normalsize
  13327. Adapt the \code{collect} function in \code{runtime.c} to implement
  13328. generational garbage collection, as outlined in this section.
  13329. Update the code generation for \code{vector-set!} to implement
  13330. pointer recording. Make sure that your new compiler and runtime
  13331. execute without error on your test suite.
  13332. \end{exercise}
  13333. \fi}
  13334. \section{Further Reading}
  13335. \citet{Appel90} describes many data representation approaches,
  13336. including the ones used in the compilation of Standard ML.
  13337. There are many alternatives to copying collectors (and their bigger
  13338. siblings, the generational collectors) with regard to garbage
  13339. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13340. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13341. collectors are that allocation is fast (just a comparison and pointer
  13342. increment), there is no fragmentation, cyclic garbage is collected,
  13343. and the time complexity of collection depends only on the amount of
  13344. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13345. main disadvantages of a two-space copying collector is that it uses a
  13346. lot of extra space and takes a long time to perform the copy, though
  13347. these problems are ameliorated in generational collectors.
  13348. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13349. small objects and generate a lot of garbage, so copying and
  13350. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13351. Garbage collection is an active research topic, especially concurrent
  13352. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13353. developing new techniques and revisiting old
  13354. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13355. meet every year at the International Symposium on Memory Management to
  13356. present these findings.
  13357. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13358. \chapter{Functions}
  13359. \label{ch:Lfun}
  13360. \index{subject}{function}
  13361. \setcounter{footnote}{0}
  13362. This chapter studies the compilation of a subset of \racket{Typed
  13363. Racket}\python{Python} in which only top-level function definitions
  13364. are allowed. This kind of function appears in the C programming
  13365. language, and it serves as an important stepping-stone to implementing
  13366. lexically scoped functions in the form of \key{lambda} abstractions,
  13367. which is the topic of chapter~\ref{ch:Llambda}.
  13368. \section{The \LangFun{} Language}
  13369. The concrete syntax and abstract syntax for function definitions and
  13370. function application are shown in
  13371. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13372. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13373. with zero or more function definitions. The function names from these
  13374. definitions are in scope for the entire program, including all the
  13375. function definitions, and therefore the ordering of function
  13376. definitions does not matter.
  13377. %
  13378. \python{The abstract syntax for function parameters in
  13379. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13380. consists of a parameter name and its type. This design differs from
  13381. Python's \code{ast} module, which has a more complex structure for
  13382. function parameters to handle keyword parameters,
  13383. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13384. complex Python abstract syntax into the simpler syntax of
  13385. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13386. \code{FunctionDef} constructor are for decorators and a type
  13387. comment, neither of which are used by our compiler. We recommend
  13388. replacing them with \code{None} in the \code{shrink} pass.
  13389. }
  13390. %
  13391. The concrete syntax for function application
  13392. \index{subject}{function application}
  13393. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13394. where the first expression
  13395. must evaluate to a function and the remaining expressions are the arguments. The
  13396. abstract syntax for function application is
  13397. $\APPLY{\Exp}{\Exp^*}$.
  13398. %% The syntax for function application does not include an explicit
  13399. %% keyword, which is error prone when using \code{match}. To alleviate
  13400. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13401. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13402. Functions are first-class in the sense that a function pointer
  13403. \index{subject}{function pointer} is data and can be stored in memory or passed
  13404. as a parameter to another function. Thus, there is a function
  13405. type, written
  13406. {\if\edition\racketEd
  13407. \begin{lstlisting}
  13408. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13409. \end{lstlisting}
  13410. \fi}
  13411. {\if\edition\pythonEd\pythonColor
  13412. \begin{lstlisting}
  13413. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13414. \end{lstlisting}
  13415. \fi}
  13416. %
  13417. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13418. through $\Type_n$ and whose return type is $\Type_R$. The main
  13419. limitation of these functions (with respect to
  13420. \racket{Racket}\python{Python} functions) is that they are not
  13421. lexically scoped. That is, the only external entities that can be
  13422. referenced from inside a function body are other globally defined
  13423. functions. The syntax of \LangFun{} prevents function definitions from
  13424. being nested inside each other.
  13425. \newcommand{\LfunGrammarRacket}{
  13426. \begin{array}{lcl}
  13427. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13428. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13429. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13430. \end{array}
  13431. }
  13432. \newcommand{\LfunASTRacket}{
  13433. \begin{array}{lcl}
  13434. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13435. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13436. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13437. \end{array}
  13438. }
  13439. \newcommand{\LfunGrammarPython}{
  13440. \begin{array}{lcl}
  13441. \Type &::=& \key{int}
  13442. \MID \key{bool} \MID \key{void}
  13443. \MID \key{tuple}\LS \Type^+ \RS
  13444. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13445. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13446. \Stmt &::=& \CRETURN{\Exp} \\
  13447. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13448. \end{array}
  13449. }
  13450. \newcommand{\LfunASTPython}{
  13451. \begin{array}{lcl}
  13452. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13453. \MID \key{TupleType}\LS\Type^+\RS\\
  13454. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13455. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13456. \Stmt &::=& \RETURN{\Exp} \\
  13457. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13458. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13459. \end{array}
  13460. }
  13461. \begin{figure}[tp]
  13462. \centering
  13463. \begin{tcolorbox}[colback=white]
  13464. \small
  13465. {\if\edition\racketEd
  13466. \[
  13467. \begin{array}{l}
  13468. \gray{\LintGrammarRacket{}} \\ \hline
  13469. \gray{\LvarGrammarRacket{}} \\ \hline
  13470. \gray{\LifGrammarRacket{}} \\ \hline
  13471. \gray{\LwhileGrammarRacket} \\ \hline
  13472. \gray{\LtupGrammarRacket} \\ \hline
  13473. \LfunGrammarRacket \\
  13474. \begin{array}{lcl}
  13475. \LangFunM{} &::=& \Def \ldots \; \Exp
  13476. \end{array}
  13477. \end{array}
  13478. \]
  13479. \fi}
  13480. {\if\edition\pythonEd\pythonColor
  13481. \[
  13482. \begin{array}{l}
  13483. \gray{\LintGrammarPython{}} \\ \hline
  13484. \gray{\LvarGrammarPython{}} \\ \hline
  13485. \gray{\LifGrammarPython{}} \\ \hline
  13486. \gray{\LwhileGrammarPython} \\ \hline
  13487. \gray{\LtupGrammarPython} \\ \hline
  13488. \LfunGrammarPython \\
  13489. \begin{array}{rcl}
  13490. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13491. \end{array}
  13492. \end{array}
  13493. \]
  13494. \fi}
  13495. \end{tcolorbox}
  13496. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13497. \label{fig:Lfun-concrete-syntax}
  13498. \end{figure}
  13499. \begin{figure}[tp]
  13500. \centering
  13501. \begin{tcolorbox}[colback=white]
  13502. \small
  13503. {\if\edition\racketEd
  13504. \[
  13505. \begin{array}{l}
  13506. \gray{\LintOpAST} \\ \hline
  13507. \gray{\LvarASTRacket{}} \\ \hline
  13508. \gray{\LifASTRacket{}} \\ \hline
  13509. \gray{\LwhileASTRacket{}} \\ \hline
  13510. \gray{\LtupASTRacket{}} \\ \hline
  13511. \LfunASTRacket \\
  13512. \begin{array}{lcl}
  13513. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13514. \end{array}
  13515. \end{array}
  13516. \]
  13517. \fi}
  13518. {\if\edition\pythonEd\pythonColor
  13519. \[
  13520. \begin{array}{l}
  13521. \gray{\LintASTPython{}} \\ \hline
  13522. \gray{\LvarASTPython{}} \\ \hline
  13523. \gray{\LifASTPython{}} \\ \hline
  13524. \gray{\LwhileASTPython} \\ \hline
  13525. \gray{\LtupASTPython} \\ \hline
  13526. \LfunASTPython \\
  13527. \begin{array}{rcl}
  13528. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13529. \end{array}
  13530. \end{array}
  13531. \]
  13532. \fi}
  13533. \end{tcolorbox}
  13534. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13535. \label{fig:Lfun-syntax}
  13536. \end{figure}
  13537. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13538. representative example of defining and using functions in \LangFun{}.
  13539. We define a function \code{map} that applies some other function
  13540. \code{f} to both elements of a tuple and returns a new tuple
  13541. containing the results. We also define a function \code{inc}. The
  13542. program applies \code{map} to \code{inc} and
  13543. %
  13544. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13545. %
  13546. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13547. %
  13548. from which we return \code{42}.
  13549. \begin{figure}[tbp]
  13550. \begin{tcolorbox}[colback=white]
  13551. {\if\edition\racketEd
  13552. \begin{lstlisting}
  13553. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13554. : (Vector Integer Integer)
  13555. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13556. (define (inc [x : Integer]) : Integer
  13557. (+ x 1))
  13558. (vector-ref (map inc (vector 0 41)) 1)
  13559. \end{lstlisting}
  13560. \fi}
  13561. {\if\edition\pythonEd\pythonColor
  13562. \begin{lstlisting}
  13563. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13564. return f(v[0]), f(v[1])
  13565. def inc(x : int) -> int:
  13566. return x + 1
  13567. print( map(inc, (0, 41))[1] )
  13568. \end{lstlisting}
  13569. \fi}
  13570. \end{tcolorbox}
  13571. \caption{Example of using functions in \LangFun{}.}
  13572. \label{fig:Lfun-function-example}
  13573. \end{figure}
  13574. The definitional interpreter for \LangFun{} is shown in
  13575. figure~\ref{fig:interp-Lfun}. The case for the
  13576. %
  13577. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13578. %
  13579. AST is responsible for setting up the mutual recursion between the
  13580. top-level function definitions.
  13581. %
  13582. \racket{We use the classic back-patching
  13583. \index{subject}{back-patching} approach that uses mutable variables
  13584. and makes two passes over the function
  13585. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13586. top-level environment using a mutable cons cell for each function
  13587. definition. Note that the \code{lambda} value for each function is
  13588. incomplete; it does not yet include the environment. Once the
  13589. top-level environment has been constructed, we iterate over it and
  13590. update the \code{lambda} values to use the top-level environment.}
  13591. %
  13592. \python{We create a dictionary named \code{env} and fill it in
  13593. by mapping each function name to a new \code{Function} value,
  13594. each of which stores a reference to the \code{env}.
  13595. (We define the class \code{Function} for this purpose.)}
  13596. %
  13597. To interpret a function \racket{application}\python{call}, we match
  13598. the result of the function expression to obtain a function value. We
  13599. then extend the function's environment with the mapping of parameters to
  13600. argument values. Finally, we interpret the body of the function in
  13601. this extended environment.
  13602. \begin{figure}[tp]
  13603. \begin{tcolorbox}[colback=white]
  13604. {\if\edition\racketEd
  13605. \begin{lstlisting}
  13606. (define interp-Lfun-class
  13607. (class interp-Lvec-class
  13608. (super-new)
  13609. (define/override ((interp-exp env) e)
  13610. (define recur (interp-exp env))
  13611. (match e
  13612. [(Apply fun args)
  13613. (define fun-val (recur fun))
  13614. (define arg-vals (for/list ([e args]) (recur e)))
  13615. (match fun-val
  13616. [`(function (,xs ...) ,body ,fun-env)
  13617. (define params-args (for/list ([x xs] [arg arg-vals])
  13618. (cons x (box arg))))
  13619. (define new-env (append params-args fun-env))
  13620. ((interp-exp new-env) body)]
  13621. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  13622. [else ((super interp-exp env) e)]
  13623. ))
  13624. (define/public (interp-def d)
  13625. (match d
  13626. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13627. (cons f (box `(function ,xs ,body ())))]))
  13628. (define/override (interp-program p)
  13629. (match p
  13630. [(ProgramDefsExp info ds body)
  13631. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13632. (for/list ([f (in-dict-values top-level)])
  13633. (set-box! f (match (unbox f)
  13634. [`(function ,xs ,body ())
  13635. `(function ,xs ,body ,top-level)])))
  13636. ((interp-exp top-level) body))]))
  13637. ))
  13638. (define (interp-Lfun p)
  13639. (send (new interp-Lfun-class) interp-program p))
  13640. \end{lstlisting}
  13641. \fi}
  13642. {\if\edition\pythonEd\pythonColor
  13643. \begin{lstlisting}
  13644. class InterpLfun(InterpLtup):
  13645. def apply_fun(self, fun, args, e):
  13646. match fun:
  13647. case Function(name, xs, body, env):
  13648. new_env = env.copy().update(zip(xs, args))
  13649. return self.interp_stmts(body, new_env)
  13650. case _:
  13651. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13652. def interp_exp(self, e, env):
  13653. match e:
  13654. case Call(Name('input_int'), []):
  13655. return super().interp_exp(e, env)
  13656. case Call(func, args):
  13657. f = self.interp_exp(func, env)
  13658. vs = [self.interp_exp(arg, env) for arg in args]
  13659. return self.apply_fun(f, vs, e)
  13660. case _:
  13661. return super().interp_exp(e, env)
  13662. def interp_stmts(self, ss, env):
  13663. if len(ss) == 0:
  13664. return
  13665. match ss[0]:
  13666. case Return(value):
  13667. return self.interp_exp(value, env)
  13668. case FunctionDef(name, params, bod, dl, returns, comment):
  13669. ps = [x for (x,t) in params]
  13670. env[name] = Function(name, ps, bod, env)
  13671. return self.interp_stmts(ss[1:], env)
  13672. case _:
  13673. return super().interp_stmts(ss, env)
  13674. def interp(self, p):
  13675. match p:
  13676. case Module(ss):
  13677. env = {}
  13678. self.interp_stmts(ss, env)
  13679. if 'main' in env.keys():
  13680. self.apply_fun(env['main'], [], None)
  13681. case _:
  13682. raise Exception('interp: unexpected ' + repr(p))
  13683. \end{lstlisting}
  13684. \fi}
  13685. \end{tcolorbox}
  13686. \caption{Interpreter for the \LangFun{} language.}
  13687. \label{fig:interp-Lfun}
  13688. \end{figure}
  13689. %\margincomment{TODO: explain type checker}
  13690. The type checker for \LangFun{} is shown in
  13691. figure~\ref{fig:type-check-Lfun}.
  13692. %
  13693. \python{(We omit the code that parses function parameters into the
  13694. simpler abstract syntax.)}
  13695. %
  13696. Similarly to the interpreter, the case for the
  13697. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13698. %
  13699. AST is responsible for setting up the mutual recursion between the
  13700. top-level function definitions. We begin by create a mapping
  13701. \code{env} from every function name to its type. We then type check
  13702. the program using this mapping.
  13703. %
  13704. In the case for function \racket{application}\python{call}, we match
  13705. the type of the function expression to a function type and check that
  13706. the types of the argument expressions are equal to the function's
  13707. parameter types. The type of the \racket{application}\python{call} as
  13708. a whole is the return type from the function type.
  13709. \begin{figure}[tp]
  13710. \begin{tcolorbox}[colback=white]
  13711. {\if\edition\racketEd
  13712. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13713. (define type-check-Lfun-class
  13714. (class type-check-Lvec-class
  13715. (super-new)
  13716. (inherit check-type-equal?)
  13717. (define/public (type-check-apply env e es)
  13718. (define-values (e^ ty) ((type-check-exp env) e))
  13719. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13720. ((type-check-exp env) e)))
  13721. (match ty
  13722. [`(,ty^* ... -> ,rt)
  13723. (for ([arg-ty ty*] [param-ty ty^*])
  13724. (check-type-equal? arg-ty param-ty (Apply e es)))
  13725. (values e^ e* rt)]))
  13726. (define/override (type-check-exp env)
  13727. (lambda (e)
  13728. (match e
  13729. [(FunRef f n)
  13730. (values (FunRef f n) (dict-ref env f))]
  13731. [(Apply e es)
  13732. (define-values (e^ es^ rt) (type-check-apply env e es))
  13733. (values (Apply e^ es^) rt)]
  13734. [(Call e es)
  13735. (define-values (e^ es^ rt) (type-check-apply env e es))
  13736. (values (Call e^ es^) rt)]
  13737. [else ((super type-check-exp env) e)])))
  13738. (define/public (type-check-def env)
  13739. (lambda (e)
  13740. (match e
  13741. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13742. (define new-env (append (map cons xs ps) env))
  13743. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13744. (check-type-equal? ty^ rt body)
  13745. (Def f p:t* rt info body^)])))
  13746. (define/public (fun-def-type d)
  13747. (match d
  13748. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13749. (define/override (type-check-program e)
  13750. (match e
  13751. [(ProgramDefsExp info ds body)
  13752. (define env (for/list ([d ds])
  13753. (cons (Def-name d) (fun-def-type d))))
  13754. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13755. (define-values (body^ ty) ((type-check-exp env) body))
  13756. (check-type-equal? ty 'Integer body)
  13757. (ProgramDefsExp info ds^ body^)]))))
  13758. (define (type-check-Lfun p)
  13759. (send (new type-check-Lfun-class) type-check-program p))
  13760. \end{lstlisting}
  13761. \fi}
  13762. {\if\edition\pythonEd\pythonColor
  13763. \begin{lstlisting}
  13764. class TypeCheckLfun(TypeCheckLtup):
  13765. def type_check_exp(self, e, env):
  13766. match e:
  13767. case Call(Name('input_int'), []):
  13768. return super().type_check_exp(e, env)
  13769. case Call(func, args):
  13770. func_t = self.type_check_exp(func, env)
  13771. args_t = [self.type_check_exp(arg, env) for arg in args]
  13772. match func_t:
  13773. case FunctionType(params_t, return_t):
  13774. for (arg_t, param_t) in zip(args_t, params_t):
  13775. check_type_equal(param_t, arg_t, e)
  13776. return return_t
  13777. case _:
  13778. raise Exception('type_check_exp: in call, unexpected ' +
  13779. repr(func_t))
  13780. case _:
  13781. return super().type_check_exp(e, env)
  13782. def type_check_stmts(self, ss, env):
  13783. if len(ss) == 0:
  13784. return
  13785. match ss[0]:
  13786. case FunctionDef(name, params, body, dl, returns, comment):
  13787. new_env = env.copy().update(params)
  13788. rt = self.type_check_stmts(body, new_env)
  13789. check_type_equal(returns, rt, ss[0])
  13790. return self.type_check_stmts(ss[1:], env)
  13791. case Return(value):
  13792. return self.type_check_exp(value, env)
  13793. case _:
  13794. return super().type_check_stmts(ss, env)
  13795. def type_check(self, p):
  13796. match p:
  13797. case Module(body):
  13798. env = {}
  13799. for s in body:
  13800. match s:
  13801. case FunctionDef(name, params, bod, dl, returns, comment):
  13802. if name in env:
  13803. raise Exception('type_check: function ' +
  13804. repr(name) + ' defined twice')
  13805. params_t = [t for (x,t) in params]
  13806. env[name] = FunctionType(params_t, returns)
  13807. self.type_check_stmts(body, env)
  13808. case _:
  13809. raise Exception('type_check: unexpected ' + repr(p))
  13810. \end{lstlisting}
  13811. \fi}
  13812. \end{tcolorbox}
  13813. \caption{Type checker for the \LangFun{} language.}
  13814. \label{fig:type-check-Lfun}
  13815. \end{figure}
  13816. \clearpage
  13817. \section{Functions in x86}
  13818. \label{sec:fun-x86}
  13819. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13820. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13821. %% \margincomment{\tiny Talk about the return address on the
  13822. %% stack and what callq and retq does.\\ --Jeremy }
  13823. The x86 architecture provides a few features to support the
  13824. implementation of functions. We have already seen that there are
  13825. labels in x86 so that one can refer to the location of an instruction,
  13826. as is needed for jump instructions. Labels can also be used to mark
  13827. the beginning of the instructions for a function. Going further, we
  13828. can obtain the address of a label by using the \key{leaq}
  13829. instruction. For example, the following puts the address of the
  13830. \code{inc} label into the \code{rbx} register:
  13831. \begin{lstlisting}
  13832. leaq inc(%rip), %rbx
  13833. \end{lstlisting}
  13834. Recall from section~\ref{sec:select-instructions-gc} that
  13835. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13836. addressing.
  13837. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13838. to functions whose locations were given by a label, such as
  13839. \code{read\_int}. To support function calls in this chapter we instead
  13840. jump to functions whose location are given by an address in
  13841. a register; that is, we use \emph{indirect function calls}. The
  13842. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13843. before the register name.\index{subject}{indirect function call}
  13844. \begin{lstlisting}
  13845. callq *%rbx
  13846. \end{lstlisting}
  13847. \subsection{Calling Conventions}
  13848. \label{sec:calling-conventions-fun}
  13849. \index{subject}{calling conventions}
  13850. The \code{callq} instruction provides partial support for implementing
  13851. functions: it pushes the return address on the stack and it jumps to
  13852. the target. However, \code{callq} does not handle
  13853. \begin{enumerate}
  13854. \item parameter passing,
  13855. \item pushing frames on the procedure call stack and popping them off,
  13856. or
  13857. \item determining how registers are shared by different functions.
  13858. \end{enumerate}
  13859. Regarding parameter passing, recall that the x86-64 calling
  13860. convention for Unix-based system uses the following six registers to
  13861. pass arguments to a function, in the given order.
  13862. \begin{lstlisting}
  13863. rdi rsi rdx rcx r8 r9
  13864. \end{lstlisting}
  13865. If there are more than six arguments, then the calling convention
  13866. mandates using space on the frame of the caller for the rest of the
  13867. arguments. However, to ease the implementation of efficient tail calls
  13868. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13869. arguments.
  13870. %
  13871. The return value of the function is stored in register \code{rax}.
  13872. \index{subject}{prelude}\index{subject}{conclusion}
  13873. Regarding frames \index{subject}{frame} and the procedure call stack,
  13874. \index{subject}{procedure call stack} recall from
  13875. section~\ref{sec:x86} that the stack grows down and each function call
  13876. uses a chunk of space on the stack called a frame. The caller sets the
  13877. stack pointer, register \code{rsp}, to the last data item in its
  13878. frame. The callee must not change anything in the caller's frame, that
  13879. is, anything that is at or above the stack pointer. The callee is free
  13880. to use locations that are below the stack pointer.
  13881. Recall that we store variables of tuple type on the root stack. So,
  13882. the prelude of a function needs to move the root stack pointer
  13883. \code{r15} up according to the number of variables of tuple type and
  13884. the conclusion needs to move the root stack pointer back down. Also,
  13885. the prelude must initialize to \code{0} this frame's slots in the root
  13886. stack to signal to the garbage collector that those slots do not yet
  13887. contain a valid pointer. Otherwise the garbage collector will
  13888. interpret the garbage bits in those slots as memory addresses and try
  13889. to traverse them, causing serious mayhem!
  13890. Regarding the sharing of registers between different functions, recall
  13891. from section~\ref{sec:calling-conventions} that the registers are
  13892. divided into two groups, the caller-saved registers and the
  13893. callee-saved registers. The caller should assume that all the
  13894. caller-saved registers are overwritten with arbitrary values by the
  13895. callee. For that reason we recommend in
  13896. section~\ref{sec:calling-conventions} that variables that are live
  13897. during a function call should not be assigned to caller-saved
  13898. registers.
  13899. On the flip side, if the callee wants to use a callee-saved register,
  13900. the callee must save the contents of those registers on their stack
  13901. frame and then put them back prior to returning to the caller. For
  13902. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13903. the register allocator assigns a variable to a callee-saved register,
  13904. then the prelude of the \code{main} function must save that register
  13905. to the stack and the conclusion of \code{main} must restore it. This
  13906. recommendation now generalizes to all functions.
  13907. Recall that the base pointer, register \code{rbp}, is used as a
  13908. point of reference within a frame, so that each local variable can be
  13909. accessed at a fixed offset from the base pointer
  13910. (section~\ref{sec:x86}).
  13911. %
  13912. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13913. and callee frames.
  13914. \begin{figure}[tbp]
  13915. \centering
  13916. \begin{tcolorbox}[colback=white]
  13917. \begin{tabular}{r|r|l|l} \hline
  13918. Caller View & Callee View & Contents & Frame \\ \hline
  13919. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13920. 0(\key{\%rbp}) & & old \key{rbp} \\
  13921. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13922. \ldots & & \ldots \\
  13923. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13924. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13925. \ldots & & \ldots \\
  13926. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13927. %% & & \\
  13928. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13929. %% & \ldots & \ldots \\
  13930. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13931. \hline
  13932. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13933. & 0(\key{\%rbp}) & old \key{rbp} \\
  13934. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13935. & \ldots & \ldots \\
  13936. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13937. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13938. & \ldots & \ldots \\
  13939. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13940. \end{tabular}
  13941. \end{tcolorbox}
  13942. \caption{Memory layout of caller and callee frames.}
  13943. \label{fig:call-frames}
  13944. \end{figure}
  13945. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13946. %% local variables and for storing the values of callee-saved registers
  13947. %% (we shall refer to all of these collectively as ``locals''), and that
  13948. %% at the beginning of a function we move the stack pointer \code{rsp}
  13949. %% down to make room for them.
  13950. %% We recommend storing the local variables
  13951. %% first and then the callee-saved registers, so that the local variables
  13952. %% can be accessed using \code{rbp} the same as before the addition of
  13953. %% functions.
  13954. %% To make additional room for passing arguments, we shall
  13955. %% move the stack pointer even further down. We count how many stack
  13956. %% arguments are needed for each function call that occurs inside the
  13957. %% body of the function and find their maximum. Adding this number to the
  13958. %% number of locals gives us how much the \code{rsp} should be moved at
  13959. %% the beginning of the function. In preparation for a function call, we
  13960. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13961. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13962. %% so on.
  13963. %% Upon calling the function, the stack arguments are retrieved by the
  13964. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13965. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13966. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13967. %% the layout of the caller and callee frames. Notice how important it is
  13968. %% that we correctly compute the maximum number of arguments needed for
  13969. %% function calls; if that number is too small then the arguments and
  13970. %% local variables will smash into each other!
  13971. \subsection{Efficient Tail Calls}
  13972. \label{sec:tail-call}
  13973. In general, the amount of stack space used by a program is determined
  13974. by the longest chain of nested function calls. That is, if function
  13975. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13976. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13977. large if functions are recursive. However, in some cases we can
  13978. arrange to use only a constant amount of space for a long chain of
  13979. nested function calls.
  13980. A \emph{tail call}\index{subject}{tail call} is a function call that
  13981. happens as the last action in a function body. For example, in the
  13982. following program, the recursive call to \code{tail\_sum} is a tail
  13983. call:
  13984. \begin{center}
  13985. {\if\edition\racketEd
  13986. \begin{lstlisting}
  13987. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13988. (if (eq? n 0)
  13989. r
  13990. (tail_sum (- n 1) (+ n r))))
  13991. (+ (tail_sum 3 0) 36)
  13992. \end{lstlisting}
  13993. \fi}
  13994. {\if\edition\pythonEd\pythonColor
  13995. \begin{lstlisting}
  13996. def tail_sum(n : int, r : int) -> int:
  13997. if n == 0:
  13998. return r
  13999. else:
  14000. return tail_sum(n - 1, n + r)
  14001. print( tail_sum(3, 0) + 36)
  14002. \end{lstlisting}
  14003. \fi}
  14004. \end{center}
  14005. At a tail call, the frame of the caller is no longer needed, so we can
  14006. pop the caller's frame before making the tail call. With this
  14007. approach, a recursive function that makes only tail calls ends up
  14008. using a constant amount of stack space. Functional languages like
  14009. Racket rely heavily on recursive functions, so the definition of
  14010. Racket \emph{requires} that all tail calls be optimized in this way.
  14011. \index{subject}{frame}
  14012. Some care is needed with regard to argument passing in tail calls. As
  14013. mentioned, for arguments beyond the sixth, the convention is to use
  14014. space in the caller's frame for passing arguments. However, for a
  14015. tail call we pop the caller's frame and can no longer use it. An
  14016. alternative is to use space in the callee's frame for passing
  14017. arguments. However, this option is also problematic because the caller
  14018. and callee's frames overlap in memory. As we begin to copy the
  14019. arguments from their sources in the caller's frame, the target
  14020. locations in the callee's frame might collide with the sources for
  14021. later arguments! We solve this problem by using the heap instead of
  14022. the stack for passing more than six arguments
  14023. (section~\ref{sec:limit-functions-r4}).
  14024. As mentioned, for a tail call we pop the caller's frame prior to
  14025. making the tail call. The instructions for popping a frame are the
  14026. instructions that we usually place in the conclusion of a
  14027. function. Thus, we also need to place such code immediately before
  14028. each tail call. These instructions include restoring the callee-saved
  14029. registers, so it is fortunate that the argument passing registers are
  14030. all caller-saved registers.
  14031. One note remains regarding which instruction to use to make the tail
  14032. call. When the callee is finished, it should not return to the current
  14033. function but instead return to the function that called the current
  14034. one. Thus, the return address that is already on the stack is the
  14035. right one, and we should not use \key{callq} to make the tail call
  14036. because that would overwrite the return address. Instead we simply use
  14037. the \key{jmp} instruction. As with the indirect function call, we write
  14038. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14039. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14040. jump target because the conclusion can overwrite just about everything
  14041. else.
  14042. \begin{lstlisting}
  14043. jmp *%rax
  14044. \end{lstlisting}
  14045. \section{Shrink \LangFun{}}
  14046. \label{sec:shrink-r4}
  14047. The \code{shrink} pass performs a minor modification to ease the
  14048. later passes. This pass introduces an explicit \code{main} function
  14049. that gobbles up all the top-level statements of the module.
  14050. %
  14051. \racket{It also changes the top \code{ProgramDefsExp} form to
  14052. \code{ProgramDefs}.}
  14053. {\if\edition\racketEd
  14054. \begin{lstlisting}
  14055. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14056. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14057. \end{lstlisting}
  14058. where $\itm{mainDef}$ is
  14059. \begin{lstlisting}
  14060. (Def 'main '() 'Integer '() |$\Exp'$|)
  14061. \end{lstlisting}
  14062. \fi}
  14063. {\if\edition\pythonEd\pythonColor
  14064. \begin{lstlisting}
  14065. Module(|$\Def\ldots\Stmt\ldots$|)
  14066. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14067. \end{lstlisting}
  14068. where $\itm{mainDef}$ is
  14069. \begin{lstlisting}
  14070. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14071. \end{lstlisting}
  14072. \fi}
  14073. \section{Reveal Functions and the \LangFunRef{} language}
  14074. \label{sec:reveal-functions-r4}
  14075. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14076. in that it conflates the use of function names and local
  14077. variables. This is a problem because we need to compile the use of a
  14078. function name differently from the use of a local variable. In
  14079. particular, we use \code{leaq} to convert the function name (a label
  14080. in x86) to an address in a register. Thus, we create a new pass that
  14081. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14082. $n$ is the arity of the function.\python{\footnote{The arity is not
  14083. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14084. This pass is named \code{reveal\_functions} and the output language
  14085. is \LangFunRef{}.
  14086. %is defined in figure~\ref{fig:f1-syntax}.
  14087. %% The concrete syntax for a
  14088. %% function reference is $\CFUNREF{f}$.
  14089. %% \begin{figure}[tp]
  14090. %% \centering
  14091. %% \fbox{
  14092. %% \begin{minipage}{0.96\textwidth}
  14093. %% {\if\edition\racketEd
  14094. %% \[
  14095. %% \begin{array}{lcl}
  14096. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14097. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14098. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14099. %% \end{array}
  14100. %% \]
  14101. %% \fi}
  14102. %% {\if\edition\pythonEd\pythonColor
  14103. %% \[
  14104. %% \begin{array}{lcl}
  14105. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14106. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14107. %% \end{array}
  14108. %% \]
  14109. %% \fi}
  14110. %% \end{minipage}
  14111. %% }
  14112. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14113. %% (figure~\ref{fig:Lfun-syntax}).}
  14114. %% \label{fig:f1-syntax}
  14115. %% \end{figure}
  14116. %% Distinguishing between calls in tail position and non-tail position
  14117. %% requires the pass to have some notion of context. We recommend using
  14118. %% two mutually recursive functions, one for processing expressions in
  14119. %% tail position and another for the rest.
  14120. \racket{Placing this pass after \code{uniquify} will make sure that
  14121. there are no local variables and functions that share the same
  14122. name.}
  14123. %
  14124. The \code{reveal\_functions} pass should come before the
  14125. \code{remove\_complex\_operands} pass because function references
  14126. should be categorized as complex expressions.
  14127. \section{Limit Functions}
  14128. \label{sec:limit-functions-r4}
  14129. Recall that we wish to limit the number of function parameters to six
  14130. so that we do not need to use the stack for argument passing, which
  14131. makes it easier to implement efficient tail calls. However, because
  14132. the input language \LangFun{} supports arbitrary numbers of function
  14133. arguments, we have some work to do! The \code{limit\_functions} pass
  14134. transforms functions and function calls that involve more than six
  14135. arguments to pass the first five arguments as usual, but it packs the
  14136. rest of the arguments into a tuple and passes it as the sixth
  14137. argument.\footnote{The implementation this pass can be postponed to
  14138. last because you can test the rest of the passes on functions with
  14139. six or fewer parameters.}
  14140. Each function definition with seven or more parameters is transformed as
  14141. follows.
  14142. {\if\edition\racketEd
  14143. \begin{lstlisting}
  14144. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14145. |$\Rightarrow$|
  14146. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14147. \end{lstlisting}
  14148. \fi}
  14149. {\if\edition\pythonEd\pythonColor
  14150. \begin{lstlisting}
  14151. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14152. |$\Rightarrow$|
  14153. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14154. |$T_r$|, None, |$\itm{body}'$|, None)
  14155. \end{lstlisting}
  14156. \fi}
  14157. %
  14158. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14159. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14160. the $k$th element of the tuple, where $k = i - 6$.
  14161. %
  14162. {\if\edition\racketEd
  14163. \begin{lstlisting}
  14164. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14165. \end{lstlisting}
  14166. \fi}
  14167. {\if\edition\pythonEd\pythonColor
  14168. \begin{lstlisting}
  14169. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14170. \end{lstlisting}
  14171. \fi}
  14172. For function calls with too many arguments, the \code{limit\_functions}
  14173. pass transforms them in the following way:
  14174. \begin{tabular}{lll}
  14175. \begin{minipage}{0.3\textwidth}
  14176. {\if\edition\racketEd
  14177. \begin{lstlisting}
  14178. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14179. \end{lstlisting}
  14180. \fi}
  14181. {\if\edition\pythonEd\pythonColor
  14182. \begin{lstlisting}
  14183. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14184. \end{lstlisting}
  14185. \fi}
  14186. \end{minipage}
  14187. &
  14188. $\Rightarrow$
  14189. &
  14190. \begin{minipage}{0.5\textwidth}
  14191. {\if\edition\racketEd
  14192. \begin{lstlisting}
  14193. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14194. \end{lstlisting}
  14195. \fi}
  14196. {\if\edition\pythonEd\pythonColor
  14197. \begin{lstlisting}
  14198. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14199. \end{lstlisting}
  14200. \fi}
  14201. \end{minipage}
  14202. \end{tabular}
  14203. \section{Remove Complex Operands}
  14204. \label{sec:rco-r4}
  14205. The primary decisions to make for this pass are whether to classify
  14206. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14207. atomic or complex expressions. Recall that an atomic expression will
  14208. end up as an immediate argument of an x86 instruction. Function
  14209. application will be translated to a sequence of instructions, so
  14210. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14211. complex expression. On the other hand, the arguments of
  14212. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14213. expressions.
  14214. %
  14215. Regarding \code{FunRef}, as discussed previously, the function label
  14216. needs to be converted to an address using the \code{leaq}
  14217. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14218. needs to be classified as a complex expression so that we generate an
  14219. assignment statement with a left-hand side that can serve as the
  14220. target of the \code{leaq}.
  14221. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14222. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14223. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14224. and augments programs to include a list of function definitions.
  14225. %
  14226. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14227. \newcommand{\LfunMonadASTRacket}{
  14228. \begin{array}{lcl}
  14229. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14230. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14231. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14232. \end{array}
  14233. }
  14234. \newcommand{\LfunMonadASTPython}{
  14235. \begin{array}{lcl}
  14236. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14237. \MID \key{TupleType}\LS\Type^+\RS\\
  14238. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14239. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14240. \Stmt &::=& \RETURN{\Exp} \\
  14241. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14242. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14243. \end{array}
  14244. }
  14245. \begin{figure}[tp]
  14246. \centering
  14247. \begin{tcolorbox}[colback=white]
  14248. \small
  14249. {\if\edition\racketEd
  14250. \[
  14251. \begin{array}{l}
  14252. \gray{\LvarMonadASTRacket} \\ \hline
  14253. \gray{\LifMonadASTRacket} \\ \hline
  14254. \gray{\LwhileMonadASTRacket} \\ \hline
  14255. \gray{\LtupMonadASTRacket} \\ \hline
  14256. \LfunMonadASTRacket \\
  14257. \begin{array}{rcl}
  14258. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14259. \end{array}
  14260. \end{array}
  14261. \]
  14262. \fi}
  14263. {\if\edition\pythonEd\pythonColor
  14264. \[
  14265. \begin{array}{l}
  14266. \gray{\LvarMonadASTPython} \\ \hline
  14267. \gray{\LifMonadASTPython} \\ \hline
  14268. \gray{\LwhileMonadASTPython} \\ \hline
  14269. \gray{\LtupMonadASTPython} \\ \hline
  14270. \LfunMonadASTPython \\
  14271. \begin{array}{rcl}
  14272. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14273. \end{array}
  14274. \end{array}
  14275. \]
  14276. \fi}
  14277. \end{tcolorbox}
  14278. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14279. \label{fig:Lfun-anf-syntax}
  14280. \end{figure}
  14281. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14282. %% \LangFunANF{} of this pass.
  14283. %% \begin{figure}[tp]
  14284. %% \centering
  14285. %% \fbox{
  14286. %% \begin{minipage}{0.96\textwidth}
  14287. %% \small
  14288. %% \[
  14289. %% \begin{array}{rcl}
  14290. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14291. %% \MID \VOID{} } \\
  14292. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14293. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14294. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14295. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14296. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14297. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14298. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14299. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14300. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14301. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14302. %% \end{array}
  14303. %% \]
  14304. %% \end{minipage}
  14305. %% }
  14306. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14307. %% \label{fig:Lfun-anf-syntax}
  14308. %% \end{figure}
  14309. \section{Explicate Control and the \LangCFun{} language}
  14310. \label{sec:explicate-control-r4}
  14311. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14312. output of \code{explicate\_control}.
  14313. %
  14314. %% \racket{(The concrete syntax is given in
  14315. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14316. %
  14317. The auxiliary functions for assignment\racket{ and tail contexts} should
  14318. be updated with cases for
  14319. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14320. function for predicate context should be updated for
  14321. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14322. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14323. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14324. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14325. auxiliary function for processing function definitions. This code is
  14326. similar to the case for \code{Program} in \LangVec{}. The top-level
  14327. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14328. form of \LangFun{} can then apply this new function to all the
  14329. function definitions.
  14330. {\if\edition\pythonEd\pythonColor
  14331. The translation of \code{Return} statements requires a new auxiliary
  14332. function to handle expressions in tail context, called
  14333. \code{explicate\_tail}. The function should take an expression and the
  14334. dictionary of basic blocks and produce a list of statements in the
  14335. \LangCFun{} language. The \code{explicate\_tail} function should
  14336. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14337. and a default case for other kinds of expressions. The default case
  14338. should produce a \code{Return} statement. The case for \code{Call}
  14339. should change it into \code{TailCall}. The other cases should
  14340. recursively process their subexpressions and statements, choosing the
  14341. appropriate explicate functions for the various contexts.
  14342. \fi}
  14343. \newcommand{\CfunASTRacket}{
  14344. \begin{array}{lcl}
  14345. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14346. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14347. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14348. \end{array}
  14349. }
  14350. \newcommand{\CfunASTPython}{
  14351. \begin{array}{lcl}
  14352. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14353. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14354. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14355. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14356. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14357. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14358. \end{array}
  14359. }
  14360. \begin{figure}[tp]
  14361. \begin{tcolorbox}[colback=white]
  14362. \small
  14363. {\if\edition\racketEd
  14364. \[
  14365. \begin{array}{l}
  14366. \gray{\CvarASTRacket} \\ \hline
  14367. \gray{\CifASTRacket} \\ \hline
  14368. \gray{\CloopASTRacket} \\ \hline
  14369. \gray{\CtupASTRacket} \\ \hline
  14370. \CfunASTRacket \\
  14371. \begin{array}{lcl}
  14372. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14373. \end{array}
  14374. \end{array}
  14375. \]
  14376. \fi}
  14377. {\if\edition\pythonEd\pythonColor
  14378. \[
  14379. \begin{array}{l}
  14380. \gray{\CifASTPython} \\ \hline
  14381. \gray{\CtupASTPython} \\ \hline
  14382. \CfunASTPython \\
  14383. \begin{array}{lcl}
  14384. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14385. \end{array}
  14386. \end{array}
  14387. \]
  14388. \fi}
  14389. \end{tcolorbox}
  14390. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14391. \label{fig:c3-syntax}
  14392. \end{figure}
  14393. \clearpage
  14394. \section{Select Instructions and the \LangXIndCall{} Language}
  14395. \label{sec:select-r4}
  14396. \index{subject}{instruction selection}
  14397. The output of select instructions is a program in the \LangXIndCall{}
  14398. language; the definition of its concrete syntax is shown in
  14399. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14400. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14401. directive on the labels of function definitions to make sure the
  14402. bottom three bits are zero, which we put to use in
  14403. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14404. this section. \index{subject}{x86}
  14405. \newcommand{\GrammarXIndCall}{
  14406. \begin{array}{lcl}
  14407. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14408. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14409. \Block &::= & \Instr^{+} \\
  14410. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14411. \end{array}
  14412. }
  14413. \newcommand{\ASTXIndCallRacket}{
  14414. \begin{array}{lcl}
  14415. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14416. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14417. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14418. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14419. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14420. \end{array}
  14421. }
  14422. \begin{figure}[tp]
  14423. \begin{tcolorbox}[colback=white]
  14424. \small
  14425. \[
  14426. \begin{array}{l}
  14427. \gray{\GrammarXInt} \\ \hline
  14428. \gray{\GrammarXIf} \\ \hline
  14429. \gray{\GrammarXGlobal} \\ \hline
  14430. \GrammarXIndCall \\
  14431. \begin{array}{lcl}
  14432. \LangXIndCallM{} &::= & \Def^{*}
  14433. \end{array}
  14434. \end{array}
  14435. \]
  14436. \end{tcolorbox}
  14437. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14438. \label{fig:x86-3-concrete}
  14439. \end{figure}
  14440. \begin{figure}[tp]
  14441. \begin{tcolorbox}[colback=white]
  14442. \small
  14443. {\if\edition\racketEd
  14444. \[\arraycolsep=3pt
  14445. \begin{array}{l}
  14446. \gray{\ASTXIntRacket} \\ \hline
  14447. \gray{\ASTXIfRacket} \\ \hline
  14448. \gray{\ASTXGlobalRacket} \\ \hline
  14449. \ASTXIndCallRacket \\
  14450. \begin{array}{lcl}
  14451. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14452. \end{array}
  14453. \end{array}
  14454. \]
  14455. \fi}
  14456. {\if\edition\pythonEd\pythonColor
  14457. \[
  14458. \begin{array}{lcl}
  14459. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14460. \MID \BYTEREG{\Reg} } \\
  14461. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14462. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14463. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14464. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14465. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14466. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14467. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14468. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14469. \end{array}
  14470. \]
  14471. \fi}
  14472. \end{tcolorbox}
  14473. \caption{The abstract syntax of \LangXIndCall{} (extends
  14474. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14475. \label{fig:x86-3}
  14476. \end{figure}
  14477. An assignment of a function reference to a variable becomes a
  14478. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14479. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14480. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14481. node, whose concrete syntax is instruction-pointer-relative
  14482. addressing.
  14483. \begin{center}
  14484. \begin{tabular}{lcl}
  14485. \begin{minipage}{0.35\textwidth}
  14486. {\if\edition\racketEd
  14487. \begin{lstlisting}
  14488. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14489. \end{lstlisting}
  14490. \fi}
  14491. {\if\edition\pythonEd\pythonColor
  14492. \begin{lstlisting}
  14493. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14494. \end{lstlisting}
  14495. \fi}
  14496. \end{minipage}
  14497. &
  14498. $\Rightarrow$\qquad\qquad
  14499. &
  14500. \begin{minipage}{0.3\textwidth}
  14501. \begin{lstlisting}
  14502. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14503. \end{lstlisting}
  14504. \end{minipage}
  14505. \end{tabular}
  14506. \end{center}
  14507. Regarding function definitions, we need to remove the parameters and
  14508. instead perform parameter passing using the conventions discussed in
  14509. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14510. registers. We recommend turning the parameters into local variables
  14511. and generating instructions at the beginning of the function to move
  14512. from the argument-passing registers
  14513. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14514. {\if\edition\racketEd
  14515. \begin{lstlisting}
  14516. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14517. |$\Rightarrow$|
  14518. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14519. \end{lstlisting}
  14520. \fi}
  14521. {\if\edition\pythonEd\pythonColor
  14522. \begin{lstlisting}
  14523. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14524. |$\Rightarrow$|
  14525. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14526. \end{lstlisting}
  14527. \fi}
  14528. The basic blocks $B'$ are the same as $B$ except that the
  14529. \code{start} block is modified to add the instructions for moving from
  14530. the argument registers to the parameter variables. So the \code{start}
  14531. block of $B$ shown on the left of the following is changed to the code
  14532. on the right:
  14533. \begin{center}
  14534. \begin{minipage}{0.3\textwidth}
  14535. \begin{lstlisting}
  14536. start:
  14537. |$\itm{instr}_1$|
  14538. |$\cdots$|
  14539. |$\itm{instr}_n$|
  14540. \end{lstlisting}
  14541. \end{minipage}
  14542. $\Rightarrow$
  14543. \begin{minipage}{0.3\textwidth}
  14544. \begin{lstlisting}
  14545. |$f$|start:
  14546. movq %rdi, |$x_1$|
  14547. movq %rsi, |$x_2$|
  14548. |$\cdots$|
  14549. |$\itm{instr}_1$|
  14550. |$\cdots$|
  14551. |$\itm{instr}_n$|
  14552. \end{lstlisting}
  14553. \end{minipage}
  14554. \end{center}
  14555. Recall that we use the label \code{start} for the initial block of a
  14556. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14557. the conclusion of the program with \code{conclusion}, so that
  14558. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14559. by a jump to \code{conclusion}. With the addition of function
  14560. definitions, there is a start block and conclusion for each function,
  14561. but their labels need to be unique. We recommend prepending the
  14562. function's name to \code{start} and \code{conclusion}, respectively,
  14563. to obtain unique labels.
  14564. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14565. number of parameters the function expects, but the parameters are no
  14566. longer in the syntax of function definitions. Instead, add an entry
  14567. to $\itm{info}$ that maps \code{num-params} to the number of
  14568. parameters to construct $\itm{info}'$.}
  14569. By changing the parameters to local variables, we are giving the
  14570. register allocator control over which registers or stack locations to
  14571. use for them. If you implement the move-biasing challenge
  14572. (section~\ref{sec:move-biasing}), the register allocator will try to
  14573. assign the parameter variables to the corresponding argument register,
  14574. in which case the \code{patch\_instructions} pass will remove the
  14575. \code{movq} instruction. This happens in the example translation given
  14576. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14577. the \code{add} function.
  14578. %
  14579. Also, note that the register allocator will perform liveness analysis
  14580. on this sequence of move instructions and build the interference
  14581. graph. So, for example, $x_1$ will be marked as interfering with
  14582. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14583. which is good because otherwise the first \code{movq} would overwrite
  14584. the argument in \code{rsi} that is needed for $x_2$.
  14585. Next, consider the compilation of function calls. In the mirror image
  14586. of the handling of parameters in function definitions, the arguments
  14587. are moved to the argument-passing registers. Note that the function
  14588. is not given as a label, but its address is produced by the argument
  14589. $\itm{arg}_0$. So, we translate the call into an indirect function
  14590. call. The return value from the function is stored in \code{rax}, so
  14591. it needs to be moved into the \itm{lhs}.
  14592. \begin{lstlisting}
  14593. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14594. |$\Rightarrow$|
  14595. movq |$\itm{arg}_1$|, %rdi
  14596. movq |$\itm{arg}_2$|, %rsi
  14597. |$\vdots$|
  14598. callq *|$\itm{arg}_0$|
  14599. movq %rax, |$\itm{lhs}$|
  14600. \end{lstlisting}
  14601. The \code{IndirectCallq} AST node includes an integer for the arity of
  14602. the function, that is, the number of parameters. That information is
  14603. useful in the \code{uncover\_live} pass for determining which
  14604. argument-passing registers are potentially read during the call.
  14605. For tail calls, the parameter passing is the same as non-tail calls:
  14606. generate instructions to move the arguments into the argument-passing
  14607. registers. After that we need to pop the frame from the procedure
  14608. call stack. However, we do not yet know how big the frame is; that
  14609. gets determined during register allocation. So, instead of generating
  14610. those instructions here, we invent a new instruction that means ``pop
  14611. the frame and then do an indirect jump,'' which we name
  14612. \code{TailJmp}. The abstract syntax for this instruction includes an
  14613. argument that specifies where to jump and an integer that represents
  14614. the arity of the function being called.
  14615. \section{Register Allocation}
  14616. \label{sec:register-allocation-r4}
  14617. The addition of functions requires some changes to all three aspects
  14618. of register allocation, which we discuss in the following subsections.
  14619. \subsection{Liveness Analysis}
  14620. \label{sec:liveness-analysis-r4}
  14621. \index{subject}{liveness analysis}
  14622. %% The rest of the passes need only minor modifications to handle the new
  14623. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14624. %% \code{leaq}.
  14625. The \code{IndirectCallq} instruction should be treated like
  14626. \code{Callq} regarding its written locations $W$, in that they should
  14627. include all the caller-saved registers. Recall that the reason for
  14628. that is to force variables that are live across a function call to be assigned to callee-saved
  14629. registers or to be spilled to the stack.
  14630. Regarding the set of read locations $R$, the arity field of
  14631. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14632. argument-passing registers should be considered as read by those
  14633. instructions. Also, the target field of \code{TailJmp} and
  14634. \code{IndirectCallq} should be included in the set of read locations
  14635. $R$.
  14636. \subsection{Build Interference Graph}
  14637. \label{sec:build-interference-r4}
  14638. With the addition of function definitions, we compute a separate interference
  14639. graph for each function (not just one for the whole program).
  14640. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14641. spill tuple-typed variables that are live during a call to
  14642. \code{collect}, the garbage collector. With the addition of functions
  14643. to our language, we need to revisit this issue. Functions that perform
  14644. allocation contain calls to the collector. Thus, we should not only
  14645. spill a tuple-typed variable when it is live during a call to
  14646. \code{collect}, but we should spill the variable if it is live during
  14647. call to any user-defined function. Thus, in the
  14648. \code{build\_interference} pass, we recommend adding interference
  14649. edges between call-live tuple-typed variables and the callee-saved
  14650. registers (in addition to the usual addition of edges between
  14651. call-live variables and the caller-saved registers).
  14652. \subsection{Allocate Registers}
  14653. The primary change to the \code{allocate\_registers} pass is adding an
  14654. auxiliary function for handling definitions (the \Def{} nonterminal
  14655. shown in figure~\ref{fig:x86-3}) with one case for function
  14656. definitions. The logic is the same as described in
  14657. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14658. allocation is performed many times, once for each function definition,
  14659. instead of just once for the whole program.
  14660. \section{Patch Instructions}
  14661. In \code{patch\_instructions}, you should deal with the x86
  14662. idiosyncrasy that the destination argument of \code{leaq} must be a
  14663. register. Additionally, you should ensure that the argument of
  14664. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14665. trample many other registers before the tail call, as explained in the
  14666. next section.
  14667. \section{Prelude and Conclusion}
  14668. Now that register allocation is complete, we can translate the
  14669. \code{TailJmp} into a sequence of instructions. A naive translation of
  14670. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14671. before the jump we need to pop the current frame to achieve efficient
  14672. tail calls. This sequence of instructions is the same as the code for
  14673. the conclusion of a function, except that the \code{retq} is replaced with
  14674. \code{jmp *$\itm{arg}$}.
  14675. Regarding function definitions, we generate a prelude and conclusion
  14676. for each one. This code is similar to the prelude and conclusion
  14677. generated for the \code{main} function presented in
  14678. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14679. carry out the following steps:
  14680. % TODO: .align the functions!
  14681. \begin{enumerate}
  14682. %% \item Start with \code{.global} and \code{.align} directives followed
  14683. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14684. %% example.)
  14685. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14686. pointer.
  14687. \item Push to the stack all the callee-saved registers that were
  14688. used for register allocation.
  14689. \item Move the stack pointer \code{rsp} down to make room for the
  14690. regular spills (aligned to 16 bytes).
  14691. \item Move the root stack pointer \code{r15} up by the size of the
  14692. root-stack frame for this function, which depends on the number of
  14693. spilled tuple-typed variables. \label{root-stack-init}
  14694. \item Initialize to zero all new entries in the root-stack frame.
  14695. \item Jump to the start block.
  14696. \end{enumerate}
  14697. The prelude of the \code{main} function has an additional task: call
  14698. the \code{initialize} function to set up the garbage collector, and
  14699. then move the value of the global \code{rootstack\_begin} in
  14700. \code{r15}. This initialization should happen before step
  14701. \ref{root-stack-init}, which depends on \code{r15}.
  14702. The conclusion of every function should do the following:
  14703. \begin{enumerate}
  14704. \item Move the stack pointer back up past the regular spills.
  14705. \item Restore the callee-saved registers by popping them from the
  14706. stack.
  14707. \item Move the root stack pointer back down by the size of the
  14708. root-stack frame for this function.
  14709. \item Restore \code{rbp} by popping it from the stack.
  14710. \item Return to the caller with the \code{retq} instruction.
  14711. \end{enumerate}
  14712. The output of this pass is \LangXIndCallFlat{}, which differs from
  14713. \LangXIndCall{} in that there is no longer an AST node for function
  14714. definitions. Instead, a program is just an association list of basic
  14715. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14716. \[
  14717. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14718. \]
  14719. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14720. compiling \LangFun{} to x86.
  14721. \begin{exercise}\normalfont\normalsize
  14722. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14723. Create eight new programs that use functions, including examples that
  14724. pass functions and return functions from other functions, recursive
  14725. functions, functions that create vectors, and functions that make tail
  14726. calls. Test your compiler on these new programs and all your
  14727. previously created test programs.
  14728. \end{exercise}
  14729. \begin{figure}[tbp]
  14730. \begin{tcolorbox}[colback=white]
  14731. {\if\edition\racketEd
  14732. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14733. \node (Lfun) at (0,2) {\large \LangFun{}};
  14734. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14735. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14736. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14737. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14738. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14739. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14740. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14741. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14742. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14743. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14744. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14745. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14746. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14747. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14748. \path[->,bend left=15] (Lfun) edge [above] node
  14749. {\ttfamily\footnotesize shrink} (Lfun-1);
  14750. \path[->,bend left=15] (Lfun-1) edge [above] node
  14751. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14752. \path[->,bend left=15] (Lfun-2) edge [above] node
  14753. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14754. \path[->,bend left=15] (F1-1) edge [left] node
  14755. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14756. \path[->,bend left=15] (F1-2) edge [below] node
  14757. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14758. \path[->,bend left=15] (F1-3) edge [below] node
  14759. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14760. \path[->,bend right=15] (F1-4) edge [above] node
  14761. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14762. \path[->,bend right=15] (F1-5) edge [right] node
  14763. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14764. \path[->,bend right=15] (C3-2) edge [right] node
  14765. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14766. \path[->,bend left=15] (x86-2) edge [right] node
  14767. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14768. \path[->,bend right=15] (x86-2-1) edge [below] node
  14769. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14770. \path[->,bend right=15] (x86-2-2) edge [right] node
  14771. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14772. \path[->,bend left=15] (x86-3) edge [above] node
  14773. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14774. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14775. \end{tikzpicture}
  14776. \fi}
  14777. {\if\edition\pythonEd\pythonColor
  14778. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14779. \node (Lfun) at (0,2) {\large \LangFun{}};
  14780. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14781. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14782. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14783. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14784. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14785. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14786. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14787. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14788. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14789. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14790. \path[->,bend left=15] (Lfun) edge [above] node
  14791. {\ttfamily\footnotesize shrink} (Lfun-2);
  14792. \path[->,bend left=15] (Lfun-2) edge [above] node
  14793. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14794. \path[->,bend left=15] (F1-1) edge [above] node
  14795. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14796. \path[->,bend left=15] (F1-2) edge [right] node
  14797. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14798. \path[->,bend right=15] (F1-4) edge [above] node
  14799. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14800. \path[->,bend right=15] (F1-5) edge [right] node
  14801. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14802. \path[->,bend left=15] (C3-2) edge [right] node
  14803. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14804. \path[->,bend right=15] (x86-2) edge [below] node
  14805. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14806. \path[->,bend left=15] (x86-3) edge [above] node
  14807. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14808. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14809. \end{tikzpicture}
  14810. \fi}
  14811. \end{tcolorbox}
  14812. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14813. \label{fig:Lfun-passes}
  14814. \end{figure}
  14815. \section{An Example Translation}
  14816. \label{sec:functions-example}
  14817. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14818. function in \LangFun{} to x86. The figure also includes the results of the
  14819. \code{explicate\_control} and \code{select\_instructions} passes.
  14820. \begin{figure}[htbp]
  14821. \begin{tcolorbox}[colback=white]
  14822. \begin{tabular}{ll}
  14823. \begin{minipage}{0.4\textwidth}
  14824. % s3_2.rkt
  14825. {\if\edition\racketEd
  14826. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14827. (define (add [x : Integer]
  14828. [y : Integer])
  14829. : Integer
  14830. (+ x y))
  14831. (add 40 2)
  14832. \end{lstlisting}
  14833. \fi}
  14834. {\if\edition\pythonEd\pythonColor
  14835. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14836. def add(x:int, y:int) -> int:
  14837. return x + y
  14838. print(add(40, 2))
  14839. \end{lstlisting}
  14840. \fi}
  14841. $\Downarrow$
  14842. {\if\edition\racketEd
  14843. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14844. (define (add86 [x87 : Integer]
  14845. [y88 : Integer])
  14846. : Integer
  14847. add86start:
  14848. return (+ x87 y88);
  14849. )
  14850. (define (main) : Integer ()
  14851. mainstart:
  14852. tmp89 = (fun-ref add86 2);
  14853. (tail-call tmp89 40 2)
  14854. )
  14855. \end{lstlisting}
  14856. \fi}
  14857. {\if\edition\pythonEd\pythonColor
  14858. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14859. def add(x:int, y:int) -> int:
  14860. addstart:
  14861. return x + y
  14862. def main() -> int:
  14863. mainstart:
  14864. fun.0 = add
  14865. tmp.1 = fun.0(40, 2)
  14866. print(tmp.1)
  14867. return 0
  14868. \end{lstlisting}
  14869. \fi}
  14870. \end{minipage}
  14871. &
  14872. $\Rightarrow$
  14873. \begin{minipage}{0.5\textwidth}
  14874. {\if\edition\racketEd
  14875. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14876. (define (add86) : Integer
  14877. add86start:
  14878. movq %rdi, x87
  14879. movq %rsi, y88
  14880. movq x87, %rax
  14881. addq y88, %rax
  14882. jmp inc1389conclusion
  14883. )
  14884. (define (main) : Integer
  14885. mainstart:
  14886. leaq (fun-ref add86 2), tmp89
  14887. movq $40, %rdi
  14888. movq $2, %rsi
  14889. tail-jmp tmp89
  14890. )
  14891. \end{lstlisting}
  14892. \fi}
  14893. {\if\edition\pythonEd\pythonColor
  14894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14895. def add() -> int:
  14896. addstart:
  14897. movq %rdi, x
  14898. movq %rsi, y
  14899. movq x, %rax
  14900. addq y, %rax
  14901. jmp addconclusion
  14902. def main() -> int:
  14903. mainstart:
  14904. leaq add, fun.0
  14905. movq $40, %rdi
  14906. movq $2, %rsi
  14907. callq *fun.0
  14908. movq %rax, tmp.1
  14909. movq tmp.1, %rdi
  14910. callq print_int
  14911. movq $0, %rax
  14912. jmp mainconclusion
  14913. \end{lstlisting}
  14914. \fi}
  14915. $\Downarrow$
  14916. \end{minipage}
  14917. \end{tabular}
  14918. \begin{tabular}{ll}
  14919. \begin{minipage}{0.3\textwidth}
  14920. {\if\edition\racketEd
  14921. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14922. .globl add86
  14923. .align 8
  14924. add86:
  14925. pushq %rbp
  14926. movq %rsp, %rbp
  14927. jmp add86start
  14928. add86start:
  14929. movq %rdi, %rax
  14930. addq %rsi, %rax
  14931. jmp add86conclusion
  14932. add86conclusion:
  14933. popq %rbp
  14934. retq
  14935. \end{lstlisting}
  14936. \fi}
  14937. {\if\edition\pythonEd\pythonColor
  14938. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14939. .align 8
  14940. add:
  14941. pushq %rbp
  14942. movq %rsp, %rbp
  14943. subq $0, %rsp
  14944. jmp addstart
  14945. addstart:
  14946. movq %rdi, %rdx
  14947. movq %rsi, %rcx
  14948. movq %rdx, %rax
  14949. addq %rcx, %rax
  14950. jmp addconclusion
  14951. addconclusion:
  14952. subq $0, %r15
  14953. addq $0, %rsp
  14954. popq %rbp
  14955. retq
  14956. \end{lstlisting}
  14957. \fi}
  14958. \end{minipage}
  14959. &
  14960. \begin{minipage}{0.5\textwidth}
  14961. {\if\edition\racketEd
  14962. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14963. .globl main
  14964. .align 8
  14965. main:
  14966. pushq %rbp
  14967. movq %rsp, %rbp
  14968. movq $16384, %rdi
  14969. movq $16384, %rsi
  14970. callq initialize
  14971. movq rootstack_begin(%rip), %r15
  14972. jmp mainstart
  14973. mainstart:
  14974. leaq add86(%rip), %rcx
  14975. movq $40, %rdi
  14976. movq $2, %rsi
  14977. movq %rcx, %rax
  14978. popq %rbp
  14979. jmp *%rax
  14980. mainconclusion:
  14981. popq %rbp
  14982. retq
  14983. \end{lstlisting}
  14984. \fi}
  14985. {\if\edition\pythonEd\pythonColor
  14986. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14987. .globl main
  14988. .align 8
  14989. main:
  14990. pushq %rbp
  14991. movq %rsp, %rbp
  14992. subq $0, %rsp
  14993. movq $65536, %rdi
  14994. movq $65536, %rsi
  14995. callq initialize
  14996. movq rootstack_begin(%rip), %r15
  14997. jmp mainstart
  14998. mainstart:
  14999. leaq add(%rip), %rcx
  15000. movq $40, %rdi
  15001. movq $2, %rsi
  15002. callq *%rcx
  15003. movq %rax, %rcx
  15004. movq %rcx, %rdi
  15005. callq print_int
  15006. movq $0, %rax
  15007. jmp mainconclusion
  15008. mainconclusion:
  15009. subq $0, %r15
  15010. addq $0, %rsp
  15011. popq %rbp
  15012. retq
  15013. \end{lstlisting}
  15014. \fi}
  15015. \end{minipage}
  15016. \end{tabular}
  15017. \end{tcolorbox}
  15018. \caption{Example compilation of a simple function to x86.}
  15019. \label{fig:add-fun}
  15020. \end{figure}
  15021. % Challenge idea: inlining! (simple version)
  15022. % Further Reading
  15023. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15024. \chapter{Lexically Scoped Functions}
  15025. \label{ch:Llambda}
  15026. \index{subject}{lambda}
  15027. \index{subject}{lexical scoping}
  15028. \setcounter{footnote}{0}
  15029. This chapter studies lexically scoped functions. Lexical scoping means
  15030. that a function's body may refer to variables whose binding site is
  15031. outside of the function, in an enclosing scope.
  15032. %
  15033. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15034. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  15035. creating lexically scoped functions. The body of the \key{lambda}
  15036. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  15037. binding sites for \code{x} and \code{y} are outside of the
  15038. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  15039. \key{let}}\python{a local variable of function \code{f}}, and
  15040. \code{x} is a parameter of function \code{f}. Note that function
  15041. \code{f} returns the \key{lambda} as its result value. The main
  15042. expression of the program includes two calls to \code{f} with
  15043. different arguments for \code{x}: first \code{5} and then \code{3}. The
  15044. functions returned from \code{f} are bound to variables \code{g} and
  15045. \code{h}. Even though these two functions were created by the same
  15046. \code{lambda}, they are really different functions because they use
  15047. different values for \code{x}. Applying \code{g} to \code{11} produces
  15048. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  15049. so the result of the program is \code{42}.
  15050. \begin{figure}[btp]
  15051. \begin{tcolorbox}[colback=white]
  15052. {\if\edition\racketEd
  15053. % lambda_test_21.rkt
  15054. \begin{lstlisting}
  15055. (define (f [x : Integer]) : (Integer -> Integer)
  15056. (let ([y 4])
  15057. (lambda: ([z : Integer]) : Integer
  15058. (+ x (+ y z)))))
  15059. (let ([g (f 5)])
  15060. (let ([h (f 3)])
  15061. (+ (g 11) (h 15))))
  15062. \end{lstlisting}
  15063. \fi}
  15064. {\if\edition\pythonEd\pythonColor
  15065. \begin{lstlisting}
  15066. def f(x : int) -> Callable[[int], int]:
  15067. y = 4
  15068. return lambda z: x + y + z
  15069. g = f(5)
  15070. h = f(3)
  15071. print( g(11) + h(15) )
  15072. \end{lstlisting}
  15073. \fi}
  15074. \end{tcolorbox}
  15075. \caption{Example of a lexically scoped function.}
  15076. \label{fig:lexical-scoping}
  15077. \end{figure}
  15078. The approach that we take for implementing lexically scoped functions
  15079. is to compile them into top-level function definitions, translating
  15080. from \LangLam{} into \LangFun{}. However, the compiler must give
  15081. special treatment to variable occurrences such as \code{x} and
  15082. \code{y} in the body of the \code{lambda} shown in
  15083. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15084. may not refer to variables defined outside of it. To identify such
  15085. variable occurrences, we review the standard notion of free variable.
  15086. \begin{definition}\normalfont
  15087. A variable is \emph{free in expression} $e$ if the variable occurs
  15088. inside $e$ but does not have an enclosing definition that is also in
  15089. $e$.\index{subject}{free variable}
  15090. \end{definition}
  15091. For example, in the expression
  15092. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15093. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15094. only \code{x} and \code{y} are free in the following expression,
  15095. because \code{z} is defined by the \code{lambda}
  15096. {\if\edition\racketEd
  15097. \begin{lstlisting}
  15098. (lambda: ([z : Integer]) : Integer
  15099. (+ x (+ y z)))
  15100. \end{lstlisting}
  15101. \fi}
  15102. {\if\edition\pythonEd\pythonColor
  15103. \begin{lstlisting}
  15104. lambda z: x + y + z
  15105. \end{lstlisting}
  15106. \fi}
  15107. %
  15108. \noindent Thus the free variables of a \code{lambda} are the ones that
  15109. need special treatment. We need to transport at runtime the values
  15110. of those variables from the point where the \code{lambda} was created
  15111. to the point where the \code{lambda} is applied. An efficient solution
  15112. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15113. values of the free variables together with a function pointer into a
  15114. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15115. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15116. closure}
  15117. %
  15118. By design, we have all the ingredients to make closures:
  15119. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15120. function pointers. The function pointer resides at index $0$, and the
  15121. values for the free variables fill in the rest of the tuple.
  15122. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15123. to see how closures work. It is a three-step dance. The program calls
  15124. function \code{f}, which creates a closure for the \code{lambda}. The
  15125. closure is a tuple whose first element is a pointer to the top-level
  15126. function that we will generate for the \code{lambda}; the second
  15127. element is the value of \code{x}, which is \code{5}; and the third
  15128. element is \code{4}, the value of \code{y}. The closure does not
  15129. contain an element for \code{z} because \code{z} is not a free
  15130. variable of the \code{lambda}. Creating the closure is step 1 of the
  15131. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15132. shown in figure~\ref{fig:closures}.
  15133. %
  15134. The second call to \code{f} creates another closure, this time with
  15135. \code{3} in the second slot (for \code{x}). This closure is also
  15136. returned from \code{f} but bound to \code{h}, which is also shown in
  15137. figure~\ref{fig:closures}.
  15138. \begin{figure}[tbp]
  15139. \centering
  15140. \begin{minipage}{0.65\textwidth}
  15141. \begin{tcolorbox}[colback=white]
  15142. \includegraphics[width=\textwidth]{figs/closures}
  15143. \end{tcolorbox}
  15144. \end{minipage}
  15145. \caption{Flat closure representations for the two functions
  15146. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15147. \label{fig:closures}
  15148. \end{figure}
  15149. Continuing with the example, consider the application of \code{g} to
  15150. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15151. closure, we obtain the function pointer from the first element of the
  15152. closure and call it, passing in the closure itself and then the
  15153. regular arguments, in this case \code{11}. This technique for applying
  15154. a closure is step 2 of the dance.
  15155. %
  15156. But doesn't this \code{lambda} take only one argument, for parameter
  15157. \code{z}? The third and final step of the dance is generating a
  15158. top-level function for a \code{lambda}. We add an additional
  15159. parameter for the closure and insert an initialization at the beginning
  15160. of the function for each free variable, to bind those variables to the
  15161. appropriate elements from the closure parameter.
  15162. %
  15163. This three-step dance is known as \emph{closure conversion}. We
  15164. discuss the details of closure conversion in
  15165. section~\ref{sec:closure-conversion} and show the code generated from
  15166. the example in section~\ref{sec:example-lambda}. First, we define
  15167. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  15168. \section{The \LangLam{} Language}
  15169. \label{sec:r5}
  15170. The definitions of the concrete syntax and abstract syntax for
  15171. \LangLam{}, a language with anonymous functions and lexical scoping,
  15172. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15173. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15174. for \LangFun{}, which already has syntax for function application.
  15175. %
  15176. \python{The syntax also includes an assignment statement that includes
  15177. a type annotation for the variable on the left-hand side, which
  15178. facilitates the type checking of \code{lambda} expressions that we
  15179. discuss later in this section.}
  15180. %
  15181. \racket{The \code{procedure-arity} operation returns the number of parameters
  15182. of a given function, an operation that we need for the translation
  15183. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15184. %
  15185. \python{The \code{arity} operation returns the number of parameters of
  15186. a given function, an operation that we need for the translation
  15187. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15188. The \code{arity} operation is not in Python, but the same functionality
  15189. is available in a more complex form. We include \code{arity} in the
  15190. \LangLam{} source language to enable testing.}
  15191. \newcommand{\LlambdaGrammarRacket}{
  15192. \begin{array}{lcl}
  15193. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15194. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15195. \end{array}
  15196. }
  15197. \newcommand{\LlambdaASTRacket}{
  15198. \begin{array}{lcl}
  15199. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15200. \itm{op} &::=& \code{procedure-arity}
  15201. \end{array}
  15202. }
  15203. \newcommand{\LlambdaGrammarPython}{
  15204. \begin{array}{lcl}
  15205. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15206. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15207. \end{array}
  15208. }
  15209. \newcommand{\LlambdaASTPython}{
  15210. \begin{array}{lcl}
  15211. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15212. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15213. \end{array}
  15214. }
  15215. % include AnnAssign in ASTPython
  15216. \begin{figure}[tp]
  15217. \centering
  15218. \begin{tcolorbox}[colback=white]
  15219. \small
  15220. {\if\edition\racketEd
  15221. \[
  15222. \begin{array}{l}
  15223. \gray{\LintGrammarRacket{}} \\ \hline
  15224. \gray{\LvarGrammarRacket{}} \\ \hline
  15225. \gray{\LifGrammarRacket{}} \\ \hline
  15226. \gray{\LwhileGrammarRacket} \\ \hline
  15227. \gray{\LtupGrammarRacket} \\ \hline
  15228. \gray{\LfunGrammarRacket} \\ \hline
  15229. \LlambdaGrammarRacket \\
  15230. \begin{array}{lcl}
  15231. \LangLamM{} &::=& \Def\ldots \; \Exp
  15232. \end{array}
  15233. \end{array}
  15234. \]
  15235. \fi}
  15236. {\if\edition\pythonEd\pythonColor
  15237. \[
  15238. \begin{array}{l}
  15239. \gray{\LintGrammarPython{}} \\ \hline
  15240. \gray{\LvarGrammarPython{}} \\ \hline
  15241. \gray{\LifGrammarPython{}} \\ \hline
  15242. \gray{\LwhileGrammarPython} \\ \hline
  15243. \gray{\LtupGrammarPython} \\ \hline
  15244. \gray{\LfunGrammarPython} \\ \hline
  15245. \LlambdaGrammarPython \\
  15246. \begin{array}{lcl}
  15247. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15248. \end{array}
  15249. \end{array}
  15250. \]
  15251. \fi}
  15252. \end{tcolorbox}
  15253. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15254. with \key{lambda}.}
  15255. \label{fig:Llam-concrete-syntax}
  15256. \end{figure}
  15257. \begin{figure}[tp]
  15258. \centering
  15259. \begin{tcolorbox}[colback=white]
  15260. \small
  15261. {\if\edition\racketEd
  15262. \[\arraycolsep=3pt
  15263. \begin{array}{l}
  15264. \gray{\LintOpAST} \\ \hline
  15265. \gray{\LvarASTRacket{}} \\ \hline
  15266. \gray{\LifASTRacket{}} \\ \hline
  15267. \gray{\LwhileASTRacket{}} \\ \hline
  15268. \gray{\LtupASTRacket{}} \\ \hline
  15269. \gray{\LfunASTRacket} \\ \hline
  15270. \LlambdaASTRacket \\
  15271. \begin{array}{lcl}
  15272. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15273. \end{array}
  15274. \end{array}
  15275. \]
  15276. \fi}
  15277. {\if\edition\pythonEd\pythonColor
  15278. \[
  15279. \begin{array}{l}
  15280. \gray{\LintASTPython} \\ \hline
  15281. \gray{\LvarASTPython{}} \\ \hline
  15282. \gray{\LifASTPython{}} \\ \hline
  15283. \gray{\LwhileASTPython{}} \\ \hline
  15284. \gray{\LtupASTPython{}} \\ \hline
  15285. \gray{\LfunASTPython} \\ \hline
  15286. \LlambdaASTPython \\
  15287. \begin{array}{lcl}
  15288. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15289. \end{array}
  15290. \end{array}
  15291. \]
  15292. \fi}
  15293. \end{tcolorbox}
  15294. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15295. \label{fig:Llam-syntax}
  15296. \end{figure}
  15297. \index{subject}{interpreter}
  15298. \label{sec:interp-Llambda}
  15299. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  15300. \LangLam{}. The case for \key{Lambda} saves the current environment
  15301. inside the returned function value. Recall that during function
  15302. application, the environment stored in the function value, extended
  15303. with the mapping of parameters to argument values, is used to
  15304. interpret the body of the function.
  15305. \begin{figure}[tbp]
  15306. \begin{tcolorbox}[colback=white]
  15307. {\if\edition\racketEd
  15308. \begin{lstlisting}
  15309. (define interp-Llambda-class
  15310. (class interp-Lfun-class
  15311. (super-new)
  15312. (define/override (interp-op op)
  15313. (match op
  15314. ['procedure-arity
  15315. (lambda (v)
  15316. (match v
  15317. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15318. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15319. [else (super interp-op op)]))
  15320. (define/override ((interp-exp env) e)
  15321. (define recur (interp-exp env))
  15322. (match e
  15323. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15324. `(function ,xs ,body ,env)]
  15325. [else ((super interp-exp env) e)]))
  15326. ))
  15327. (define (interp-Llambda p)
  15328. (send (new interp-Llambda-class) interp-program p))
  15329. \end{lstlisting}
  15330. \fi}
  15331. {\if\edition\pythonEd\pythonColor
  15332. \begin{lstlisting}
  15333. class InterpLlambda(InterpLfun):
  15334. def arity(self, v):
  15335. match v:
  15336. case Function(name, params, body, env):
  15337. return len(params)
  15338. case _:
  15339. raise Exception('Llambda arity unexpected ' + repr(v))
  15340. def interp_exp(self, e, env):
  15341. match e:
  15342. case Call(Name('arity'), [fun]):
  15343. f = self.interp_exp(fun, env)
  15344. return self.arity(f)
  15345. case Lambda(params, body):
  15346. return Function('lambda', params, [Return(body)], env)
  15347. case _:
  15348. return super().interp_exp(e, env)
  15349. def interp_stmts(self, ss, env):
  15350. if len(ss) == 0:
  15351. return
  15352. match ss[0]:
  15353. case AnnAssign(lhs, typ, value, simple):
  15354. env[lhs.id] = self.interp_exp(value, env)
  15355. return self.interp_stmts(ss[1:], env)
  15356. case _:
  15357. return super().interp_stmts(ss, env)
  15358. \end{lstlisting}
  15359. \fi}
  15360. \end{tcolorbox}
  15361. \caption{Interpreter for \LangLam{}.}
  15362. \label{fig:interp-Llambda}
  15363. \end{figure}
  15364. \label{sec:type-check-r5}
  15365. \index{subject}{type checking}
  15366. {\if\edition\racketEd
  15367. %
  15368. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15369. \key{lambda} form. The body of the \key{lambda} is checked in an
  15370. environment that includes the current environment (because it is
  15371. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15372. require the body's type to match the declared return type.
  15373. %
  15374. \fi}
  15375. {\if\edition\pythonEd\pythonColor
  15376. %
  15377. Figures~\ref{fig:type-check-Llambda} and
  15378. \ref{fig:type-check-Llambda-part2} define the type checker for
  15379. \LangLam{}, which is more complex than one might expect. The reason
  15380. for the added complexity is that the syntax of \key{lambda} does not
  15381. include type annotations for the parameters or return type. Instead
  15382. they must be inferred. There are many approaches of type inference to
  15383. choose from of varying degrees of complexity. We choose one of the
  15384. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15385. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15386. this book is compilation, not type inference.
  15387. The main idea of bidirectional type inference is to add an auxiliary
  15388. function, here named \code{check\_exp}, that takes an expected type
  15389. and checks whether the given expression is of that type. Thus, in
  15390. \code{check\_exp}, type information flows in a top-down manner with
  15391. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15392. function, where type information flows in a primarily bottom-up
  15393. manner.
  15394. %
  15395. The idea then is to use \code{check\_exp} in all the places where we
  15396. already know what the type of an expression should be, such as in the
  15397. \code{return} statement of a top-level function definition, or on the
  15398. right-hand side of an annotated assignment statement.
  15399. Getting back to \code{lambda}, it is straightforward to check a
  15400. \code{lambda} inside \code{check\_exp} because the expected type
  15401. provides the parameter types and the return type. On the other hand,
  15402. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15403. that we do not allow \code{lambda} in contexts where we don't already
  15404. know its type. This restriction does not incur a loss of
  15405. expressiveness for \LangLam{} because it is straightforward to modify
  15406. a program to sidestep the restriction, for example, by using an
  15407. annotated assignment statement to assign the \code{lambda} to a
  15408. temporary variable.
  15409. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15410. checker records their type in a \code{has\_type} field. This type
  15411. information is used later in this chapter.
  15412. %
  15413. \fi}
  15414. \begin{figure}[tbp]
  15415. \begin{tcolorbox}[colback=white]
  15416. {\if\edition\racketEd
  15417. \begin{lstlisting}
  15418. (define (type-check-Llambda env)
  15419. (lambda (e)
  15420. (match e
  15421. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15422. (define-values (new-body bodyT)
  15423. ((type-check-exp (append (map cons xs Ts) env)) body))
  15424. (define ty `(,@Ts -> ,rT))
  15425. (cond
  15426. [(equal? rT bodyT)
  15427. (values (HasType (Lambda params rT new-body) ty) ty)]
  15428. [else
  15429. (error "mismatch in return type" bodyT rT)])]
  15430. ...
  15431. )))
  15432. \end{lstlisting}
  15433. \fi}
  15434. {\if\edition\pythonEd\pythonColor
  15435. \begin{lstlisting}
  15436. class TypeCheckLlambda(TypeCheckLfun):
  15437. def type_check_exp(self, e, env):
  15438. match e:
  15439. case Name(id):
  15440. e.has_type = env[id]
  15441. return env[id]
  15442. case Lambda(params, body):
  15443. raise Exception('cannot synthesize a type for a lambda')
  15444. case Call(Name('arity'), [func]):
  15445. func_t = self.type_check_exp(func, env)
  15446. match func_t:
  15447. case FunctionType(params_t, return_t):
  15448. return IntType()
  15449. case _:
  15450. raise Exception('in arity, unexpected ' + repr(func_t))
  15451. case _:
  15452. return super().type_check_exp(e, env)
  15453. def check_exp(self, e, ty, env):
  15454. match e:
  15455. case Lambda(params, body):
  15456. e.has_type = ty
  15457. match ty:
  15458. case FunctionType(params_t, return_t):
  15459. new_env = env.copy().update(zip(params, params_t))
  15460. self.check_exp(body, return_t, new_env)
  15461. case _:
  15462. raise Exception('lambda does not have type ' + str(ty))
  15463. case Call(func, args):
  15464. func_t = self.type_check_exp(func, env)
  15465. match func_t:
  15466. case FunctionType(params_t, return_t):
  15467. for (arg, param_t) in zip(args, params_t):
  15468. self.check_exp(arg, param_t, env)
  15469. self.check_type_equal(return_t, ty, e)
  15470. case _:
  15471. raise Exception('type_check_exp: in call, unexpected ' + \
  15472. repr(func_t))
  15473. case _:
  15474. t = self.type_check_exp(e, env)
  15475. self.check_type_equal(t, ty, e)
  15476. \end{lstlisting}
  15477. \fi}
  15478. \end{tcolorbox}
  15479. \caption{Type checking \LangLam{}\python{, part 1}.}
  15480. \label{fig:type-check-Llambda}
  15481. \end{figure}
  15482. {\if\edition\pythonEd\pythonColor
  15483. \begin{figure}[tbp]
  15484. \begin{tcolorbox}[colback=white]
  15485. \begin{lstlisting}
  15486. def check_stmts(self, ss, return_ty, env):
  15487. if len(ss) == 0:
  15488. return
  15489. match ss[0]:
  15490. case FunctionDef(name, params, body, dl, returns, comment):
  15491. new_env = env.copy().update(params)
  15492. rt = self.check_stmts(body, returns, new_env)
  15493. self.check_stmts(ss[1:], return_ty, env)
  15494. case Return(value):
  15495. self.check_exp(value, return_ty, env)
  15496. case Assign([Name(id)], value):
  15497. if id in env:
  15498. self.check_exp(value, env[id], env)
  15499. else:
  15500. env[id] = self.type_check_exp(value, env)
  15501. self.check_stmts(ss[1:], return_ty, env)
  15502. case Assign([Subscript(tup, Constant(index), Store())], value):
  15503. tup_t = self.type_check_exp(tup, env)
  15504. match tup_t:
  15505. case TupleType(ts):
  15506. self.check_exp(value, ts[index], env)
  15507. case _:
  15508. raise Exception('expected a tuple, not ' + repr(tup_t))
  15509. self.check_stmts(ss[1:], return_ty, env)
  15510. case AnnAssign(Name(id), ty_annot, value, simple):
  15511. ss[0].annotation = ty_annot
  15512. if id in env:
  15513. self.check_type_equal(env[id], ty_annot)
  15514. else:
  15515. env[id] = ty_annot
  15516. self.check_exp(value, ty_annot, env)
  15517. self.check_stmts(ss[1:], return_ty, env)
  15518. case _:
  15519. self.type_check_stmts(ss, env)
  15520. def type_check(self, p):
  15521. match p:
  15522. case Module(body):
  15523. env = {}
  15524. for s in body:
  15525. match s:
  15526. case FunctionDef(name, params, bod, dl, returns, comment):
  15527. params_t = [t for (x,t) in params]
  15528. env[name] = FunctionType(params_t, returns)
  15529. self.check_stmts(body, int, env)
  15530. \end{lstlisting}
  15531. \end{tcolorbox}
  15532. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15533. \label{fig:type-check-Llambda-part2}
  15534. \end{figure}
  15535. \fi}
  15536. \clearpage
  15537. \section{Assignment and Lexically Scoped Functions}
  15538. \label{sec:assignment-scoping}
  15539. The combination of lexically scoped functions and assignment to
  15540. variables raises a challenge with the flat-closure approach to
  15541. implementing lexically scoped functions. Consider the following
  15542. example in which function \code{f} has a free variable \code{x} that
  15543. is changed after \code{f} is created but before the call to \code{f}.
  15544. % loop_test_11.rkt
  15545. {\if\edition\racketEd
  15546. \begin{lstlisting}
  15547. (let ([x 0])
  15548. (let ([y 0])
  15549. (let ([z 20])
  15550. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15551. (begin
  15552. (set! x 10)
  15553. (set! y 12)
  15554. (f y))))))
  15555. \end{lstlisting}
  15556. \fi}
  15557. {\if\edition\pythonEd\pythonColor
  15558. % box_free_assign.py
  15559. \begin{lstlisting}
  15560. def g(z : int) -> int:
  15561. x = 0
  15562. y = 0
  15563. f : Callable[[int],int] = lambda a: a + x + z
  15564. x = 10
  15565. y = 12
  15566. return f(y)
  15567. print( g(20) )
  15568. \end{lstlisting}
  15569. \fi} The correct output for this example is \code{42} because the call
  15570. to \code{f} is required to use the current value of \code{x} (which is
  15571. \code{10}). Unfortunately, the closure conversion pass
  15572. (section~\ref{sec:closure-conversion}) generates code for the
  15573. \code{lambda} that copies the old value of \code{x} into a
  15574. closure. Thus, if we naively applied closure conversion, the output of
  15575. this program would be \code{32}.
  15576. A first attempt at solving this problem would be to save a pointer to
  15577. \code{x} in the closure and change the occurrences of \code{x} inside
  15578. the lambda to dereference the pointer. Of course, this would require
  15579. assigning \code{x} to the stack and not to a register. However, the
  15580. problem goes a bit deeper.
  15581. Consider the following example that returns a function that refers to
  15582. a local variable of the enclosing function:
  15583. \begin{center}
  15584. \begin{minipage}{\textwidth}
  15585. {\if\edition\racketEd
  15586. \begin{lstlisting}
  15587. (define (f []) : Integer
  15588. (let ([x 0])
  15589. (let ([g (lambda: () : Integer x)])
  15590. (begin
  15591. (set! x 42)
  15592. g))))
  15593. ((f))
  15594. \end{lstlisting}
  15595. \fi}
  15596. {\if\edition\pythonEd\pythonColor
  15597. % counter.py
  15598. \begin{lstlisting}
  15599. def f():
  15600. x = 0
  15601. g = lambda: x
  15602. x = 42
  15603. return g
  15604. print( f()() )
  15605. \end{lstlisting}
  15606. \fi}
  15607. \end{minipage}
  15608. \end{center}
  15609. In this example, the lifetime of \code{x} extends beyond the lifetime
  15610. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15611. stack frame for the call to \code{f}, it would be gone by the time we
  15612. called \code{g}, leaving us with dangling pointers for
  15613. \code{x}. This example demonstrates that when a variable occurs free
  15614. inside a function, its lifetime becomes indefinite. Thus, the value of
  15615. the variable needs to live on the heap. The verb
  15616. \emph{box}\index{subject}{box} is often used for allocating a single
  15617. value on the heap, producing a pointer, and
  15618. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15619. %
  15620. We introduce a new pass named \code{convert\_assignments} to address
  15621. this challenge.
  15622. %
  15623. \python{But before diving into that, we have one more
  15624. problem to discuss.}
  15625. {\if\edition\pythonEd\pythonColor
  15626. \section{Uniquify Variables}
  15627. \label{sec:uniquify-lambda}
  15628. With the addition of \code{lambda} we have a complication to deal
  15629. with: name shadowing. Consider the following program with a function
  15630. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15631. \code{lambda} expressions. The first \code{lambda} has a parameter
  15632. that is also named \code{x}.
  15633. \begin{lstlisting}
  15634. def f(x:int, y:int) -> Callable[[int], int]:
  15635. g : Callable[[int],int] = (lambda x: x + y)
  15636. h : Callable[[int],int] = (lambda y: x + y)
  15637. x = input_int()
  15638. return g
  15639. print(f(0, 10)(32))
  15640. \end{lstlisting}
  15641. Many of our compiler passes rely on being able to connect variable
  15642. uses with their definitions using just the name of the variable,
  15643. including new passes in this chapter. However, in the above example
  15644. the name of the variable does not uniquely determine its
  15645. definition. To solve this problem we recommend implementing a pass
  15646. named \code{uniquify} that renames every variable in the program to
  15647. make sure they are all unique.
  15648. The following shows the result of \code{uniquify} for the above
  15649. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15650. and the \code{x} parameter of the \code{lambda} is renamed to
  15651. \code{x\_4}.
  15652. \begin{lstlisting}
  15653. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15654. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15655. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15656. x_0 = input_int()
  15657. return g_2
  15658. def main() -> int :
  15659. print(f(0, 10)(32))
  15660. return 0
  15661. \end{lstlisting}
  15662. \fi} % pythonEd
  15663. %% \section{Reveal Functions}
  15664. %% \label{sec:reveal-functions-r5}
  15665. %% \racket{To support the \code{procedure-arity} operator we need to
  15666. %% communicate the arity of a function to the point of closure
  15667. %% creation.}
  15668. %% %
  15669. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15670. %% function at runtime. Thus, we need to communicate the arity of a
  15671. %% function to the point of closure creation.}
  15672. %% %
  15673. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15674. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15675. %% \[
  15676. %% \begin{array}{lcl}
  15677. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15678. %% \end{array}
  15679. %% \]
  15680. \section{Assignment Conversion}
  15681. \label{sec:convert-assignments}
  15682. The purpose of the \code{convert\_assignments} pass is to address the
  15683. challenge regarding the interaction between variable assignments and
  15684. closure conversion. First we identify which variables need to be
  15685. boxed, and then we transform the program to box those variables. In
  15686. general, boxing introduces runtime overhead that we would like to
  15687. avoid, so we should box as few variables as possible. We recommend
  15688. boxing the variables in the intersection of the following two sets of
  15689. variables:
  15690. \begin{enumerate}
  15691. \item The variables that are free in a \code{lambda}.
  15692. \item The variables that appear on the left-hand side of an
  15693. assignment.
  15694. \end{enumerate}
  15695. The first condition is a must but the second condition is
  15696. conservative. It is possible to develop a more liberal condition using
  15697. static program analysis.
  15698. Consider again the first example from
  15699. section~\ref{sec:assignment-scoping}:
  15700. %
  15701. {\if\edition\racketEd
  15702. \begin{lstlisting}
  15703. (let ([x 0])
  15704. (let ([y 0])
  15705. (let ([z 20])
  15706. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15707. (begin
  15708. (set! x 10)
  15709. (set! y 12)
  15710. (f y))))))
  15711. \end{lstlisting}
  15712. \fi}
  15713. {\if\edition\pythonEd\pythonColor
  15714. \begin{lstlisting}
  15715. def g(z : int) -> int:
  15716. x = 0
  15717. y = 0
  15718. f : Callable[[int],int] = lambda a: a + x + z
  15719. x = 10
  15720. y = 12
  15721. return f(y)
  15722. print( g(20) )
  15723. \end{lstlisting}
  15724. \fi}
  15725. %
  15726. \noindent The variables \code{x} and \code{y} are assigned to. The
  15727. variables \code{x} and \code{z} occur free inside the
  15728. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15729. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15730. transformations: initialize \code{x} with a tuple whose elements are
  15731. uninitialized, replace reads from \code{x} with tuple reads, and
  15732. replace each assignment to \code{x} with a tuple write. The output of
  15733. \code{convert\_assignments} for this example is as follows:
  15734. %
  15735. {\if\edition\racketEd
  15736. \begin{lstlisting}
  15737. (define (main) : Integer
  15738. (let ([x0 (vector 0)])
  15739. (let ([y1 0])
  15740. (let ([z2 20])
  15741. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15742. (+ a3 (+ (vector-ref x0 0) z2)))])
  15743. (begin
  15744. (vector-set! x0 0 10)
  15745. (set! y1 12)
  15746. (f4 y1)))))))
  15747. \end{lstlisting}
  15748. \fi}
  15749. %
  15750. {\if\edition\pythonEd\pythonColor
  15751. \begin{lstlisting}
  15752. def g(z : int)-> int:
  15753. x = (uninitialized(int),)
  15754. x[0] = 0
  15755. y = 0
  15756. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15757. x[0] = 10
  15758. y = 12
  15759. return f(y)
  15760. def main() -> int:
  15761. print(g(20))
  15762. return 0
  15763. \end{lstlisting}
  15764. \fi}
  15765. To compute the free variables of all the \code{lambda} expressions, we
  15766. recommend defining the following two auxiliary functions:
  15767. \begin{enumerate}
  15768. \item \code{free\_variables} computes the free variables of an expression, and
  15769. \item \code{free\_in\_lambda} collects all the variables that are
  15770. free in any of the \code{lambda} expressions, using
  15771. \code{free\_variables} in the case for each \code{lambda}.
  15772. \end{enumerate}
  15773. {\if\edition\racketEd
  15774. %
  15775. To compute the variables that are assigned to, we recommend updating
  15776. the \code{collect-set!} function that we introduced in
  15777. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15778. as \code{Lambda}.
  15779. %
  15780. \fi}
  15781. {\if\edition\pythonEd\pythonColor
  15782. %
  15783. To compute the variables that are assigned to, we recommend defining
  15784. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15785. the set of variables that occur in the left-hand side of an assignment
  15786. statement, and otherwise returns the empty set.
  15787. %
  15788. \fi}
  15789. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15790. free in a \code{lambda} and that are assigned to in the enclosing
  15791. function definition.
  15792. Next we discuss the \code{convert\_assignments} pass. In the case for
  15793. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15794. $\VAR{x}$ to a tuple read.
  15795. %
  15796. {\if\edition\racketEd
  15797. \begin{lstlisting}
  15798. (Var |$x$|)
  15799. |$\Rightarrow$|
  15800. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15801. \end{lstlisting}
  15802. \fi}
  15803. %
  15804. {\if\edition\pythonEd\pythonColor
  15805. \begin{lstlisting}
  15806. Name(|$x$|)
  15807. |$\Rightarrow$|
  15808. Subscript(Name(|$x$|), Constant(0), Load())
  15809. \end{lstlisting}
  15810. \fi}
  15811. %
  15812. \noindent In the case for assignment, recursively process the
  15813. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15814. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15815. as follows:
  15816. %
  15817. {\if\edition\racketEd
  15818. \begin{lstlisting}
  15819. (SetBang |$x$| |$\itm{rhs}$|)
  15820. |$\Rightarrow$|
  15821. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15822. \end{lstlisting}
  15823. \fi}
  15824. {\if\edition\pythonEd\pythonColor
  15825. \begin{lstlisting}
  15826. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15827. |$\Rightarrow$|
  15828. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15829. \end{lstlisting}
  15830. \fi}
  15831. %
  15832. {\if\edition\racketEd
  15833. The case for \code{Lambda} is nontrivial, but it is similar to the
  15834. case for function definitions, which we discuss next.
  15835. \fi}
  15836. %
  15837. To translate a function definition, we first compute $\mathit{AF}$,
  15838. the intersection of the variables that are free in a \code{lambda} and
  15839. that are assigned to. We then apply assignment conversion to the body
  15840. of the function definition. Finally, we box the parameters of this
  15841. function definition that are in $\mathit{AF}$. For example,
  15842. the parameter \code{x} of the following function \code{g}
  15843. needs to be boxed:
  15844. {\if\edition\racketEd
  15845. \begin{lstlisting}
  15846. (define (g [x : Integer]) : Integer
  15847. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15848. (begin
  15849. (set! x 10)
  15850. (f 32))))
  15851. \end{lstlisting}
  15852. \fi}
  15853. %
  15854. {\if\edition\pythonEd\pythonColor
  15855. \begin{lstlisting}
  15856. def g(x : int) -> int:
  15857. f : Callable[[int],int] = lambda a: a + x
  15858. x = 10
  15859. return f(32)
  15860. \end{lstlisting}
  15861. \fi}
  15862. %
  15863. \noindent We box parameter \code{x} by creating a local variable named
  15864. \code{x} that is initialized to a tuple whose contents is the value of
  15865. the parameter, which has been renamed to \code{x\_0}.
  15866. %
  15867. {\if\edition\racketEd
  15868. \begin{lstlisting}
  15869. (define (g [x_0 : Integer]) : Integer
  15870. (let ([x (vector x_0)])
  15871. (let ([f (lambda: ([a : Integer]) : Integer
  15872. (+ a (vector-ref x 0)))])
  15873. (begin
  15874. (vector-set! x 0 10)
  15875. (f 32)))))
  15876. \end{lstlisting}
  15877. \fi}
  15878. %
  15879. {\if\edition\pythonEd\pythonColor
  15880. \begin{lstlisting}
  15881. def g(x_0 : int)-> int:
  15882. x = (x_0,)
  15883. f : Callable[[int], int] = (lambda a: a + x[0])
  15884. x[0] = 10
  15885. return f(32)
  15886. \end{lstlisting}
  15887. \fi}
  15888. \section{Closure Conversion}
  15889. \label{sec:closure-conversion}
  15890. \index{subject}{closure conversion}
  15891. The compiling of lexically scoped functions into top-level function
  15892. definitions and flat closures is accomplished in the pass
  15893. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15894. and before \code{limit\_functions}.
  15895. As usual, we implement the pass as a recursive function over the
  15896. AST. The interesting cases are for \key{lambda} and function
  15897. application. We transform a \key{lambda} expression into an expression
  15898. that creates a closure, that is, a tuple for which the first element
  15899. is a function pointer and the rest of the elements are the values of
  15900. the free variables of the \key{lambda}.
  15901. %
  15902. However, we use the \code{Closure} AST node instead of using a tuple
  15903. so that we can record the arity.
  15904. %
  15905. In the generated code that follows, \itm{fvs} is the free variables of
  15906. the lambda and \itm{name} is a unique symbol generated to identify the
  15907. lambda.
  15908. %
  15909. \racket{The \itm{arity} is the number of parameters (the length of
  15910. \itm{ps}).}
  15911. %
  15912. {\if\edition\racketEd
  15913. \begin{lstlisting}
  15914. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15915. |$\Rightarrow$|
  15916. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15917. \end{lstlisting}
  15918. \fi}
  15919. %
  15920. {\if\edition\pythonEd\pythonColor
  15921. \begin{lstlisting}
  15922. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15923. |$\Rightarrow$|
  15924. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15925. \end{lstlisting}
  15926. \fi}
  15927. %
  15928. In addition to transforming each \key{Lambda} AST node into a
  15929. tuple, we create a top-level function definition for each
  15930. \key{Lambda}, as shown next.\\
  15931. \begin{minipage}{0.8\textwidth}
  15932. {\if\edition\racketEd
  15933. \begin{lstlisting}
  15934. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15935. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15936. ...
  15937. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15938. |\itm{body'}|)...))
  15939. \end{lstlisting}
  15940. \fi}
  15941. {\if\edition\pythonEd\pythonColor
  15942. \begin{lstlisting}
  15943. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15944. |$\itm{fvs}_1$| = clos[1]
  15945. |$\ldots$|
  15946. |$\itm{fvs}_n$| = clos[|$n$|]
  15947. |\itm{body'}|
  15948. \end{lstlisting}
  15949. \fi}
  15950. \end{minipage}\\
  15951. The \code{clos} parameter refers to the closure. Translate the type
  15952. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15953. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15954. \itm{closTy} is a tuple type for which the first element type is
  15955. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15956. the element types are the types of the free variables in the
  15957. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15958. is nontrivial to give a type to the function in the closure's type.%
  15959. %
  15960. \footnote{To give an accurate type to a closure, we would need to add
  15961. existential types to the type checker~\citep{Minamide:1996ys}.}
  15962. %
  15963. %% The dummy type is considered to be equal to any other type during type
  15964. %% checking.
  15965. The free variables become local variables that are initialized with
  15966. their values in the closure.
  15967. Closure conversion turns every function into a tuple, so the type
  15968. annotations in the program must also be translated. We recommend
  15969. defining an auxiliary recursive function for this purpose. Function
  15970. types should be translated as follows:
  15971. %
  15972. {\if\edition\racketEd
  15973. \begin{lstlisting}
  15974. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15975. |$\Rightarrow$|
  15976. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15977. \end{lstlisting}
  15978. \fi}
  15979. {\if\edition\pythonEd\pythonColor
  15980. \begin{lstlisting}
  15981. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15982. |$\Rightarrow$|
  15983. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15984. \end{lstlisting}
  15985. \fi}
  15986. %
  15987. This type indicates that the first thing in the tuple is a
  15988. function. The first parameter of the function is a tuple (a closure)
  15989. and the rest of the parameters are the ones from the original
  15990. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15991. omits the types of the free variables because (1) those types are not
  15992. available in this context, and (2) we do not need them in the code that
  15993. is generated for function application. So this type describes only the
  15994. first component of the closure tuple. At runtime the tuple may have
  15995. more components, but we ignore them at this point.
  15996. We transform function application into code that retrieves the
  15997. function from the closure and then calls the function, passing the
  15998. closure as the first argument. We place $e'$ in a temporary variable
  15999. to avoid code duplication.
  16000. \begin{center}
  16001. \begin{minipage}{\textwidth}
  16002. {\if\edition\racketEd
  16003. \begin{lstlisting}
  16004. (Apply |$e$| |$\itm{es}$|)
  16005. |$\Rightarrow$|
  16006. (Let |$\itm{tmp}$| |$e'$|
  16007. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16008. \end{lstlisting}
  16009. \fi}
  16010. %
  16011. {\if\edition\pythonEd\pythonColor
  16012. \begin{lstlisting}
  16013. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16014. |$\Rightarrow$|
  16015. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16016. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16017. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16018. \end{lstlisting}
  16019. \fi}
  16020. \end{minipage}
  16021. \end{center}
  16022. There is also the question of what to do with references to top-level
  16023. function definitions. To maintain a uniform translation of function
  16024. application, we turn function references into closures.
  16025. \begin{tabular}{lll}
  16026. \begin{minipage}{0.3\textwidth}
  16027. {\if\edition\racketEd
  16028. \begin{lstlisting}
  16029. (FunRef |$f$| |$n$|)
  16030. \end{lstlisting}
  16031. \fi}
  16032. {\if\edition\pythonEd\pythonColor
  16033. \begin{lstlisting}
  16034. FunRef(|$f$|, |$n$|)
  16035. \end{lstlisting}
  16036. \fi}
  16037. \end{minipage}
  16038. &
  16039. $\Rightarrow$
  16040. &
  16041. \begin{minipage}{0.5\textwidth}
  16042. {\if\edition\racketEd
  16043. \begin{lstlisting}
  16044. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16045. \end{lstlisting}
  16046. \fi}
  16047. {\if\edition\pythonEd\pythonColor
  16048. \begin{lstlisting}
  16049. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16050. \end{lstlisting}
  16051. \fi}
  16052. \end{minipage}
  16053. \end{tabular} \\
  16054. We no longer need the annotated assignment statement \code{AnnAssign}
  16055. to support the type checking of \code{lambda} expressions, so we
  16056. translate it to a regular \code{Assign} statement.
  16057. The top-level function definitions need to be updated to take an extra
  16058. closure parameter, but that parameter is ignored in the body of those
  16059. functions.
  16060. \section{An Example Translation}
  16061. \label{sec:example-lambda}
  16062. Figure~\ref{fig:lexical-functions-example} shows the result of
  16063. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16064. program demonstrating lexical scoping that we discussed at the
  16065. beginning of this chapter.
  16066. \begin{figure}[tbp]
  16067. \begin{tcolorbox}[colback=white]
  16068. \begin{minipage}{0.8\textwidth}
  16069. {\if\edition\racketEd
  16070. % tests/lambda_test_6.rkt
  16071. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16072. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16073. (let ([y8 4])
  16074. (lambda: ([z9 : Integer]) : Integer
  16075. (+ x7 (+ y8 z9)))))
  16076. (define (main) : Integer
  16077. (let ([g0 ((fun-ref f6 1) 5)])
  16078. (let ([h1 ((fun-ref f6 1) 3)])
  16079. (+ (g0 11) (h1 15)))))
  16080. \end{lstlisting}
  16081. $\Rightarrow$
  16082. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16083. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16084. (let ([y8 4])
  16085. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16086. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16087. (let ([x7 (vector-ref fvs3 1)])
  16088. (let ([y8 (vector-ref fvs3 2)])
  16089. (+ x7 (+ y8 z9)))))
  16090. (define (main) : Integer
  16091. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16092. ((vector-ref clos5 0) clos5 5))])
  16093. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16094. ((vector-ref clos6 0) clos6 3))])
  16095. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16096. \end{lstlisting}
  16097. \fi}
  16098. %
  16099. {\if\edition\pythonEd\pythonColor
  16100. % free_var.py
  16101. \begin{lstlisting}
  16102. def f(x : int) -> Callable[[int], int]:
  16103. y = 4
  16104. return lambda z: x + y + z
  16105. g = f(5)
  16106. h = f(3)
  16107. print( g(11) + h(15) )
  16108. \end{lstlisting}
  16109. $\Rightarrow$
  16110. \begin{lstlisting}
  16111. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16112. x = fvs_1[1]
  16113. y = fvs_1[2]
  16114. return x + y[0] + z
  16115. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16116. y = (777,)
  16117. y[0] = 4
  16118. return (lambda_0, x, y)
  16119. def main() -> int:
  16120. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16121. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16122. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16123. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16124. return 0
  16125. \end{lstlisting}
  16126. \fi}
  16127. \end{minipage}
  16128. \end{tcolorbox}
  16129. \caption{Example of closure conversion.}
  16130. \label{fig:lexical-functions-example}
  16131. \end{figure}
  16132. \begin{exercise}\normalfont\normalsize
  16133. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16134. Create five new programs that use \key{lambda} functions and make use of
  16135. lexical scoping. Test your compiler on these new programs and all
  16136. your previously created test programs.
  16137. \end{exercise}
  16138. \section{Expose Allocation}
  16139. \label{sec:expose-allocation-r5}
  16140. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16141. that allocates and initializes a tuple, similar to the translation of
  16142. the tuple creation in section~\ref{sec:expose-allocation}.
  16143. The only difference is replacing the use of
  16144. \ALLOC{\itm{len}}{\itm{type}} with
  16145. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16146. \section{Explicate Control and \LangCLam{}}
  16147. \label{sec:explicate-r5}
  16148. The output language of \code{explicate\_control} is \LangCLam{}; the
  16149. definition of its abstract syntax is shown in
  16150. figure~\ref{fig:Clam-syntax}.
  16151. %
  16152. \racket{The only differences with respect to \LangCFun{} are the
  16153. addition of the \code{AllocateClosure} form to the grammar for
  16154. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16155. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16156. similar to the handling of other expressions such as primitive
  16157. operators.}
  16158. %
  16159. \python{The differences with respect to \LangCFun{} are the
  16160. additions of \code{Uninitialized}, \code{AllocateClosure},
  16161. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16162. \code{explicate\_control} pass is similar to the handling of other
  16163. expressions such as primitive operators.}
  16164. \newcommand{\ClambdaASTRacket}{
  16165. \begin{array}{lcl}
  16166. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16167. \itm{op} &::= & \code{procedure-arity}
  16168. \end{array}
  16169. }
  16170. \newcommand{\ClambdaASTPython}{
  16171. \begin{array}{lcl}
  16172. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16173. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16174. &\MID& \ARITY{\Atm}
  16175. \end{array}
  16176. }
  16177. \begin{figure}[tp]
  16178. \begin{tcolorbox}[colback=white]
  16179. \small
  16180. {\if\edition\racketEd
  16181. \[
  16182. \begin{array}{l}
  16183. \gray{\CvarASTRacket} \\ \hline
  16184. \gray{\CifASTRacket} \\ \hline
  16185. \gray{\CloopASTRacket} \\ \hline
  16186. \gray{\CtupASTRacket} \\ \hline
  16187. \gray{\CfunASTRacket} \\ \hline
  16188. \ClambdaASTRacket \\
  16189. \begin{array}{lcl}
  16190. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16191. \end{array}
  16192. \end{array}
  16193. \]
  16194. \fi}
  16195. {\if\edition\pythonEd\pythonColor
  16196. \[
  16197. \begin{array}{l}
  16198. \gray{\CifASTPython} \\ \hline
  16199. \gray{\CtupASTPython} \\ \hline
  16200. \gray{\CfunASTPython} \\ \hline
  16201. \ClambdaASTPython \\
  16202. \begin{array}{lcl}
  16203. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16204. \end{array}
  16205. \end{array}
  16206. \]
  16207. \fi}
  16208. \end{tcolorbox}
  16209. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16210. \label{fig:Clam-syntax}
  16211. \end{figure}
  16212. \section{Select Instructions}
  16213. \label{sec:select-instructions-Llambda}
  16214. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16215. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16216. (section~\ref{sec:select-instructions-gc}). The only difference is
  16217. that you should place the \itm{arity} in the tag that is stored at
  16218. position $0$ of the vector. Recall that in
  16219. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16220. was not used. We store the arity in the $5$ bits starting at position
  16221. $58$.
  16222. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16223. instructions that access the tag from position $0$ of the vector and
  16224. extract the $5$ bits starting at position $58$ from the tag.}
  16225. %
  16226. \python{Compile a call to the \code{arity} operator to a sequence of
  16227. instructions that access the tag from position $0$ of the tuple
  16228. (representing a closure) and extract the $5$-bits starting at position
  16229. $58$ from the tag.}
  16230. \begin{figure}[p]
  16231. \begin{tcolorbox}[colback=white]
  16232. {\if\edition\racketEd
  16233. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16234. \node (Lfun) at (0,2) {\large \LangLam{}};
  16235. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16236. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16237. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16238. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16239. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16240. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16241. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16242. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16243. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16244. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16245. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16246. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16247. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16248. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16249. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16250. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16251. \path[->,bend left=15] (Lfun) edge [above] node
  16252. {\ttfamily\footnotesize shrink} (Lfun-2);
  16253. \path[->,bend left=15] (Lfun-2) edge [above] node
  16254. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16255. \path[->,bend left=15] (Lfun-3) edge [above] node
  16256. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16257. \path[->,bend left=15] (F1-0) edge [left] node
  16258. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16259. \path[->,bend left=15] (F1-1) edge [below] node
  16260. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16261. \path[->,bend right=15] (F1-2) edge [above] node
  16262. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16263. \path[->,bend right=15] (F1-3) edge [above] node
  16264. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16265. \path[->,bend left=15] (F1-4) edge [right] node
  16266. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16267. \path[->,bend right=15] (F1-5) edge [below] node
  16268. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16269. \path[->,bend left=15] (F1-6) edge [above] node
  16270. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16271. \path[->] (C3-2) edge [right] node
  16272. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16273. \path[->,bend right=15] (x86-2) edge [right] node
  16274. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16275. \path[->,bend right=15] (x86-2-1) edge [below] node
  16276. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16277. \path[->,bend right=15] (x86-2-2) edge [right] node
  16278. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16279. \path[->,bend left=15] (x86-3) edge [above] node
  16280. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16281. \path[->,bend left=15] (x86-4) edge [right] node
  16282. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16283. \end{tikzpicture}
  16284. \fi}
  16285. {\if\edition\pythonEd\pythonColor
  16286. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16287. \node (Lfun) at (0,2) {\large \LangLam{}};
  16288. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16289. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16290. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16291. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16292. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16293. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16294. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16295. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16296. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16297. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16298. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16299. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16300. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16301. \path[->,bend left=15] (Lfun) edge [above] node
  16302. {\ttfamily\footnotesize shrink} (Lfun-2);
  16303. \path[->,bend left=15] (Lfun-2) edge [above] node
  16304. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16305. \path[->,bend left=15] (Lfun-3) edge [above] node
  16306. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16307. \path[->,bend left=15] (F1-0) edge [left] node
  16308. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16309. \path[->,bend left=15] (F1-1) edge [below] node
  16310. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16311. \path[->,bend left=15] (F1-2) edge [below] node
  16312. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16313. \path[->,bend right=15] (F1-3) edge [above] node
  16314. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16315. \path[->,bend right=15] (F1-5) edge [right] node
  16316. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16317. \path[->,bend left=15] (F1-6) edge [right] node
  16318. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16319. \path[->,bend right=15] (C3-2) edge [right] node
  16320. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16321. \path[->,bend right=15] (x86-2) edge [below] node
  16322. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16323. \path[->,bend right=15] (x86-3) edge [below] node
  16324. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16325. \path[->,bend left=15] (x86-4) edge [above] node
  16326. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16327. \end{tikzpicture}
  16328. \fi}
  16329. \end{tcolorbox}
  16330. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16331. functions.}
  16332. \label{fig:Llambda-passes}
  16333. \end{figure}
  16334. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16335. needed for the compilation of \LangLam{}.
  16336. \clearpage
  16337. \section{Challenge: Optimize Closures}
  16338. \label{sec:optimize-closures}
  16339. In this chapter we compile lexically scoped functions into a
  16340. relatively efficient representation: flat closures. However, even this
  16341. representation comes with some overhead. For example, consider the
  16342. following program with a function \code{tail\_sum} that does not have
  16343. any free variables and where all the uses of \code{tail\_sum} are in
  16344. applications in which we know that only \code{tail\_sum} is being applied
  16345. (and not any other functions):
  16346. \begin{center}
  16347. \begin{minipage}{0.95\textwidth}
  16348. {\if\edition\racketEd
  16349. \begin{lstlisting}
  16350. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16351. (if (eq? n 0)
  16352. s
  16353. (tail_sum (- n 1) (+ n s))))
  16354. (+ (tail_sum 3 0) 36)
  16355. \end{lstlisting}
  16356. \fi}
  16357. {\if\edition\pythonEd\pythonColor
  16358. \begin{lstlisting}
  16359. def tail_sum(n : int, s : int) -> int:
  16360. if n == 0:
  16361. return s
  16362. else:
  16363. return tail_sum(n - 1, n + s)
  16364. print( tail_sum(3, 0) + 36)
  16365. \end{lstlisting}
  16366. \fi}
  16367. \end{minipage}
  16368. \end{center}
  16369. As described in this chapter, we uniformly apply closure conversion to
  16370. all functions, obtaining the following output for this program:
  16371. \begin{center}
  16372. \begin{minipage}{0.95\textwidth}
  16373. {\if\edition\racketEd
  16374. \begin{lstlisting}
  16375. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16376. (if (eq? n2 0)
  16377. s3
  16378. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16379. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16380. (define (main) : Integer
  16381. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16382. ((vector-ref clos6 0) clos6 3 0)) 27))
  16383. \end{lstlisting}
  16384. \fi}
  16385. {\if\edition\pythonEd\pythonColor
  16386. \begin{lstlisting}
  16387. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16388. if n_0 == 0:
  16389. return s_1
  16390. else:
  16391. return (let clos_2 = (tail_sum,)
  16392. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16393. def main() -> int :
  16394. print((let clos_4 = (tail_sum,)
  16395. in clos_4[0](clos_4, 3, 0)) + 36)
  16396. return 0
  16397. \end{lstlisting}
  16398. \fi}
  16399. \end{minipage}
  16400. \end{center}
  16401. If this program were compiled according to the previous chapter, there
  16402. would be no allocation and the calls to \code{tail\_sum} would be
  16403. direct calls. In contrast, the program presented here allocates memory
  16404. for each closure and the calls to \code{tail\_sum} are indirect. These
  16405. two differences incur considerable overhead in a program such as this,
  16406. in which the allocations and indirect calls occur inside a tight loop.
  16407. One might think that this problem is trivial to solve: can't we just
  16408. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16409. and compile them to direct calls instead of treating it like a call to
  16410. a closure? We would also drop the new \code{fvs} parameter of
  16411. \code{tail\_sum}.
  16412. %
  16413. However, this problem is not so trivial, because a global function may
  16414. \emph{escape} and become involved in applications that also involve
  16415. closures. Consider the following example in which the application
  16416. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16417. application because the \code{lambda} may flow into \code{f}, but the
  16418. \code{inc} function might also flow into \code{f}:
  16419. \begin{center}
  16420. \begin{minipage}{\textwidth}
  16421. % lambda_test_30.rkt
  16422. {\if\edition\racketEd
  16423. \begin{lstlisting}
  16424. (define (inc [x : Integer]) : Integer
  16425. (+ x 1))
  16426. (let ([y (read)])
  16427. (let ([f (if (eq? (read) 0)
  16428. inc
  16429. (lambda: ([x : Integer]) : Integer (- x y)))])
  16430. (f 41)))
  16431. \end{lstlisting}
  16432. \fi}
  16433. {\if\edition\pythonEd\pythonColor
  16434. \begin{lstlisting}
  16435. def add1(x : int) -> int:
  16436. return x + 1
  16437. y = input_int()
  16438. g : Callable[[int], int] = lambda x: x - y
  16439. f = add1 if input_int() == 0 else g
  16440. print( f(41) )
  16441. \end{lstlisting}
  16442. \fi}
  16443. \end{minipage}
  16444. \end{center}
  16445. If a global function name is used in any way other than as the
  16446. operator in a direct call, then we say that the function
  16447. \emph{escapes}. If a global function does not escape, then we do not
  16448. need to perform closure conversion on the function.
  16449. \begin{exercise}\normalfont\normalsize
  16450. Implement an auxiliary function for detecting which global
  16451. functions escape. Using that function, implement an improved version
  16452. of closure conversion that does not apply closure conversion to
  16453. global functions that do not escape but instead compiles them as
  16454. regular functions. Create several new test cases that check whether
  16455. your compiler properly detect whether global functions escape or not.
  16456. \end{exercise}
  16457. So far we have reduced the overhead of calling global functions, but
  16458. it would also be nice to reduce the overhead of calling a
  16459. \code{lambda} when we can determine at compile time which
  16460. \code{lambda} will be called. We refer to such calls as \emph{known
  16461. calls}. Consider the following example in which a \code{lambda} is
  16462. bound to \code{f} and then applied.
  16463. {\if\edition\racketEd
  16464. % lambda_test_9.rkt
  16465. \begin{lstlisting}
  16466. (let ([y (read)])
  16467. (let ([f (lambda: ([x : Integer]) : Integer
  16468. (+ x y))])
  16469. (f 21)))
  16470. \end{lstlisting}
  16471. \fi}
  16472. {\if\edition\pythonEd\pythonColor
  16473. \begin{lstlisting}
  16474. y = input_int()
  16475. f : Callable[[int],int] = lambda x: x + y
  16476. print( f(21) )
  16477. \end{lstlisting}
  16478. \fi}
  16479. %
  16480. \noindent Closure conversion compiles the application
  16481. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16482. %
  16483. {\if\edition\racketEd
  16484. \begin{lstlisting}
  16485. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16486. (let ([y2 (vector-ref fvs6 1)])
  16487. (+ x3 y2)))
  16488. (define (main) : Integer
  16489. (let ([y2 (read)])
  16490. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16491. ((vector-ref f4 0) f4 21))))
  16492. \end{lstlisting}
  16493. \fi}
  16494. {\if\edition\pythonEd\pythonColor
  16495. \begin{lstlisting}
  16496. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16497. y_1 = fvs_4[1]
  16498. return x_2 + y_1[0]
  16499. def main() -> int:
  16500. y_1 = (777,)
  16501. y_1[0] = input_int()
  16502. f_0 = (lambda_3, y_1)
  16503. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16504. return 0
  16505. \end{lstlisting}
  16506. \fi}
  16507. %
  16508. \noindent However, we can instead compile the application
  16509. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16510. %
  16511. {\if\edition\racketEd
  16512. \begin{lstlisting}
  16513. (define (main) : Integer
  16514. (let ([y2 (read)])
  16515. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16516. ((fun-ref lambda5 1) f4 21))))
  16517. \end{lstlisting}
  16518. \fi}
  16519. {\if\edition\pythonEd\pythonColor
  16520. \begin{lstlisting}
  16521. def main() -> int:
  16522. y_1 = (777,)
  16523. y_1[0] = input_int()
  16524. f_0 = (lambda_3, y_1)
  16525. print(lambda_3(f_0, 21))
  16526. return 0
  16527. \end{lstlisting}
  16528. \fi}
  16529. The problem of determining which \code{lambda} will be called from a
  16530. particular application is quite challenging in general and the topic
  16531. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16532. following exercise we recommend that you compile an application to a
  16533. direct call when the operator is a variable and \racket{the variable
  16534. is \code{let}-bound to a closure}\python{the previous assignment to
  16535. the variable is a closure}. This can be accomplished by maintaining
  16536. an environment that maps variables to function names. Extend the
  16537. environment whenever you encounter a closure on the right-hand side of
  16538. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16539. name of the global function for the closure. This pass should come
  16540. after closure conversion.
  16541. \begin{exercise}\normalfont\normalsize
  16542. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16543. compiles known calls into direct calls. Verify that your compiler is
  16544. successful in this regard on several example programs.
  16545. \end{exercise}
  16546. These exercises only scratch the surface of closure optimization. A
  16547. good next step for the interested reader is to look at the work of
  16548. \citet{Keep:2012ab}.
  16549. \section{Further Reading}
  16550. The notion of lexically scoped functions predates modern computers by
  16551. about a decade. They were invented by \citet{Church:1932aa}, who
  16552. proposed the lambda calculus as a foundation for logic. Anonymous
  16553. functions were included in the LISP~\citep{McCarthy:1960dz}
  16554. programming language but were initially dynamically scoped. The Scheme
  16555. dialect of LISP adopted lexical scoping, and
  16556. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16557. Scheme programs. However, environments were represented as linked
  16558. lists, so variable look-up was linear in the size of the
  16559. environment. \citet{Appel91} gives a detailed description of several
  16560. closure representations. In this chapter we represent environments
  16561. using flat closures, which were invented by
  16562. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  16563. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16564. closures, variable look-up is constant time but the time to create a
  16565. closure is proportional to the number of its free variables. Flat
  16566. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16567. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16568. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16569. % compilers)
  16570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16571. \chapter{Dynamic Typing}
  16572. \label{ch:Ldyn}
  16573. \index{subject}{dynamic typing}
  16574. \setcounter{footnote}{0}
  16575. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16576. typed language that is a subset of \racket{Racket}\python{Python}. The
  16577. focus on dynamic typing is in contrast to the previous chapters, which
  16578. have studied the compilation of statically typed languages. In
  16579. dynamically typed languages such as \LangDyn{}, a particular
  16580. expression may produce a value of a different type each time it is
  16581. executed. Consider the following example with a conditional \code{if}
  16582. expression that may return a Boolean or an integer depending on the
  16583. input to the program:
  16584. % part of dynamic_test_25.rkt
  16585. {\if\edition\racketEd
  16586. \begin{lstlisting}
  16587. (not (if (eq? (read) 1) #f 0))
  16588. \end{lstlisting}
  16589. \fi}
  16590. {\if\edition\pythonEd\pythonColor
  16591. \begin{lstlisting}
  16592. not (False if input_int() == 1 else 0)
  16593. \end{lstlisting}
  16594. \fi}
  16595. Languages that allow expressions to produce different kinds of values
  16596. are called \emph{polymorphic}, a word composed of the Greek roots
  16597. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16598. There are several kinds of polymorphism in programming languages, such as
  16599. subtype polymorphism and parametric polymorphism
  16600. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16601. study in this chapter does not have a special name; it is the kind
  16602. that arises in dynamically typed languages.
  16603. Another characteristic of dynamically typed languages is that
  16604. their primitive operations, such as \code{not}, are often defined to operate
  16605. on many different types of values. In fact, in
  16606. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16607. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16608. given anything else it returns \FALSE{}.
  16609. Furthermore, even when primitive operations restrict their inputs to
  16610. values of a certain type, this restriction is enforced at runtime
  16611. instead of during compilation. For example, the tuple read
  16612. operation
  16613. \racket{\code{(vector-ref \#t 0)}}
  16614. \python{\code{True[0]}}
  16615. results in a runtime error because the first argument must
  16616. be a tuple, not a Boolean.
  16617. \section{The \LangDyn{} Language}
  16618. \newcommand{\LdynGrammarRacket}{
  16619. \begin{array}{rcl}
  16620. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16621. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16622. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16623. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16624. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16625. \end{array}
  16626. }
  16627. \newcommand{\LdynASTRacket}{
  16628. \begin{array}{lcl}
  16629. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16630. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16631. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16632. \end{array}
  16633. }
  16634. \begin{figure}[tp]
  16635. \centering
  16636. \begin{tcolorbox}[colback=white]
  16637. \small
  16638. {\if\edition\racketEd
  16639. \[
  16640. \begin{array}{l}
  16641. \gray{\LintGrammarRacket{}} \\ \hline
  16642. \gray{\LvarGrammarRacket{}} \\ \hline
  16643. \gray{\LifGrammarRacket{}} \\ \hline
  16644. \gray{\LwhileGrammarRacket} \\ \hline
  16645. \gray{\LtupGrammarRacket} \\ \hline
  16646. \LdynGrammarRacket \\
  16647. \begin{array}{rcl}
  16648. \LangDynM{} &::=& \Def\ldots\; \Exp
  16649. \end{array}
  16650. \end{array}
  16651. \]
  16652. \fi}
  16653. {\if\edition\pythonEd\pythonColor
  16654. \[
  16655. \begin{array}{rcl}
  16656. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16657. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16658. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16659. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16660. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16661. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16662. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16663. \MID \CLEN{\Exp} \\
  16664. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16665. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16666. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16667. \MID \Var\mathop{\key{=}}\Exp \\
  16668. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16669. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16670. &\MID& \CRETURN{\Exp} \\
  16671. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16672. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16673. \end{array}
  16674. \]
  16675. \fi}
  16676. \end{tcolorbox}
  16677. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16678. \label{fig:r7-concrete-syntax}
  16679. \end{figure}
  16680. \begin{figure}[tp]
  16681. \centering
  16682. \begin{tcolorbox}[colback=white]
  16683. \small
  16684. {\if\edition\racketEd
  16685. \[
  16686. \begin{array}{l}
  16687. \gray{\LintASTRacket{}} \\ \hline
  16688. \gray{\LvarASTRacket{}} \\ \hline
  16689. \gray{\LifASTRacket{}} \\ \hline
  16690. \gray{\LwhileASTRacket} \\ \hline
  16691. \gray{\LtupASTRacket} \\ \hline
  16692. \LdynASTRacket \\
  16693. \begin{array}{lcl}
  16694. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16695. \end{array}
  16696. \end{array}
  16697. \]
  16698. \fi}
  16699. {\if\edition\pythonEd\pythonColor
  16700. \[
  16701. \begin{array}{rcl}
  16702. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16703. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16704. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16705. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16706. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16707. &\MID & \code{Is()} \\
  16708. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16709. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16710. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16711. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16712. \MID \VAR{\Var{}} \\
  16713. &\MID& \BOOL{\itm{bool}}
  16714. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16715. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16716. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16717. &\MID& \LEN{\Exp} \\
  16718. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16719. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16720. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16721. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16722. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16723. &\MID& \RETURN{\Exp} \\
  16724. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16725. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16726. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16727. \end{array}
  16728. \]
  16729. \fi}
  16730. \end{tcolorbox}
  16731. \caption{The abstract syntax of \LangDyn{}.}
  16732. \label{fig:r7-syntax}
  16733. \end{figure}
  16734. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16735. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16736. %
  16737. There is no type checker for \LangDyn{} because it checks types only
  16738. at runtime.
  16739. The definitional interpreter for \LangDyn{} is presented in
  16740. \racket{figure~\ref{fig:interp-Ldyn}}
  16741. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16742. and definitions of its auxiliary functions are shown in
  16743. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16744. \INT{n}. Instead of simply returning the integer \code{n} (as
  16745. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16746. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16747. value} that combines an underlying value with a tag that identifies
  16748. what kind of value it is. We define the following \racket{struct}\python{class}
  16749. to represent tagged values:
  16750. %
  16751. {\if\edition\racketEd
  16752. \begin{lstlisting}
  16753. (struct Tagged (value tag) #:transparent)
  16754. \end{lstlisting}
  16755. \fi}
  16756. {\if\edition\pythonEd\pythonColor
  16757. \begin{minipage}{\textwidth}
  16758. \begin{lstlisting}
  16759. @dataclass(eq=True)
  16760. class Tagged(Value):
  16761. value : Value
  16762. tag : str
  16763. def __str__(self):
  16764. return str(self.value)
  16765. \end{lstlisting}
  16766. \end{minipage}
  16767. \fi}
  16768. %
  16769. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16770. \code{Vector}, and \code{Procedure}.}
  16771. %
  16772. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16773. \code{'tuple'}, and \code{'function'}.}
  16774. %
  16775. Tags are closely related to types but do not always capture all the
  16776. information that a type does.
  16777. %
  16778. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16779. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16780. Any)} is tagged with \code{Procedure}.}
  16781. %
  16782. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16783. is tagged with \code{'tuple'} and a function of type
  16784. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16785. is tagged with \code{'function'}.}
  16786. Next consider the match case for accessing the element of a tuple.
  16787. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16788. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16789. argument is a tuple and the second is an integer.
  16790. \racket{
  16791. If they are not, a \code{trapped-error} is raised. Recall from
  16792. section~\ref{sec:interp_Lint} that when a definition interpreter
  16793. raises a \code{trapped-error} error, the compiled code must also
  16794. signal an error by exiting with return code \code{255}. A
  16795. \code{trapped-error} is also raised if the index is not less than the
  16796. length of the vector.
  16797. }
  16798. %
  16799. \python{If they are not, an exception is raised. The compiled code
  16800. must also signal an error by exiting with return code \code{255}. A
  16801. exception is also raised if the index is not less than the length of the
  16802. tuple or if it is negative.}
  16803. \begin{figure}[tbp]
  16804. \begin{tcolorbox}[colback=white]
  16805. {\if\edition\racketEd
  16806. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16807. (define ((interp-Ldyn-exp env) ast)
  16808. (define recur (interp-Ldyn-exp env))
  16809. (match ast
  16810. [(Var x) (dict-ref env x)]
  16811. [(Int n) (Tagged n 'Integer)]
  16812. [(Bool b) (Tagged b 'Boolean)]
  16813. [(Lambda xs rt body)
  16814. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16815. [(Prim 'vector es)
  16816. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16817. [(Prim 'vector-ref (list e1 e2))
  16818. (define vec (recur e1)) (define i (recur e2))
  16819. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16820. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16821. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16822. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16823. [(Prim 'vector-set! (list e1 e2 e3))
  16824. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16825. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16826. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16827. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16828. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16829. (Tagged (void) 'Void)]
  16830. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16831. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16832. [(Prim 'or (list e1 e2))
  16833. (define v1 (recur e1))
  16834. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16835. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16836. [(Prim op (list e1))
  16837. #:when (set-member? type-predicates op)
  16838. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16839. [(Prim op es)
  16840. (define args (map recur es))
  16841. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16842. (unless (for/or ([expected-tags (op-tags op)])
  16843. (equal? expected-tags tags))
  16844. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16845. (tag-value
  16846. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16847. [(If q t f)
  16848. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16849. [(Apply f es)
  16850. (define new-f (recur f)) (define args (map recur es))
  16851. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16852. (match f-val
  16853. [`(function ,xs ,body ,lam-env)
  16854. (unless (eq? (length xs) (length args))
  16855. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16856. (define new-env (append (map cons xs args) lam-env))
  16857. ((interp-Ldyn-exp new-env) body)]
  16858. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16859. \end{lstlisting}
  16860. \fi}
  16861. {\if\edition\pythonEd\pythonColor
  16862. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16863. class InterpLdyn(InterpLlambda):
  16864. def interp_exp(self, e, env):
  16865. match e:
  16866. case Constant(n):
  16867. return self.tag(super().interp_exp(e, env))
  16868. case Tuple(es, Load()):
  16869. return self.tag(super().interp_exp(e, env))
  16870. case Lambda(params, body):
  16871. return self.tag(super().interp_exp(e, env))
  16872. case Call(Name('input_int'), []):
  16873. return self.tag(super().interp_exp(e, env))
  16874. case BinOp(left, Add(), right):
  16875. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16876. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16877. case BinOp(left, Sub(), right):
  16878. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16879. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16880. case UnaryOp(USub(), e1):
  16881. v = self.interp_exp(e1, env)
  16882. return self.tag(- self.untag(v, 'int', e))
  16883. case IfExp(test, body, orelse):
  16884. v = self.interp_exp(test, env)
  16885. if self.untag(v, 'bool', e):
  16886. return self.interp_exp(body, env)
  16887. else:
  16888. return self.interp_exp(orelse, env)
  16889. case UnaryOp(Not(), e1):
  16890. v = self.interp_exp(e1, env)
  16891. return self.tag(not self.untag(v, 'bool', e))
  16892. case BoolOp(And(), values):
  16893. left = values[0]; right = values[1]
  16894. l = self.interp_exp(left, env)
  16895. if self.untag(l, 'bool', e):
  16896. return self.interp_exp(right, env)
  16897. else:
  16898. return self.tag(False)
  16899. case BoolOp(Or(), values):
  16900. left = values[0]; right = values[1]
  16901. l = self.interp_exp(left, env)
  16902. if self.untag(l, 'bool', e):
  16903. return self.tag(True)
  16904. else:
  16905. return self.interp_exp(right, env)
  16906. case Compare(left, [cmp], [right]):
  16907. l = self.interp_exp(left, env)
  16908. r = self.interp_exp(right, env)
  16909. if l.tag == r.tag:
  16910. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16911. else:
  16912. raise Exception('interp Compare unexpected '
  16913. + repr(l) + ' ' + repr(r))
  16914. case Subscript(tup, index, Load()):
  16915. t = self.interp_exp(tup, env)
  16916. n = self.interp_exp(index, env)
  16917. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16918. case Call(Name('len'), [tup]):
  16919. t = self.interp_exp(tup, env)
  16920. return self.tag(len(self.untag(t, 'tuple', e)))
  16921. case _:
  16922. return self.tag(super().interp_exp(e, env))
  16923. \end{lstlisting}
  16924. \fi}
  16925. \end{tcolorbox}
  16926. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16927. \label{fig:interp-Ldyn}
  16928. \end{figure}
  16929. {\if\edition\pythonEd\pythonColor
  16930. \begin{figure}[tbp]
  16931. \begin{tcolorbox}[colback=white]
  16932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16933. class InterpLdyn(InterpLlambda):
  16934. def interp_stmts(self, ss, env):
  16935. if len(ss) == 0:
  16936. return
  16937. match ss[0]:
  16938. case If(test, body, orelse):
  16939. v = self.interp_exp(test, env)
  16940. if self.untag(v, 'bool', ss[0]):
  16941. return self.interp_stmts(body + ss[1:], env)
  16942. else:
  16943. return self.interp_stmts(orelse + ss[1:], env)
  16944. case While(test, body, []):
  16945. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16946. self.interp_stmts(body, env)
  16947. return self.interp_stmts(ss[1:], env)
  16948. case Assign([Subscript(tup, index)], value):
  16949. tup = self.interp_exp(tup, env)
  16950. index = self.interp_exp(index, env)
  16951. tup_v = self.untag(tup, 'tuple', ss[0])
  16952. index_v = self.untag(index, 'int', ss[0])
  16953. tup_v[index_v] = self.interp_exp(value, env)
  16954. return self.interp_stmts(ss[1:], env)
  16955. case FunctionDef(name, params, bod, dl, returns, comment):
  16956. ps = [x for (x,t) in params]
  16957. env[name] = self.tag(Function(name, ps, bod, env))
  16958. return self.interp_stmts(ss[1:], env)
  16959. case _:
  16960. return super().interp_stmts(ss, env)
  16961. \end{lstlisting}
  16962. \end{tcolorbox}
  16963. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16964. \label{fig:interp-Ldyn-2}
  16965. \end{figure}
  16966. \fi}
  16967. \begin{figure}[tbp]
  16968. \begin{tcolorbox}[colback=white]
  16969. {\if\edition\racketEd
  16970. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16971. (define (interp-op op)
  16972. (match op
  16973. ['+ fx+]
  16974. ['- fx-]
  16975. ['read read-fixnum]
  16976. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16977. ['< (lambda (v1 v2)
  16978. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16979. ['<= (lambda (v1 v2)
  16980. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16981. ['> (lambda (v1 v2)
  16982. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16983. ['>= (lambda (v1 v2)
  16984. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16985. ['boolean? boolean?]
  16986. ['integer? fixnum?]
  16987. ['void? void?]
  16988. ['vector? vector?]
  16989. ['vector-length vector-length]
  16990. ['procedure? (match-lambda
  16991. [`(functions ,xs ,body ,env) #t] [else #f])]
  16992. [else (error 'interp-op "unknown operator" op)]))
  16993. (define (op-tags op)
  16994. (match op
  16995. ['+ '((Integer Integer))]
  16996. ['- '((Integer Integer) (Integer))]
  16997. ['read '(())]
  16998. ['not '((Boolean))]
  16999. ['< '((Integer Integer))]
  17000. ['<= '((Integer Integer))]
  17001. ['> '((Integer Integer))]
  17002. ['>= '((Integer Integer))]
  17003. ['vector-length '((Vector))]))
  17004. (define type-predicates
  17005. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17006. (define (tag-value v)
  17007. (cond [(boolean? v) (Tagged v 'Boolean)]
  17008. [(fixnum? v) (Tagged v 'Integer)]
  17009. [(procedure? v) (Tagged v 'Procedure)]
  17010. [(vector? v) (Tagged v 'Vector)]
  17011. [(void? v) (Tagged v 'Void)]
  17012. [else (error 'tag-value "unidentified value ~a" v)]))
  17013. (define (check-tag val expected ast)
  17014. (define tag (Tagged-tag val))
  17015. (unless (eq? tag expected)
  17016. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17017. \end{lstlisting}
  17018. \fi}
  17019. {\if\edition\pythonEd\pythonColor
  17020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17021. class InterpLdyn(InterpLlambda):
  17022. def tag(self, v):
  17023. if v is True or v is False:
  17024. return Tagged(v, 'bool')
  17025. elif isinstance(v, int):
  17026. return Tagged(v, 'int')
  17027. elif isinstance(v, Function):
  17028. return Tagged(v, 'function')
  17029. elif isinstance(v, tuple):
  17030. return Tagged(v, 'tuple')
  17031. elif isinstance(v, type(None)):
  17032. return Tagged(v, 'none')
  17033. else:
  17034. raise Exception('tag: unexpected ' + repr(v))
  17035. def untag(self, v, expected_tag, ast):
  17036. match v:
  17037. case Tagged(val, tag) if tag == expected_tag:
  17038. return val
  17039. case _:
  17040. raise Exception('expected Tagged value with '
  17041. + expected_tag + ', not ' + ' ' + repr(v))
  17042. def apply_fun(self, fun, args, e):
  17043. f = self.untag(fun, 'function', e)
  17044. return super().apply_fun(f, args, e)
  17045. \end{lstlisting}
  17046. \fi}
  17047. \end{tcolorbox}
  17048. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17049. \label{fig:interp-Ldyn-aux}
  17050. \end{figure}
  17051. \clearpage
  17052. \section{Representation of Tagged Values}
  17053. The interpreter for \LangDyn{} introduced a new kind of value: the
  17054. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17055. represent tagged values at the bit level. Because almost every
  17056. operation in \LangDyn{} involves manipulating tagged values, the
  17057. representation must be efficient. Recall that all our values are 64
  17058. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17059. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17060. $011$ for procedures, and $101$ for the void value\python{,
  17061. \key{None}}. We define the following auxiliary function for mapping
  17062. types to tag codes:
  17063. %
  17064. {\if\edition\racketEd
  17065. \begin{align*}
  17066. \itm{tagof}(\key{Integer}) &= 001 \\
  17067. \itm{tagof}(\key{Boolean}) &= 100 \\
  17068. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17069. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17070. \itm{tagof}(\key{Void}) &= 101
  17071. \end{align*}
  17072. \fi}
  17073. {\if\edition\pythonEd\pythonColor
  17074. \begin{align*}
  17075. \itm{tagof}(\key{IntType()}) &= 001 \\
  17076. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17077. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17078. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17079. \itm{tagof}(\key{type(None)}) &= 101
  17080. \end{align*}
  17081. \fi}
  17082. %
  17083. This stealing of 3 bits comes at some price: integers are now restricted
  17084. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17085. affect tuples and procedures because those values are addresses, and
  17086. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17087. they are always $000$. Thus, we do not lose information by overwriting
  17088. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17089. to recover the original address.
  17090. To make tagged values into first-class entities, we can give them a
  17091. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17092. operations such as \code{Inject} and \code{Project} for creating and
  17093. using them, yielding the statically typed \LangAny{} intermediate
  17094. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17095. section~\ref{sec:compile-r7}; in th next section we describe the
  17096. \LangAny{} language in greater detail.
  17097. \section{The \LangAny{} Language}
  17098. \label{sec:Rany-lang}
  17099. \newcommand{\LanyASTRacket}{
  17100. \begin{array}{lcl}
  17101. \Type &::= & \ANYTY \\
  17102. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17103. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17104. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17105. \itm{op} &::= & \code{any-vector-length}
  17106. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17107. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17108. \MID \code{procedure?} \MID \code{void?} \\
  17109. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17110. \end{array}
  17111. }
  17112. \newcommand{\LanyASTPython}{
  17113. \begin{array}{lcl}
  17114. \Type &::= & \key{AnyType()} \\
  17115. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17116. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17117. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17118. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17119. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17120. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17121. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17122. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17123. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17124. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17125. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17126. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17127. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17128. \end{array}
  17129. }
  17130. \begin{figure}[tp]
  17131. \centering
  17132. \begin{tcolorbox}[colback=white]
  17133. \small
  17134. {\if\edition\racketEd
  17135. \[
  17136. \begin{array}{l}
  17137. \gray{\LintOpAST} \\ \hline
  17138. \gray{\LvarASTRacket{}} \\ \hline
  17139. \gray{\LifASTRacket{}} \\ \hline
  17140. \gray{\LwhileASTRacket{}} \\ \hline
  17141. \gray{\LtupASTRacket{}} \\ \hline
  17142. \gray{\LfunASTRacket} \\ \hline
  17143. \gray{\LlambdaASTRacket} \\ \hline
  17144. \LanyASTRacket \\
  17145. \begin{array}{lcl}
  17146. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17147. \end{array}
  17148. \end{array}
  17149. \]
  17150. \fi}
  17151. {\if\edition\pythonEd\pythonColor
  17152. \[
  17153. \begin{array}{l}
  17154. \gray{\LintASTPython} \\ \hline
  17155. \gray{\LvarASTPython{}} \\ \hline
  17156. \gray{\LifASTPython{}} \\ \hline
  17157. \gray{\LwhileASTPython{}} \\ \hline
  17158. \gray{\LtupASTPython{}} \\ \hline
  17159. \gray{\LfunASTPython} \\ \hline
  17160. \gray{\LlambdaASTPython} \\ \hline
  17161. \LanyASTPython \\
  17162. \begin{array}{lcl}
  17163. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17164. \end{array}
  17165. \end{array}
  17166. \]
  17167. \fi}
  17168. \end{tcolorbox}
  17169. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17170. \label{fig:Lany-syntax}
  17171. \end{figure}
  17172. The definition of the abstract syntax of \LangAny{} is given in
  17173. figure~\ref{fig:Lany-syntax}.
  17174. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17175. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17176. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17177. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17178. converts the tagged value produced by expression $e$ into a value of
  17179. type $T$ or halts the program if the type tag does not match $T$.
  17180. %
  17181. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17182. restricted to be a flat type (the nonterminal $\FType$) which
  17183. simplifies the implementation and complies with the needs for
  17184. compiling \LangDyn{}.
  17185. The \racket{\code{any-vector}} operators
  17186. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17187. operations so that they can be applied to a value of type
  17188. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17189. tuple operations in that the index is not restricted to a literal
  17190. integer in the grammar but is allowed to be any expression.
  17191. \racket{The type predicates such as
  17192. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17193. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17194. the predicate and return {\FALSE} otherwise.}
  17195. The type checker for \LangAny{} is shown in
  17196. figure~\ref{fig:type-check-Lany}
  17197. %
  17198. \racket{ and uses the auxiliary functions presented in
  17199. figure~\ref{fig:type-check-Lany-aux}}.
  17200. %
  17201. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17202. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17203. \begin{figure}[btp]
  17204. \begin{tcolorbox}[colback=white]
  17205. {\if\edition\racketEd
  17206. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17207. (define type-check-Lany-class
  17208. (class type-check-Llambda-class
  17209. (super-new)
  17210. (inherit check-type-equal?)
  17211. (define/override (type-check-exp env)
  17212. (lambda (e)
  17213. (define recur (type-check-exp env))
  17214. (match e
  17215. [(Inject e1 ty)
  17216. (unless (flat-ty? ty)
  17217. (error 'type-check "may only inject from flat type, not ~a" ty))
  17218. (define-values (new-e1 e-ty) (recur e1))
  17219. (check-type-equal? e-ty ty e)
  17220. (values (Inject new-e1 ty) 'Any)]
  17221. [(Project e1 ty)
  17222. (unless (flat-ty? ty)
  17223. (error 'type-check "may only project to flat type, not ~a" ty))
  17224. (define-values (new-e1 e-ty) (recur e1))
  17225. (check-type-equal? e-ty 'Any e)
  17226. (values (Project new-e1 ty) ty)]
  17227. [(Prim 'any-vector-length (list e1))
  17228. (define-values (e1^ t1) (recur e1))
  17229. (check-type-equal? t1 'Any e)
  17230. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17231. [(Prim 'any-vector-ref (list e1 e2))
  17232. (define-values (e1^ t1) (recur e1))
  17233. (define-values (e2^ t2) (recur e2))
  17234. (check-type-equal? t1 'Any e)
  17235. (check-type-equal? t2 'Integer e)
  17236. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17237. [(Prim 'any-vector-set! (list e1 e2 e3))
  17238. (define-values (e1^ t1) (recur e1))
  17239. (define-values (e2^ t2) (recur e2))
  17240. (define-values (e3^ t3) (recur e3))
  17241. (check-type-equal? t1 'Any e)
  17242. (check-type-equal? t2 'Integer e)
  17243. (check-type-equal? t3 'Any e)
  17244. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17245. [(Prim pred (list e1))
  17246. #:when (set-member? (type-predicates) pred)
  17247. (define-values (new-e1 e-ty) (recur e1))
  17248. (check-type-equal? e-ty 'Any e)
  17249. (values (Prim pred (list new-e1)) 'Boolean)]
  17250. [(Prim 'eq? (list arg1 arg2))
  17251. (define-values (e1 t1) (recur arg1))
  17252. (define-values (e2 t2) (recur arg2))
  17253. (match* (t1 t2)
  17254. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17255. [(other wise) (check-type-equal? t1 t2 e)])
  17256. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17257. [else ((super type-check-exp env) e)])))
  17258. ))
  17259. \end{lstlisting}
  17260. \fi}
  17261. {\if\edition\pythonEd\pythonColor
  17262. \begin{lstlisting}
  17263. class TypeCheckLany(TypeCheckLlambda):
  17264. def type_check_exp(self, e, env):
  17265. match e:
  17266. case Inject(value, typ):
  17267. self.check_exp(value, typ, env)
  17268. return AnyType()
  17269. case Project(value, typ):
  17270. self.check_exp(value, AnyType(), env)
  17271. return typ
  17272. case Call(Name('any_tuple_load'), [tup, index]):
  17273. self.check_exp(tup, AnyType(), env)
  17274. self.check_exp(index, IntType(), env)
  17275. return AnyType()
  17276. case Call(Name('any_len'), [tup]):
  17277. self.check_exp(tup, AnyType(), env)
  17278. return IntType()
  17279. case Call(Name('arity'), [fun]):
  17280. ty = self.type_check_exp(fun, env)
  17281. match ty:
  17282. case FunctionType(ps, rt):
  17283. return IntType()
  17284. case TupleType([FunctionType(ps,rs)]):
  17285. return IntType()
  17286. case _:
  17287. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17288. case Call(Name('make_any'), [value, tag]):
  17289. self.type_check_exp(value, env)
  17290. self.check_exp(tag, IntType(), env)
  17291. return AnyType()
  17292. case AnnLambda(params, returns, body):
  17293. new_env = {x:t for (x,t) in env.items()}
  17294. for (x,t) in params:
  17295. new_env[x] = t
  17296. return_t = self.type_check_exp(body, new_env)
  17297. self.check_type_equal(returns, return_t, e)
  17298. return FunctionType([t for (x,t) in params], return_t)
  17299. case _:
  17300. return super().type_check_exp(e, env)
  17301. \end{lstlisting}
  17302. \fi}
  17303. \end{tcolorbox}
  17304. \caption{Type checker for the \LangAny{} language.}
  17305. \label{fig:type-check-Lany}
  17306. \end{figure}
  17307. {\if\edition\racketEd
  17308. \begin{figure}[tbp]
  17309. \begin{tcolorbox}[colback=white]
  17310. \begin{lstlisting}
  17311. (define/override (operator-types)
  17312. (append
  17313. '((integer? . ((Any) . Boolean))
  17314. (vector? . ((Any) . Boolean))
  17315. (procedure? . ((Any) . Boolean))
  17316. (void? . ((Any) . Boolean)))
  17317. (super operator-types)))
  17318. (define/public (type-predicates)
  17319. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17320. (define/public (flat-ty? ty)
  17321. (match ty
  17322. [(or `Integer `Boolean `Void) #t]
  17323. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17324. [`(,ts ... -> ,rt)
  17325. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17326. [else #f]))
  17327. \end{lstlisting}
  17328. \end{tcolorbox}
  17329. \caption{Auxiliary methods for type checking \LangAny{}.}
  17330. \label{fig:type-check-Lany-aux}
  17331. \end{figure}
  17332. \fi}
  17333. \begin{figure}[btp]
  17334. \begin{tcolorbox}[colback=white]
  17335. {\if\edition\racketEd
  17336. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17337. (define interp-Lany-class
  17338. (class interp-Llambda-class
  17339. (super-new)
  17340. (define/override (interp-op op)
  17341. (match op
  17342. ['boolean? (match-lambda
  17343. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17344. [else #f])]
  17345. ['integer? (match-lambda
  17346. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17347. [else #f])]
  17348. ['vector? (match-lambda
  17349. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17350. [else #f])]
  17351. ['procedure? (match-lambda
  17352. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17353. [else #f])]
  17354. ['eq? (match-lambda*
  17355. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17356. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17357. [ls (apply (super interp-op op) ls)])]
  17358. ['any-vector-ref (lambda (v i)
  17359. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17360. ['any-vector-set! (lambda (v i a)
  17361. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17362. ['any-vector-length (lambda (v)
  17363. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17364. [else (super interp-op op)]))
  17365. (define/override ((interp-exp env) e)
  17366. (define recur (interp-exp env))
  17367. (match e
  17368. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17369. [(Project e ty2) (apply-project (recur e) ty2)]
  17370. [else ((super interp-exp env) e)]))
  17371. ))
  17372. (define (interp-Lany p)
  17373. (send (new interp-Lany-class) interp-program p))
  17374. \end{lstlisting}
  17375. \fi}
  17376. {\if\edition\pythonEd\pythonColor
  17377. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17378. class InterpLany(InterpLlambda):
  17379. def interp_exp(self, e, env):
  17380. match e:
  17381. case Inject(value, typ):
  17382. v = self.interp_exp(value, env)
  17383. return Tagged(v, self.type_to_tag(typ))
  17384. case Project(value, typ):
  17385. v = self.interp_exp(value, env)
  17386. match v:
  17387. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17388. return val
  17389. case _:
  17390. raise Exception('interp project to ' + repr(typ)
  17391. + ' unexpected ' + repr(v))
  17392. case Call(Name('any_tuple_load'), [tup, index]):
  17393. tv = self.interp_exp(tup, env)
  17394. n = self.interp_exp(index, env)
  17395. match tv:
  17396. case Tagged(v, tag):
  17397. return v[n]
  17398. case _:
  17399. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17400. case Call(Name('any_len'), [value]):
  17401. v = self.interp_exp(value, env)
  17402. match v:
  17403. case Tagged(value, tag):
  17404. return len(value)
  17405. case _:
  17406. raise Exception('interp any_len unexpected ' + repr(v))
  17407. case Call(Name('arity'), [fun]):
  17408. f = self.interp_exp(fun, env)
  17409. return self.arity(f)
  17410. case _:
  17411. return super().interp_exp(e, env)
  17412. \end{lstlisting}
  17413. \fi}
  17414. \end{tcolorbox}
  17415. \caption{Interpreter for \LangAny{}.}
  17416. \label{fig:interp-Lany}
  17417. \end{figure}
  17418. \begin{figure}[tbp]
  17419. \begin{tcolorbox}[colback=white]
  17420. {\if\edition\racketEd
  17421. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17422. (define/public (apply-inject v tg) (Tagged v tg))
  17423. (define/public (apply-project v ty2)
  17424. (define tag2 (any-tag ty2))
  17425. (match v
  17426. [(Tagged v1 tag1)
  17427. (cond
  17428. [(eq? tag1 tag2)
  17429. (match ty2
  17430. [`(Vector ,ts ...)
  17431. (define l1 ((interp-op 'vector-length) v1))
  17432. (cond
  17433. [(eq? l1 (length ts)) v1]
  17434. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17435. l1 (length ts))])]
  17436. [`(,ts ... -> ,rt)
  17437. (match v1
  17438. [`(function ,xs ,body ,env)
  17439. (cond [(eq? (length xs) (length ts)) v1]
  17440. [else
  17441. (error 'apply-project "arity mismatch ~a != ~a"
  17442. (length xs) (length ts))])]
  17443. [else (error 'apply-project "expected function not ~a" v1)])]
  17444. [else v1])]
  17445. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17446. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17447. \end{lstlisting}
  17448. \fi}
  17449. {\if\edition\pythonEd\pythonColor
  17450. \begin{lstlisting}
  17451. class InterpLany(InterpLlambda):
  17452. def type_to_tag(self, typ):
  17453. match typ:
  17454. case FunctionType(params, rt):
  17455. return 'function'
  17456. case TupleType(fields):
  17457. return 'tuple'
  17458. case t if t == int:
  17459. return 'int'
  17460. case t if t == bool:
  17461. return 'bool'
  17462. case IntType():
  17463. return 'int'
  17464. case BoolType():
  17465. return 'int'
  17466. case _:
  17467. raise Exception('type_to_tag unexpected ' + repr(typ))
  17468. def arity(self, v):
  17469. match v:
  17470. case Function(name, params, body, env):
  17471. return len(params)
  17472. case ClosureTuple(args, arity):
  17473. return arity
  17474. case _:
  17475. raise Exception('Lany arity unexpected ' + repr(v))
  17476. \end{lstlisting}
  17477. \fi}
  17478. \end{tcolorbox}
  17479. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17480. \label{fig:interp-Lany-aux}
  17481. \end{figure}
  17482. \clearpage
  17483. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17484. \label{sec:compile-r7}
  17485. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17486. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17487. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17488. is that given any subexpression $e$ in the \LangDyn{} program, the
  17489. pass will produce an expression $e'$ in \LangAny{} that has type
  17490. \ANYTY{}. For example, the first row in
  17491. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17492. \TRUE{}, which must be injected to produce an expression of type
  17493. \ANYTY{}.
  17494. %
  17495. The compilation of addition is shown in the second row of
  17496. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17497. representative of many primitive operations: the arguments have type
  17498. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17499. be performed.
  17500. The compilation of \key{lambda} (third row of
  17501. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17502. produce type annotations: we simply use \ANYTY{}.
  17503. %
  17504. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17505. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17506. this pass has to account for some differences in behavior between
  17507. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17508. permissive than \LangAny{} regarding what kind of values can be used
  17509. in various places. For example, the condition of an \key{if} does
  17510. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17511. of the same type (in that case the result is \code{\#f}).}
  17512. \begin{figure}[btp]
  17513. \centering
  17514. \begin{tcolorbox}[colback=white]
  17515. {\if\edition\racketEd
  17516. \begin{tabular}{lll}
  17517. \begin{minipage}{0.27\textwidth}
  17518. \begin{lstlisting}
  17519. #t
  17520. \end{lstlisting}
  17521. \end{minipage}
  17522. &
  17523. $\Rightarrow$
  17524. &
  17525. \begin{minipage}{0.65\textwidth}
  17526. \begin{lstlisting}
  17527. (inject #t Boolean)
  17528. \end{lstlisting}
  17529. \end{minipage}
  17530. \\[2ex]\hline
  17531. \begin{minipage}{0.27\textwidth}
  17532. \begin{lstlisting}
  17533. (+ |$e_1$| |$e_2$|)
  17534. \end{lstlisting}
  17535. \end{minipage}
  17536. &
  17537. $\Rightarrow$
  17538. &
  17539. \begin{minipage}{0.65\textwidth}
  17540. \begin{lstlisting}
  17541. (inject
  17542. (+ (project |$e'_1$| Integer)
  17543. (project |$e'_2$| Integer))
  17544. Integer)
  17545. \end{lstlisting}
  17546. \end{minipage}
  17547. \\[2ex]\hline
  17548. \begin{minipage}{0.27\textwidth}
  17549. \begin{lstlisting}
  17550. (lambda (|$x_1 \ldots$|) |$e$|)
  17551. \end{lstlisting}
  17552. \end{minipage}
  17553. &
  17554. $\Rightarrow$
  17555. &
  17556. \begin{minipage}{0.65\textwidth}
  17557. \begin{lstlisting}
  17558. (inject
  17559. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17560. (Any|$\ldots$|Any -> Any))
  17561. \end{lstlisting}
  17562. \end{minipage}
  17563. \\[2ex]\hline
  17564. \begin{minipage}{0.27\textwidth}
  17565. \begin{lstlisting}
  17566. (|$e_0$| |$e_1 \ldots e_n$|)
  17567. \end{lstlisting}
  17568. \end{minipage}
  17569. &
  17570. $\Rightarrow$
  17571. &
  17572. \begin{minipage}{0.65\textwidth}
  17573. \begin{lstlisting}
  17574. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17575. \end{lstlisting}
  17576. \end{minipage}
  17577. \\[2ex]\hline
  17578. \begin{minipage}{0.27\textwidth}
  17579. \begin{lstlisting}
  17580. (vector-ref |$e_1$| |$e_2$|)
  17581. \end{lstlisting}
  17582. \end{minipage}
  17583. &
  17584. $\Rightarrow$
  17585. &
  17586. \begin{minipage}{0.65\textwidth}
  17587. \begin{lstlisting}
  17588. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17589. \end{lstlisting}
  17590. \end{minipage}
  17591. \\[2ex]\hline
  17592. \begin{minipage}{0.27\textwidth}
  17593. \begin{lstlisting}
  17594. (if |$e_1$| |$e_2$| |$e_3$|)
  17595. \end{lstlisting}
  17596. \end{minipage}
  17597. &
  17598. $\Rightarrow$
  17599. &
  17600. \begin{minipage}{0.65\textwidth}
  17601. \begin{lstlisting}
  17602. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17603. \end{lstlisting}
  17604. \end{minipage}
  17605. \\[2ex]\hline
  17606. \begin{minipage}{0.27\textwidth}
  17607. \begin{lstlisting}
  17608. (eq? |$e_1$| |$e_2$|)
  17609. \end{lstlisting}
  17610. \end{minipage}
  17611. &
  17612. $\Rightarrow$
  17613. &
  17614. \begin{minipage}{0.65\textwidth}
  17615. \begin{lstlisting}
  17616. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17617. \end{lstlisting}
  17618. \end{minipage}
  17619. \\[2ex]\hline
  17620. \begin{minipage}{0.27\textwidth}
  17621. \begin{lstlisting}
  17622. (not |$e_1$|)
  17623. \end{lstlisting}
  17624. \end{minipage}
  17625. &
  17626. $\Rightarrow$
  17627. &
  17628. \begin{minipage}{0.65\textwidth}
  17629. \begin{lstlisting}
  17630. (if (eq? |$e'_1$| (inject #f Boolean))
  17631. (inject #t Boolean) (inject #f Boolean))
  17632. \end{lstlisting}
  17633. \end{minipage}
  17634. \end{tabular}
  17635. \fi}
  17636. {\if\edition\pythonEd\pythonColor
  17637. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17638. \begin{minipage}{0.23\textwidth}
  17639. \begin{lstlisting}
  17640. True
  17641. \end{lstlisting}
  17642. \end{minipage}
  17643. &
  17644. $\Rightarrow$
  17645. &
  17646. \begin{minipage}{0.7\textwidth}
  17647. \begin{lstlisting}
  17648. Inject(True, BoolType())
  17649. \end{lstlisting}
  17650. \end{minipage}
  17651. \\[2ex]\hline
  17652. \begin{minipage}{0.23\textwidth}
  17653. \begin{lstlisting}
  17654. |$e_1$| + |$e_2$|
  17655. \end{lstlisting}
  17656. \end{minipage}
  17657. &
  17658. $\Rightarrow$
  17659. &
  17660. \begin{minipage}{0.7\textwidth}
  17661. \begin{lstlisting}
  17662. Inject(Project(|$e'_1$|, IntType())
  17663. + Project(|$e'_2$|, IntType()),
  17664. IntType())
  17665. \end{lstlisting}
  17666. \end{minipage}
  17667. \\[2ex]\hline
  17668. \begin{minipage}{0.23\textwidth}
  17669. \begin{lstlisting}
  17670. lambda |$x_1 \ldots$|: |$e$|
  17671. \end{lstlisting}
  17672. \end{minipage}
  17673. &
  17674. $\Rightarrow$
  17675. &
  17676. \begin{minipage}{0.7\textwidth}
  17677. \begin{lstlisting}
  17678. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17679. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17680. \end{lstlisting}
  17681. \end{minipage}
  17682. \\[2ex]\hline
  17683. \begin{minipage}{0.23\textwidth}
  17684. \begin{lstlisting}
  17685. |$e_0$|(|$e_1 \ldots e_n$|)
  17686. \end{lstlisting}
  17687. \end{minipage}
  17688. &
  17689. $\Rightarrow$
  17690. &
  17691. \begin{minipage}{0.7\textwidth}
  17692. \begin{lstlisting}
  17693. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17694. AnyType())), |$e'_1, \ldots, e'_n$|)
  17695. \end{lstlisting}
  17696. \end{minipage}
  17697. \\[2ex]\hline
  17698. \begin{minipage}{0.23\textwidth}
  17699. \begin{lstlisting}
  17700. |$e_1$|[|$e_2$|]
  17701. \end{lstlisting}
  17702. \end{minipage}
  17703. &
  17704. $\Rightarrow$
  17705. &
  17706. \begin{minipage}{0.7\textwidth}
  17707. \begin{lstlisting}
  17708. Call(Name('any_tuple_load'),
  17709. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17710. \end{lstlisting}
  17711. \end{minipage}
  17712. %% \begin{minipage}{0.23\textwidth}
  17713. %% \begin{lstlisting}
  17714. %% |$e_2$| if |$e_1$| else |$e_3$|
  17715. %% \end{lstlisting}
  17716. %% \end{minipage}
  17717. %% &
  17718. %% $\Rightarrow$
  17719. %% &
  17720. %% \begin{minipage}{0.7\textwidth}
  17721. %% \begin{lstlisting}
  17722. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17723. %% \end{lstlisting}
  17724. %% \end{minipage}
  17725. %% \\[2ex]\hline
  17726. %% \begin{minipage}{0.23\textwidth}
  17727. %% \begin{lstlisting}
  17728. %% (eq? |$e_1$| |$e_2$|)
  17729. %% \end{lstlisting}
  17730. %% \end{minipage}
  17731. %% &
  17732. %% $\Rightarrow$
  17733. %% &
  17734. %% \begin{minipage}{0.7\textwidth}
  17735. %% \begin{lstlisting}
  17736. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17737. %% \end{lstlisting}
  17738. %% \end{minipage}
  17739. %% \\[2ex]\hline
  17740. %% \begin{minipage}{0.23\textwidth}
  17741. %% \begin{lstlisting}
  17742. %% (not |$e_1$|)
  17743. %% \end{lstlisting}
  17744. %% \end{minipage}
  17745. %% &
  17746. %% $\Rightarrow$
  17747. %% &
  17748. %% \begin{minipage}{0.7\textwidth}
  17749. %% \begin{lstlisting}
  17750. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17751. %% (inject #t Boolean) (inject #f Boolean))
  17752. %% \end{lstlisting}
  17753. %% \end{minipage}
  17754. %% \\[2ex]\hline
  17755. \\\hline
  17756. \end{tabular}
  17757. \fi}
  17758. \end{tcolorbox}
  17759. \caption{Cast insertion}
  17760. \label{fig:compile-r7-Lany}
  17761. \end{figure}
  17762. \section{Reveal Casts}
  17763. \label{sec:reveal-casts-Lany}
  17764. % TODO: define R'_6
  17765. In the \code{reveal\_casts} pass, we recommend compiling
  17766. \code{Project} into a conditional expression that checks whether the
  17767. value's tag matches the target type; if it does, the value is
  17768. converted to a value of the target type by removing the tag; if it
  17769. does not, the program exits.
  17770. %
  17771. {\if\edition\racketEd
  17772. %
  17773. To perform these actions we need a new primitive operation,
  17774. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17775. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17776. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17777. underlying value from a tagged value. The \code{ValueOf} form
  17778. includes the type for the underlying value that is used by the type
  17779. checker.
  17780. %
  17781. \fi}
  17782. %
  17783. {\if\edition\pythonEd\pythonColor
  17784. %
  17785. To perform these actions we need two new AST classes: \code{TagOf} and
  17786. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17787. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17788. the underlying value from a tagged value. The \code{ValueOf}
  17789. operation includes the type for the underlying value which is used by
  17790. the type checker.
  17791. %
  17792. \fi}
  17793. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17794. \code{Project} can be translated as follows.
  17795. \begin{center}
  17796. \begin{minipage}{1.0\textwidth}
  17797. {\if\edition\racketEd
  17798. \begin{lstlisting}
  17799. (Project |$e$| |$\FType$|)
  17800. |$\Rightarrow$|
  17801. (Let |$\itm{tmp}$| |$e'$|
  17802. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17803. (Int |$\itm{tagof}(\FType)$|)))
  17804. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17805. (Exit)))
  17806. \end{lstlisting}
  17807. \fi}
  17808. {\if\edition\pythonEd\pythonColor
  17809. \begin{lstlisting}
  17810. Project(|$e$|, |$\FType$|)
  17811. |$\Rightarrow$|
  17812. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17813. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17814. [Constant(|$\itm{tagof}(\FType)$|)]),
  17815. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17816. Call(Name('exit'), [])))
  17817. \end{lstlisting}
  17818. \fi}
  17819. \end{minipage}
  17820. \end{center}
  17821. If the target type of the projection is a tuple or function type, then
  17822. there is a bit more work to do. For tuples, check that the length of
  17823. the tuple type matches the length of the tuple. For functions, check
  17824. that the number of parameters in the function type matches the
  17825. function's arity.
  17826. Regarding \code{Inject}, we recommend compiling it to a slightly
  17827. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17828. takes a tag instead of a type.
  17829. \begin{center}
  17830. \begin{minipage}{1.0\textwidth}
  17831. {\if\edition\racketEd
  17832. \begin{lstlisting}
  17833. (Inject |$e$| |$\FType$|)
  17834. |$\Rightarrow$|
  17835. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17836. \end{lstlisting}
  17837. \fi}
  17838. {\if\edition\pythonEd\pythonColor
  17839. \begin{lstlisting}
  17840. Inject(|$e$|, |$\FType$|)
  17841. |$\Rightarrow$|
  17842. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17843. \end{lstlisting}
  17844. \fi}
  17845. \end{minipage}
  17846. \end{center}
  17847. {\if\edition\pythonEd\pythonColor
  17848. %
  17849. The introduction of \code{make\_any} makes it difficult to use
  17850. bidirectional type checking because we no longer have an expected type
  17851. to use for type checking the expression $e'$. Thus, we run into
  17852. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17853. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17854. annotated lambda) whose parameters have type annotations and that
  17855. records the return type.
  17856. %
  17857. \fi}
  17858. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17859. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17860. translation of \code{Project}.}
  17861. {\if\edition\racketEd
  17862. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17863. combine the projection action with the vector operation. Also, the
  17864. read and write operations allow arbitrary expressions for the index, so
  17865. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17866. cannot guarantee that the index is within bounds. Thus, we insert code
  17867. to perform bounds checking at runtime. The translation for
  17868. \code{any-vector-ref} is as follows, and the other two operations are
  17869. translated in a similar way:
  17870. \begin{center}
  17871. \begin{minipage}{0.95\textwidth}
  17872. \begin{lstlisting}
  17873. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17874. |$\Rightarrow$|
  17875. (Let |$v$| |$e'_1$|
  17876. (Let |$i$| |$e'_2$|
  17877. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17878. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17879. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17880. (Exit))
  17881. (Exit))))
  17882. \end{lstlisting}
  17883. \end{minipage}
  17884. \end{center}
  17885. \fi}
  17886. %
  17887. {\if\edition\pythonEd\pythonColor
  17888. %
  17889. The \code{any\_tuple\_load} operation combines the projection action
  17890. with the load operation. Also, the load operation allows arbitrary
  17891. expressions for the index so the type checker for \LangAny{}
  17892. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17893. within bounds. Thus, we insert code to perform bounds checking at
  17894. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17895. \begin{lstlisting}
  17896. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17897. |$\Rightarrow$|
  17898. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17899. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17900. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17901. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17902. Call(Name('exit'), [])),
  17903. Call(Name('exit'), [])))
  17904. \end{lstlisting}
  17905. \fi}
  17906. {\if\edition\pythonEd\pythonColor
  17907. \section{Assignment Conversion}
  17908. \label{sec:convert-assignments-Lany}
  17909. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17910. \code{AnnLambda} AST classes.
  17911. \section{Closure Conversion}
  17912. \label{sec:closure-conversion-Lany}
  17913. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17914. \code{AnnLambda} AST classes.
  17915. \fi}
  17916. \section{Remove Complex Operands}
  17917. \label{sec:rco-Lany}
  17918. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17919. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17920. %
  17921. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17922. complex expressions. Their subexpressions must be atomic.}
  17923. \section{Explicate Control and \LangCAny{}}
  17924. \label{sec:explicate-Lany}
  17925. The output of \code{explicate\_control} is the \LangCAny{} language,
  17926. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17927. %
  17928. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17929. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17930. note that the index argument of \code{vector-ref} and
  17931. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17932. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17933. %
  17934. \python{
  17935. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17936. and \code{explicate\_pred} as appropriately to handle the new expressions
  17937. in \LangCAny{}.
  17938. }
  17939. \newcommand{\CanyASTPython}{
  17940. \begin{array}{lcl}
  17941. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17942. &\MID& \key{TagOf}\LP \Atm \RP
  17943. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17944. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17945. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17946. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17947. \end{array}
  17948. }
  17949. \newcommand{\CanyASTRacket}{
  17950. \begin{array}{lcl}
  17951. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17952. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17953. &\MID& \VALUEOF{\Atm}{\FType} \\
  17954. \Tail &::= & \LP\key{Exit}\RP
  17955. \end{array}
  17956. }
  17957. \begin{figure}[tp]
  17958. \begin{tcolorbox}[colback=white]
  17959. \small
  17960. {\if\edition\racketEd
  17961. \[
  17962. \begin{array}{l}
  17963. \gray{\CvarASTRacket} \\ \hline
  17964. \gray{\CifASTRacket} \\ \hline
  17965. \gray{\CloopASTRacket} \\ \hline
  17966. \gray{\CtupASTRacket} \\ \hline
  17967. \gray{\CfunASTRacket} \\ \hline
  17968. \gray{\ClambdaASTRacket} \\ \hline
  17969. \CanyASTRacket \\
  17970. \begin{array}{lcl}
  17971. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17972. \end{array}
  17973. \end{array}
  17974. \]
  17975. \fi}
  17976. {\if\edition\pythonEd\pythonColor
  17977. \[
  17978. \begin{array}{l}
  17979. \gray{\CifASTPython} \\ \hline
  17980. \gray{\CtupASTPython} \\ \hline
  17981. \gray{\CfunASTPython} \\ \hline
  17982. \gray{\ClambdaASTPython} \\ \hline
  17983. \CanyASTPython \\
  17984. \begin{array}{lcl}
  17985. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17986. \end{array}
  17987. \end{array}
  17988. \]
  17989. \fi}
  17990. \end{tcolorbox}
  17991. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17992. \label{fig:c5-syntax}
  17993. \end{figure}
  17994. \section{Select Instructions}
  17995. \label{sec:select-Lany}
  17996. In the \code{select\_instructions} pass, we translate the primitive
  17997. operations on the \ANYTY{} type to x86 instructions that manipulate
  17998. the three tag bits of the tagged value. In the following descriptions,
  17999. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18000. of translating $e$ into an x86 argument:
  18001. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18002. We recommend compiling the
  18003. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18004. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18005. shifts the destination to the left by the number of bits specified its
  18006. source argument (in this case three, the length of the tag), and it
  18007. preserves the sign of the integer. We use the \key{orq} instruction to
  18008. combine the tag and the value to form the tagged value. \\
  18009. %
  18010. {\if\edition\racketEd
  18011. \begin{lstlisting}
  18012. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18013. |$\Rightarrow$|
  18014. movq |$e'$|, |\itm{lhs'}|
  18015. salq $3, |\itm{lhs'}|
  18016. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18017. \end{lstlisting}
  18018. \fi}
  18019. %
  18020. {\if\edition\pythonEd\pythonColor
  18021. \begin{lstlisting}
  18022. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18023. |$\Rightarrow$|
  18024. movq |$e'$|, |\itm{lhs'}|
  18025. salq $3, |\itm{lhs'}|
  18026. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18027. \end{lstlisting}
  18028. \fi}
  18029. %
  18030. The instruction selection for tuples and procedures is different
  18031. because their is no need to shift them to the left. The rightmost 3
  18032. bits are already zeros, so we simply combine the value and the tag
  18033. using \key{orq}. \\
  18034. %
  18035. {\if\edition\racketEd
  18036. \begin{center}
  18037. \begin{minipage}{\textwidth}
  18038. \begin{lstlisting}
  18039. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18040. |$\Rightarrow$|
  18041. movq |$e'$|, |\itm{lhs'}|
  18042. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18043. \end{lstlisting}
  18044. \end{minipage}
  18045. \end{center}
  18046. \fi}
  18047. %
  18048. {\if\edition\pythonEd\pythonColor
  18049. \begin{lstlisting}
  18050. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18051. |$\Rightarrow$|
  18052. movq |$e'$|, |\itm{lhs'}|
  18053. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18054. \end{lstlisting}
  18055. \fi}
  18056. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18057. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18058. operation extracts the type tag from a value of type \ANYTY{}. The
  18059. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18060. bitwise-and of the value with $111$ ($7$ decimal).
  18061. %
  18062. {\if\edition\racketEd
  18063. \begin{lstlisting}
  18064. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18065. |$\Rightarrow$|
  18066. movq |$e'$|, |\itm{lhs'}|
  18067. andq $7, |\itm{lhs'}|
  18068. \end{lstlisting}
  18069. \fi}
  18070. %
  18071. {\if\edition\pythonEd\pythonColor
  18072. \begin{lstlisting}
  18073. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18074. |$\Rightarrow$|
  18075. movq |$e'$|, |\itm{lhs'}|
  18076. andq $7, |\itm{lhs'}|
  18077. \end{lstlisting}
  18078. \fi}
  18079. \paragraph{\code{ValueOf}}
  18080. The instructions for \key{ValueOf} also differ, depending on whether
  18081. the type $T$ is a pointer (tuple or function) or not (integer or
  18082. Boolean). The following shows the instruction selection for integers
  18083. and Booleans, in which we produce an untagged value by shifting it to
  18084. the right by 3 bits:
  18085. %
  18086. {\if\edition\racketEd
  18087. \begin{lstlisting}
  18088. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18089. |$\Rightarrow$|
  18090. movq |$e'$|, |\itm{lhs'}|
  18091. sarq $3, |\itm{lhs'}|
  18092. \end{lstlisting}
  18093. \fi}
  18094. %
  18095. {\if\edition\pythonEd\pythonColor
  18096. \begin{lstlisting}
  18097. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18098. |$\Rightarrow$|
  18099. movq |$e'$|, |\itm{lhs'}|
  18100. sarq $3, |\itm{lhs'}|
  18101. \end{lstlisting}
  18102. \fi}
  18103. %
  18104. In the case for tuples and procedures, we zero out the rightmost 3
  18105. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18106. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18107. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18108. Finally, we apply \code{andq} with the tagged value to get the desired
  18109. result.
  18110. %
  18111. {\if\edition\racketEd
  18112. \begin{lstlisting}
  18113. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18114. |$\Rightarrow$|
  18115. movq $|$-8$|, |\itm{lhs'}|
  18116. andq |$e'$|, |\itm{lhs'}|
  18117. \end{lstlisting}
  18118. \fi}
  18119. %
  18120. {\if\edition\pythonEd\pythonColor
  18121. \begin{lstlisting}
  18122. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18123. |$\Rightarrow$|
  18124. movq $|$-8$|, |\itm{lhs'}|
  18125. andq |$e'$|, |\itm{lhs'}|
  18126. \end{lstlisting}
  18127. \fi}
  18128. %% \paragraph{Type Predicates} We leave it to the reader to
  18129. %% devise a sequence of instructions to implement the type predicates
  18130. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18131. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18132. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18133. operation combines the effect of \code{ValueOf} with accessing the
  18134. length of a tuple from the tag stored at the zero index of the tuple.
  18135. {\if\edition\racketEd
  18136. \begin{lstlisting}
  18137. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18138. |$\Longrightarrow$|
  18139. movq $|$-8$|, %r11
  18140. andq |$e_1'$|, %r11
  18141. movq 0(%r11), %r11
  18142. andq $126, %r11
  18143. sarq $1, %r11
  18144. movq %r11, |$\itm{lhs'}$|
  18145. \end{lstlisting}
  18146. \fi}
  18147. {\if\edition\pythonEd\pythonColor
  18148. \begin{lstlisting}
  18149. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18150. |$\Longrightarrow$|
  18151. movq $|$-8$|, %r11
  18152. andq |$e_1'$|, %r11
  18153. movq 0(%r11), %r11
  18154. andq $126, %r11
  18155. sarq $1, %r11
  18156. movq %r11, |$\itm{lhs'}$|
  18157. \end{lstlisting}
  18158. \fi}
  18159. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18160. This operation combines the effect of \code{ValueOf} with reading an
  18161. element of the tuple (see
  18162. section~\ref{sec:select-instructions-gc}). However, the index may be
  18163. an arbitrary atom, so instead of computing the offset at compile time,
  18164. we must generate instructions to compute the offset at runtime as
  18165. follows. Note the use of the new instruction \code{imulq}.
  18166. \begin{center}
  18167. \begin{minipage}{0.96\textwidth}
  18168. {\if\edition\racketEd
  18169. \begin{lstlisting}
  18170. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18171. |$\Longrightarrow$|
  18172. movq |$\neg 111$|, %r11
  18173. andq |$e_1'$|, %r11
  18174. movq |$e_2'$|, %rax
  18175. addq $1, %rax
  18176. imulq $8, %rax
  18177. addq %rax, %r11
  18178. movq 0(%r11) |$\itm{lhs'}$|
  18179. \end{lstlisting}
  18180. \fi}
  18181. %
  18182. {\if\edition\pythonEd\pythonColor
  18183. \begin{lstlisting}
  18184. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18185. |$\Longrightarrow$|
  18186. movq $|$-8$|, %r11
  18187. andq |$e_1'$|, %r11
  18188. movq |$e_2'$|, %rax
  18189. addq $1, %rax
  18190. imulq $8, %rax
  18191. addq %rax, %r11
  18192. movq 0(%r11) |$\itm{lhs'}$|
  18193. \end{lstlisting}
  18194. \fi}
  18195. \end{minipage}
  18196. \end{center}
  18197. % $ pacify font lock
  18198. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18199. %% The code generation for
  18200. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18201. %% analogous to the above translation for reading from a tuple.
  18202. \section{Register Allocation for \LangAny{}}
  18203. \label{sec:register-allocation-Lany}
  18204. \index{subject}{register allocation}
  18205. There is an interesting interaction between tagged values and garbage
  18206. collection that has an impact on register allocation. A variable of
  18207. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18208. that needs to be inspected and copied during garbage collection. Thus,
  18209. we need to treat variables of type \ANYTY{} in a similar way to
  18210. variables of tuple type for purposes of register allocation,
  18211. with particular attention to the following:
  18212. \begin{itemize}
  18213. \item If a variable of type \ANYTY{} is live during a function call,
  18214. then it must be spilled. This can be accomplished by changing
  18215. \code{build\_interference} to mark all variables of type \ANYTY{}
  18216. that are live after a \code{callq} to be interfering with all the
  18217. registers.
  18218. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18219. the root stack instead of the normal procedure call stack.
  18220. \end{itemize}
  18221. Another concern regarding the root stack is that the garbage collector
  18222. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18223. tagged value that points to a tuple, and (3) a tagged value that is
  18224. not a tuple. We enable this differentiation by choosing not to use the
  18225. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18226. reserved for identifying plain old pointers to tuples. That way, if
  18227. one of the first three bits is set, then we have a tagged value and
  18228. inspecting the tag can differentiate between tuples ($010$) and the
  18229. other kinds of values.
  18230. %% \begin{exercise}\normalfont
  18231. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18232. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18233. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18234. %% compiler on these new programs and all of your previously created test
  18235. %% programs.
  18236. %% \end{exercise}
  18237. \begin{exercise}\normalfont\normalsize
  18238. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18239. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18240. by removing type annotations. Add five more test programs that
  18241. specifically rely on the language being dynamically typed. That is,
  18242. they should not be legal programs in a statically typed language, but
  18243. nevertheless they should be valid \LangDyn{} programs that run to
  18244. completion without error.
  18245. \end{exercise}
  18246. \begin{figure}[p]
  18247. \begin{tcolorbox}[colback=white]
  18248. {\if\edition\racketEd
  18249. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18250. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18251. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18252. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18253. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18254. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18255. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18256. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18257. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18258. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18259. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18260. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18261. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18262. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18263. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18264. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18265. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18266. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18267. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18268. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18269. \path[->,bend left=15] (Lfun) edge [above] node
  18270. {\ttfamily\footnotesize shrink} (Lfun-2);
  18271. \path[->,bend left=15] (Lfun-2) edge [above] node
  18272. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18273. \path[->,bend left=15] (Lfun-3) edge [above] node
  18274. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18275. \path[->,bend left=15] (Lfun-4) edge [left] node
  18276. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18277. \path[->,bend left=15] (Lfun-5) edge [below] node
  18278. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18279. \path[->,bend left=15] (Lfun-6) edge [below] node
  18280. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18281. \path[->,bend right=15] (Lfun-7) edge [above] node
  18282. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18283. \path[->,bend right=15] (F1-2) edge [right] node
  18284. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18285. \path[->,bend right=15] (F1-3) edge [below] node
  18286. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18287. \path[->,bend right=15] (F1-4) edge [below] node
  18288. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18289. \path[->,bend left=15] (F1-5) edge [above] node
  18290. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18291. \path[->,bend left=15] (F1-6) edge [below] node
  18292. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18293. \path[->,bend left=15] (C3-2) edge [right] node
  18294. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18295. \path[->,bend right=15] (x86-2) edge [right] node
  18296. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18297. \path[->,bend right=15] (x86-2-1) edge [below] node
  18298. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18299. \path[->,bend right=15] (x86-2-2) edge [right] node
  18300. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18301. \path[->,bend left=15] (x86-3) edge [above] node
  18302. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18303. \path[->,bend left=15] (x86-4) edge [right] node
  18304. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18305. \end{tikzpicture}
  18306. \fi}
  18307. {\if\edition\pythonEd\pythonColor
  18308. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18309. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18310. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18311. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18312. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18313. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18314. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18315. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18316. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18317. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18318. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18319. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18320. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18321. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18322. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18323. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18324. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18325. \path[->,bend left=15] (Lfun) edge [above] node
  18326. {\ttfamily\footnotesize shrink} (Lfun-2);
  18327. \path[->,bend left=15] (Lfun-2) edge [above] node
  18328. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18329. \path[->,bend left=15] (Lfun-3) edge [above] node
  18330. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18331. \path[->,bend left=15] (Lfun-4) edge [left] node
  18332. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18333. \path[->,bend left=15] (Lfun-5) edge [below] node
  18334. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18335. \path[->,bend right=15] (Lfun-6) edge [above] node
  18336. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18337. \path[->,bend right=15] (Lfun-7) edge [above] node
  18338. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18339. \path[->,bend right=15] (F1-2) edge [right] node
  18340. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18341. \path[->,bend right=15] (F1-3) edge [below] node
  18342. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18343. \path[->,bend left=15] (F1-5) edge [above] node
  18344. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18345. \path[->,bend left=15] (F1-6) edge [below] node
  18346. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18347. \path[->,bend right=15] (C3-2) edge [right] node
  18348. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18349. \path[->,bend right=15] (x86-2) edge [below] node
  18350. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18351. \path[->,bend right=15] (x86-3) edge [below] node
  18352. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18353. \path[->,bend left=15] (x86-4) edge [above] node
  18354. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18355. \end{tikzpicture}
  18356. \fi}
  18357. \end{tcolorbox}
  18358. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18359. \label{fig:Ldyn-passes}
  18360. \end{figure}
  18361. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18362. for the compilation of \LangDyn{}.
  18363. % Further Reading
  18364. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18365. %% {\if\edition\pythonEd\pythonColor
  18366. %% \chapter{Objects}
  18367. %% \label{ch:Lobject}
  18368. %% \index{subject}{objects}
  18369. %% \index{subject}{classes}
  18370. %% \setcounter{footnote}{0}
  18371. %% \fi}
  18372. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18373. \chapter{Gradual Typing}
  18374. \label{ch:Lgrad}
  18375. \index{subject}{gradual typing}
  18376. \setcounter{footnote}{0}
  18377. This chapter studies the language \LangGrad{}, in which the programmer
  18378. can choose between static and dynamic type checking in different parts
  18379. of a program, thereby mixing the statically typed \LangLam{} language
  18380. with the dynamically typed \LangDyn{}. There are several approaches to
  18381. mixing static and dynamic typing, including multilanguage
  18382. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18383. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18384. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18385. programmer controls the amount of static versus dynamic checking by
  18386. adding or removing type annotations on parameters and
  18387. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18388. The definition of the concrete syntax of \LangGrad{} is shown in
  18389. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  18390. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18391. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18392. annotations are optional, which is specified in the grammar using the
  18393. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18394. annotations are not optional, but we use the \CANYTY{} type when a type
  18395. annotation is absent.
  18396. %
  18397. Both the type checker and the interpreter for \LangGrad{} require some
  18398. interesting changes to enable gradual typing, which we discuss in the
  18399. next two sections.
  18400. \newcommand{\LgradGrammarRacket}{
  18401. \begin{array}{lcl}
  18402. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18403. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18404. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18405. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18406. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18407. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18408. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18409. \end{array}
  18410. }
  18411. \newcommand{\LgradASTRacket}{
  18412. \begin{array}{lcl}
  18413. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18414. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18415. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18416. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18417. \itm{op} &::=& \code{procedure-arity} \\
  18418. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18419. \end{array}
  18420. }
  18421. \newcommand{\LgradGrammarPython}{
  18422. \begin{array}{lcl}
  18423. \Type &::=& \key{Any}
  18424. \MID \key{int}
  18425. \MID \key{bool}
  18426. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18427. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18428. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18429. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18430. \MID \CARITY{\Exp} \\
  18431. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18432. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18433. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18434. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18435. \end{array}
  18436. }
  18437. \newcommand{\LgradASTPython}{
  18438. \begin{array}{lcl}
  18439. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18440. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18441. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18442. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18443. &\MID& \ARITY{\Exp} \\
  18444. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18445. \MID \RETURN{\Exp} \\
  18446. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18447. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18448. \end{array}
  18449. }
  18450. \begin{figure}[tp]
  18451. \centering
  18452. \begin{tcolorbox}[colback=white]
  18453. \small
  18454. {\if\edition\racketEd
  18455. \[
  18456. \begin{array}{l}
  18457. \gray{\LintGrammarRacket{}} \\ \hline
  18458. \gray{\LvarGrammarRacket{}} \\ \hline
  18459. \gray{\LifGrammarRacket{}} \\ \hline
  18460. \gray{\LwhileGrammarRacket} \\ \hline
  18461. \gray{\LtupGrammarRacket} \\ \hline
  18462. \LgradGrammarRacket \\
  18463. \begin{array}{lcl}
  18464. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18465. \end{array}
  18466. \end{array}
  18467. \]
  18468. \fi}
  18469. {\if\edition\pythonEd\pythonColor
  18470. \[
  18471. \begin{array}{l}
  18472. \gray{\LintGrammarPython{}} \\ \hline
  18473. \gray{\LvarGrammarPython{}} \\ \hline
  18474. \gray{\LifGrammarPython{}} \\ \hline
  18475. \gray{\LwhileGrammarPython} \\ \hline
  18476. \gray{\LtupGrammarPython} \\ \hline
  18477. \LgradGrammarPython \\
  18478. \begin{array}{lcl}
  18479. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18480. \end{array}
  18481. \end{array}
  18482. \]
  18483. \fi}
  18484. \end{tcolorbox}
  18485. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18486. \label{fig:Lgrad-concrete-syntax}
  18487. \end{figure}
  18488. \begin{figure}[tp]
  18489. \centering
  18490. \begin{tcolorbox}[colback=white]
  18491. \small
  18492. {\if\edition\racketEd
  18493. \[
  18494. \begin{array}{l}
  18495. \gray{\LintOpAST} \\ \hline
  18496. \gray{\LvarASTRacket{}} \\ \hline
  18497. \gray{\LifASTRacket{}} \\ \hline
  18498. \gray{\LwhileASTRacket{}} \\ \hline
  18499. \gray{\LtupASTRacket{}} \\ \hline
  18500. \LgradASTRacket \\
  18501. \begin{array}{lcl}
  18502. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18503. \end{array}
  18504. \end{array}
  18505. \]
  18506. \fi}
  18507. {\if\edition\pythonEd\pythonColor
  18508. \[
  18509. \begin{array}{l}
  18510. \gray{\LintASTPython{}} \\ \hline
  18511. \gray{\LvarASTPython{}} \\ \hline
  18512. \gray{\LifASTPython{}} \\ \hline
  18513. \gray{\LwhileASTPython} \\ \hline
  18514. \gray{\LtupASTPython} \\ \hline
  18515. \LgradASTPython \\
  18516. \begin{array}{lcl}
  18517. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18518. \end{array}
  18519. \end{array}
  18520. \]
  18521. \fi}
  18522. \end{tcolorbox}
  18523. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18524. \label{fig:Lgrad-syntax}
  18525. \end{figure}
  18526. % TODO: more road map -Jeremy
  18527. %\clearpage
  18528. \section{Type Checking \LangGrad{}}
  18529. \label{sec:gradual-type-check}
  18530. We begin by discussing the type checking of a partially typed variant
  18531. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18532. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18533. statically typed, so there is nothing special happening there with
  18534. respect to type checking. On the other hand, the \code{inc} function
  18535. does not have type annotations, so the type checker assigns the type
  18536. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18537. \code{+} operator inside \code{inc}. It expects both arguments to have
  18538. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18539. a gradually typed language, such differences are allowed so long as
  18540. the types are \emph{consistent}; that is, they are equal except in
  18541. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18542. is consistent with every other type. Figure~\ref{fig:consistent}
  18543. shows the definition of the
  18544. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18545. %
  18546. So the type checker allows the \code{+} operator to be applied
  18547. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18548. %
  18549. Next consider the call to the \code{map} function shown in
  18550. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18551. tuple. The \code{inc} function has type
  18552. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18553. but parameter \code{f} of \code{map} has type
  18554. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18555. The type checker for \LangGrad{} accepts this call because the two types are
  18556. consistent.
  18557. \begin{figure}[btp]
  18558. % gradual_test_9.rkt
  18559. \begin{tcolorbox}[colback=white]
  18560. {\if\edition\racketEd
  18561. \begin{lstlisting}
  18562. (define (map [f : (Integer -> Integer)]
  18563. [v : (Vector Integer Integer)])
  18564. : (Vector Integer Integer)
  18565. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18566. (define (inc x) (+ x 1))
  18567. (vector-ref (map inc (vector 0 41)) 1)
  18568. \end{lstlisting}
  18569. \fi}
  18570. {\if\edition\pythonEd\pythonColor
  18571. \begin{lstlisting}
  18572. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18573. return f(v[0]), f(v[1])
  18574. def inc(x):
  18575. return x + 1
  18576. t = map(inc, (0, 41))
  18577. print(t[1])
  18578. \end{lstlisting}
  18579. \fi}
  18580. \end{tcolorbox}
  18581. \caption{A partially typed version of the \code{map} example.}
  18582. \label{fig:gradual-map}
  18583. \end{figure}
  18584. \begin{figure}[tbp]
  18585. \begin{tcolorbox}[colback=white]
  18586. {\if\edition\racketEd
  18587. \begin{lstlisting}
  18588. (define/public (consistent? t1 t2)
  18589. (match* (t1 t2)
  18590. [('Integer 'Integer) #t]
  18591. [('Boolean 'Boolean) #t]
  18592. [('Void 'Void) #t]
  18593. [('Any t2) #t]
  18594. [(t1 'Any) #t]
  18595. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18596. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18597. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18598. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18599. (consistent? rt1 rt2))]
  18600. [(other wise) #f]))
  18601. \end{lstlisting}
  18602. \fi}
  18603. {\if\edition\pythonEd\pythonColor
  18604. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18605. def consistent(self, t1, t2):
  18606. match (t1, t2):
  18607. case (AnyType(), _):
  18608. return True
  18609. case (_, AnyType()):
  18610. return True
  18611. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18612. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18613. case (TupleType(ts1), TupleType(ts2)):
  18614. return all(map(self.consistent, ts1, ts2))
  18615. case (_, _):
  18616. return t1 == t2
  18617. \end{lstlisting}
  18618. \fi}
  18619. \end{tcolorbox}
  18620. \caption{The consistency method on types.}
  18621. \label{fig:consistent}
  18622. \end{figure}
  18623. It is also helpful to consider how gradual typing handles programs with an
  18624. error, such as applying \code{map} to a function that sometimes
  18625. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18626. type checker for \LangGrad{} accepts this program because the type of
  18627. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18628. \code{map}; that is,
  18629. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18630. is consistent with
  18631. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18632. One might say that a gradual type checker is optimistic in that it
  18633. accepts programs that might execute without a runtime type error.
  18634. %
  18635. The definition of the type checker for \LangGrad{} is shown in
  18636. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18637. and \ref{fig:type-check-Lgradual-3}.
  18638. %% \begin{figure}[tp]
  18639. %% \centering
  18640. %% \fbox{
  18641. %% \begin{minipage}{0.96\textwidth}
  18642. %% \small
  18643. %% \[
  18644. %% \begin{array}{lcl}
  18645. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18646. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18647. %% \end{array}
  18648. %% \]
  18649. %% \end{minipage}
  18650. %% }
  18651. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18652. %% \label{fig:Lgrad-prime-syntax}
  18653. %% \end{figure}
  18654. \begin{figure}[tbp]
  18655. \begin{tcolorbox}[colback=white]
  18656. {\if\edition\racketEd
  18657. \begin{lstlisting}
  18658. (define (map [f : (Integer -> Integer)]
  18659. [v : (Vector Integer Integer)])
  18660. : (Vector Integer Integer)
  18661. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18662. (define (inc x) (+ x 1))
  18663. (define (true) #t)
  18664. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18665. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18666. \end{lstlisting}
  18667. \fi}
  18668. {\if\edition\pythonEd\pythonColor
  18669. \begin{lstlisting}
  18670. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18671. return f(v[0]), f(v[1])
  18672. def inc(x):
  18673. return x + 1
  18674. def true():
  18675. return True
  18676. def maybe_inc(x):
  18677. return inc(x) if input_int() == 0 else true()
  18678. t = map(maybe_inc, (0, 41))
  18679. print( t[1] )
  18680. \end{lstlisting}
  18681. \fi}
  18682. \end{tcolorbox}
  18683. \caption{A variant of the \code{map} example with an error.}
  18684. \label{fig:map-maybe_inc}
  18685. \end{figure}
  18686. Running this program with input \code{1} triggers an
  18687. error when the \code{maybe\_inc} function returns
  18688. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18689. performs checking at runtime to ensure the integrity of the static
  18690. types, such as the
  18691. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18692. annotation on
  18693. parameter \code{f} of \code{map}.
  18694. Here we give a preview of how the runtime checking is accomplished;
  18695. the following sections provide the details.
  18696. The runtime checking is carried out by a new \code{Cast} AST node that
  18697. is generated in a new pass named \code{cast\_insert}. The output of
  18698. \code{cast\_insert} is a program in the \LangCast{} language, which
  18699. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18700. %
  18701. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18702. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18703. inserted every time the type checker encounters two types that are
  18704. consistent but not equal. In the \code{inc} function, \code{x} is
  18705. cast to \INTTY{} and the result of the \code{+} is cast to
  18706. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18707. is cast from
  18708. \racket{\code{(Any -> Any)}}
  18709. \python{\code{Callable[[Any], Any]}}
  18710. to
  18711. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18712. %
  18713. In the next section we see how to interpret the \code{Cast} node.
  18714. \begin{figure}[btp]
  18715. \begin{tcolorbox}[colback=white]
  18716. {\if\edition\racketEd
  18717. \begin{lstlisting}
  18718. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18719. : (Vector Integer Integer)
  18720. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18721. (define (inc [x : Any]) : Any
  18722. (cast (+ (cast x Any Integer) 1) Integer Any))
  18723. (define (true) : Any (cast #t Boolean Any))
  18724. (define (maybe_inc [x : Any]) : Any
  18725. (if (eq? 0 (read)) (inc x) (true)))
  18726. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18727. (vector 0 41)) 0)
  18728. \end{lstlisting}
  18729. \fi}
  18730. {\if\edition\pythonEd\pythonColor
  18731. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18732. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18733. return f(v[0]), f(v[1])
  18734. def inc(x : Any) -> Any:
  18735. return Cast(Cast(x, Any, int) + 1, int, Any)
  18736. def true() -> Any:
  18737. return Cast(True, bool, Any)
  18738. def maybe_inc(x : Any) -> Any:
  18739. return inc(x) if input_int() == 0 else true()
  18740. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18741. (0, 41))
  18742. print(t[1])
  18743. \end{lstlisting}
  18744. \fi}
  18745. \end{tcolorbox}
  18746. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18747. and \code{maybe\_inc} example.}
  18748. \label{fig:map-cast}
  18749. \end{figure}
  18750. {\if\edition\pythonEd\pythonColor
  18751. \begin{figure}[tbp]
  18752. \begin{tcolorbox}[colback=white]
  18753. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18754. class TypeCheckLgrad(TypeCheckLlambda):
  18755. def type_check_exp(self, e, env) -> Type:
  18756. match e:
  18757. case Name(id):
  18758. return env[id]
  18759. case Constant(value) if isinstance(value, bool):
  18760. return BoolType()
  18761. case Constant(value) if isinstance(value, int):
  18762. return IntType()
  18763. case Call(Name('input_int'), []):
  18764. return IntType()
  18765. case BinOp(left, op, right):
  18766. left_type = self.type_check_exp(left, env)
  18767. self.check_consistent(left_type, IntType(), left)
  18768. right_type = self.type_check_exp(right, env)
  18769. self.check_consistent(right_type, IntType(), right)
  18770. return IntType()
  18771. case IfExp(test, body, orelse):
  18772. test_t = self.type_check_exp(test, env)
  18773. self.check_consistent(test_t, BoolType(), test)
  18774. body_t = self.type_check_exp(body, env)
  18775. orelse_t = self.type_check_exp(orelse, env)
  18776. self.check_consistent(body_t, orelse_t, e)
  18777. return self.join_types(body_t, orelse_t)
  18778. case Call(func, args):
  18779. func_t = self.type_check_exp(func, env)
  18780. args_t = [self.type_check_exp(arg, env) for arg in args]
  18781. match func_t:
  18782. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18783. for (arg_t, param_t) in zip(args_t, params_t):
  18784. self.check_consistent(param_t, arg_t, e)
  18785. return return_t
  18786. case AnyType():
  18787. return AnyType()
  18788. case _:
  18789. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18790. ...
  18791. case _:
  18792. raise Exception('type_check_exp: unexpected ' + repr(e))
  18793. \end{lstlisting}
  18794. \end{tcolorbox}
  18795. \caption{Type checking expressions in the \LangGrad{} language.}
  18796. \label{fig:type-check-Lgradual-1}
  18797. \end{figure}
  18798. \begin{figure}[tbp]
  18799. \begin{tcolorbox}[colback=white]
  18800. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18801. def check_exp(self, e, expected_ty, env):
  18802. match e:
  18803. case Lambda(params, body):
  18804. match expected_ty:
  18805. case FunctionType(params_t, return_t):
  18806. new_env = env.copy().update(zip(params, params_t))
  18807. e.has_type = expected_ty
  18808. body_ty = self.type_check_exp(body, new_env)
  18809. self.check_consistent(body_ty, return_t)
  18810. case AnyType():
  18811. new_env = env.copy().update((p, AnyType()) for p in params)
  18812. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18813. body_ty = self.type_check_exp(body, new_env)
  18814. case _:
  18815. raise Exception('lambda does not have type ' + str(expected_ty))
  18816. case _:
  18817. e_ty = self.type_check_exp(e, env)
  18818. self.check_consistent(e_ty, expected_ty, e)
  18819. \end{lstlisting}
  18820. \end{tcolorbox}
  18821. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18822. \label{fig:type-check-Lgradual-2}
  18823. \end{figure}
  18824. \begin{figure}[tbp]
  18825. \begin{tcolorbox}[colback=white]
  18826. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18827. def type_check_stmt(self, s, env, return_type):
  18828. match s:
  18829. case Assign([Name(id)], value):
  18830. value_ty = self.type_check_exp(value, env)
  18831. if id in env:
  18832. self.check_consistent(env[id], value_ty, value)
  18833. else:
  18834. env[id] = value_ty
  18835. ...
  18836. case _:
  18837. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18838. def type_check_stmts(self, ss, env, return_type):
  18839. for s in ss:
  18840. self.type_check_stmt(s, env, return_type)
  18841. \end{lstlisting}
  18842. \end{tcolorbox}
  18843. \caption{Type checking statements in the \LangGrad{} language.}
  18844. \label{fig:type-check-Lgradual-3}
  18845. \end{figure}
  18846. \begin{figure}[tbp]
  18847. \begin{tcolorbox}[colback=white]
  18848. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18849. def join_types(self, t1, t2):
  18850. match (t1, t2):
  18851. case (AnyType(), _):
  18852. return t2
  18853. case (_, AnyType()):
  18854. return t1
  18855. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18856. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18857. self.join_types(rt1,rt2))
  18858. case (TupleType(ts1), TupleType(ts2)):
  18859. return TupleType(list(map(self.join_types, ts1, ts2)))
  18860. case (_, _):
  18861. return t1
  18862. def check_consistent(self, t1, t2, e):
  18863. if not self.consistent(t1, t2):
  18864. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18865. + ' in ' + repr(e))
  18866. \end{lstlisting}
  18867. \end{tcolorbox}
  18868. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18869. \label{fig:type-check-Lgradual-aux}
  18870. \end{figure}
  18871. \fi}
  18872. {\if\edition\racketEd
  18873. \begin{figure}[tbp]
  18874. \begin{tcolorbox}[colback=white]
  18875. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18876. (define/override (type-check-exp env)
  18877. (lambda (e)
  18878. (define recur (type-check-exp env))
  18879. (match e
  18880. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18881. (define-values (new-es ts)
  18882. (for/lists (exprs types) ([e es])
  18883. (recur e)))
  18884. (define t-ret (type-check-op op ts e))
  18885. (values (Prim op new-es) t-ret)]
  18886. [(Prim 'eq? (list e1 e2))
  18887. (define-values (e1^ t1) (recur e1))
  18888. (define-values (e2^ t2) (recur e2))
  18889. (check-consistent? t1 t2 e)
  18890. (define T (meet t1 t2))
  18891. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18892. [(Prim 'and (list e1 e2))
  18893. (recur (If e1 e2 (Bool #f)))]
  18894. [(Prim 'or (list e1 e2))
  18895. (define tmp (gensym 'tmp))
  18896. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18897. [(If e1 e2 e3)
  18898. (define-values (e1^ T1) (recur e1))
  18899. (define-values (e2^ T2) (recur e2))
  18900. (define-values (e3^ T3) (recur e3))
  18901. (check-consistent? T1 'Boolean e)
  18902. (check-consistent? T2 T3 e)
  18903. (define Tif (meet T2 T3))
  18904. (values (If e1^ e2^ e3^) Tif)]
  18905. [(SetBang x e1)
  18906. (define-values (e1^ T1) (recur e1))
  18907. (define varT (dict-ref env x))
  18908. (check-consistent? T1 varT e)
  18909. (values (SetBang x e1^) 'Void)]
  18910. [(WhileLoop e1 e2)
  18911. (define-values (e1^ T1) (recur e1))
  18912. (check-consistent? T1 'Boolean e)
  18913. (define-values (e2^ T2) ((type-check-exp env) e2))
  18914. (values (WhileLoop e1^ e2^) 'Void)]
  18915. [(Prim 'vector-length (list e1))
  18916. (define-values (e1^ t) (recur e1))
  18917. (match t
  18918. [`(Vector ,ts ...)
  18919. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18920. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18921. \end{lstlisting}
  18922. \end{tcolorbox}
  18923. \caption{Type checker for the \LangGrad{} language, part 1.}
  18924. \label{fig:type-check-Lgradual-1}
  18925. \end{figure}
  18926. \begin{figure}[tbp]
  18927. \begin{tcolorbox}[colback=white]
  18928. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18929. [(Prim 'vector-ref (list e1 e2))
  18930. (define-values (e1^ t1) (recur e1))
  18931. (define-values (e2^ t2) (recur e2))
  18932. (check-consistent? t2 'Integer e)
  18933. (match t1
  18934. [`(Vector ,ts ...)
  18935. (match e2^
  18936. [(Int i)
  18937. (unless (and (0 . <= . i) (i . < . (length ts)))
  18938. (error 'type-check "invalid index ~a in ~a" i e))
  18939. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18940. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18941. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18942. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18943. [(Prim 'vector-set! (list e1 e2 e3) )
  18944. (define-values (e1^ t1) (recur e1))
  18945. (define-values (e2^ t2) (recur e2))
  18946. (define-values (e3^ t3) (recur e3))
  18947. (check-consistent? t2 'Integer e)
  18948. (match t1
  18949. [`(Vector ,ts ...)
  18950. (match e2^
  18951. [(Int i)
  18952. (unless (and (0 . <= . i) (i . < . (length ts)))
  18953. (error 'type-check "invalid index ~a in ~a" i e))
  18954. (check-consistent? (list-ref ts i) t3 e)
  18955. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18956. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18957. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18958. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18959. [(Apply e1 e2s)
  18960. (define-values (e1^ T1) (recur e1))
  18961. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18962. (match T1
  18963. [`(,T1ps ... -> ,T1rt)
  18964. (for ([T2 T2s] [Tp T1ps])
  18965. (check-consistent? T2 Tp e))
  18966. (values (Apply e1^ e2s^) T1rt)]
  18967. [`Any (values (Apply e1^ e2s^) 'Any)]
  18968. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18969. [(Lambda params Tr e1)
  18970. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18971. (match p
  18972. [`[,x : ,T] (values x T)]
  18973. [(? symbol? x) (values x 'Any)])))
  18974. (define-values (e1^ T1)
  18975. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18976. (check-consistent? Tr T1 e)
  18977. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18978. `(,@Ts -> ,Tr))]
  18979. [else ((super type-check-exp env) e)]
  18980. )))
  18981. \end{lstlisting}
  18982. \end{tcolorbox}
  18983. \caption{Type checker for the \LangGrad{} language, part 2.}
  18984. \label{fig:type-check-Lgradual-2}
  18985. \end{figure}
  18986. \begin{figure}[tbp]
  18987. \begin{tcolorbox}[colback=white]
  18988. \begin{lstlisting}
  18989. (define/override (type-check-def env)
  18990. (lambda (e)
  18991. (match e
  18992. [(Def f params rt info body)
  18993. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18994. (match p
  18995. [`[,x : ,T] (values x T)]
  18996. [(? symbol? x) (values x 'Any)])))
  18997. (define new-env (append (map cons xs ps) env))
  18998. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18999. (check-consistent? ty^ rt e)
  19000. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19001. [else (error 'type-check "ill-formed function definition ~a" e)]
  19002. )))
  19003. (define/override (type-check-program e)
  19004. (match e
  19005. [(Program info body)
  19006. (define-values (body^ ty) ((type-check-exp '()) body))
  19007. (check-consistent? ty 'Integer e)
  19008. (ProgramDefsExp info '() body^)]
  19009. [(ProgramDefsExp info ds body)
  19010. (define new-env (for/list ([d ds])
  19011. (cons (Def-name d) (fun-def-type d))))
  19012. (define ds^ (for/list ([d ds])
  19013. ((type-check-def new-env) d)))
  19014. (define-values (body^ ty) ((type-check-exp new-env) body))
  19015. (check-consistent? ty 'Integer e)
  19016. (ProgramDefsExp info ds^ body^)]
  19017. [else (super type-check-program e)]))
  19018. \end{lstlisting}
  19019. \end{tcolorbox}
  19020. \caption{Type checker for the \LangGrad{} language, part 3.}
  19021. \label{fig:type-check-Lgradual-3}
  19022. \end{figure}
  19023. \begin{figure}[tbp]
  19024. \begin{tcolorbox}[colback=white]
  19025. \begin{lstlisting}
  19026. (define/public (join t1 t2)
  19027. (match* (t1 t2)
  19028. [('Integer 'Integer) 'Integer]
  19029. [('Boolean 'Boolean) 'Boolean]
  19030. [('Void 'Void) 'Void]
  19031. [('Any t2) t2]
  19032. [(t1 'Any) t1]
  19033. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19034. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19035. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19036. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19037. -> ,(join rt1 rt2))]))
  19038. (define/public (meet t1 t2)
  19039. (match* (t1 t2)
  19040. [('Integer 'Integer) 'Integer]
  19041. [('Boolean 'Boolean) 'Boolean]
  19042. [('Void 'Void) 'Void]
  19043. [('Any t2) 'Any]
  19044. [(t1 'Any) 'Any]
  19045. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19046. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19047. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19048. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19049. -> ,(meet rt1 rt2))]))
  19050. (define/public (check-consistent? t1 t2 e)
  19051. (unless (consistent? t1 t2)
  19052. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19053. (define explicit-prim-ops
  19054. (set-union
  19055. (type-predicates)
  19056. (set 'procedure-arity 'eq? 'not 'and 'or
  19057. 'vector 'vector-length 'vector-ref 'vector-set!
  19058. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19059. (define/override (fun-def-type d)
  19060. (match d
  19061. [(Def f params rt info body)
  19062. (define ps
  19063. (for/list ([p params])
  19064. (match p
  19065. [`[,x : ,T] T]
  19066. [(? symbol?) 'Any]
  19067. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19068. `(,@ps -> ,rt)]
  19069. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19070. \end{lstlisting}
  19071. \end{tcolorbox}
  19072. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19073. \label{fig:type-check-Lgradual-aux}
  19074. \end{figure}
  19075. \fi}
  19076. \clearpage
  19077. \section{Interpreting \LangCast{}}
  19078. \label{sec:interp-casts}
  19079. The runtime behavior of casts involving simple types such as
  19080. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19081. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19082. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19083. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19084. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19085. operator, by checking the value's tag and either retrieving
  19086. the underlying integer or signaling an error if the tag is not the
  19087. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19088. %
  19089. Things get more interesting with casts involving
  19090. \racket{function and tuple types}\python{function, tuple, and array types}.
  19091. Consider the cast of the function \code{maybe\_inc} from
  19092. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19093. to
  19094. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19095. shown in figure~\ref{fig:map-maybe_inc}.
  19096. When the \code{maybe\_inc} function flows through
  19097. this cast at runtime, we don't know whether it will return
  19098. an integer, because that depends on the input from the user.
  19099. The \LangCast{} interpreter therefore delays the checking
  19100. of the cast until the function is applied. To do so it
  19101. wraps \code{maybe\_inc} in a new function that casts its parameter
  19102. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19103. casts the return value from \CANYTY{} to \INTTY{}.
  19104. {\if\edition\pythonEd\pythonColor
  19105. %
  19106. There are further complications regarding casts on mutable data
  19107. such as the \code{list} type introduced in
  19108. the challenge assignment of section~\ref{sec:arrays}.
  19109. %
  19110. \fi}
  19111. %
  19112. Consider the example presented in figure~\ref{fig:map-bang} that
  19113. defines a partially typed version of \code{map} whose parameter
  19114. \code{v} has type
  19115. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19116. and that updates \code{v} in place
  19117. instead of returning a new tuple. So, we name this function
  19118. \code{map\_inplace}. We apply \code{map\_inplace} to an
  19119. \racket{tuple}\python{array} of integers, so the type checker inserts a
  19120. cast from
  19121. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19122. to
  19123. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19124. A naive way for the \LangCast{} interpreter to cast between
  19125. \racket{tuple}\python{array} types would be a build a new
  19126. \racket{tuple}\python{array}
  19127. whose elements are the result
  19128. of casting each of the original elements to the appropriate target
  19129. type.
  19130. However, this approach is not valid for mutable data structures.
  19131. In the example of figure~\ref{fig:map-bang},
  19132. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19133. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19134. the original one.
  19135. \begin{figure}[tbp]
  19136. \begin{tcolorbox}[colback=white]
  19137. % gradual_test_11.rkt
  19138. {\if\edition\racketEd
  19139. \begin{lstlisting}
  19140. (define (map_inplace [f : (Any -> Any)]
  19141. [v : (Vector Any Any)]) : Void
  19142. (begin
  19143. (vector-set! v 0 (f (vector-ref v 0)))
  19144. (vector-set! v 1 (f (vector-ref v 1)))))
  19145. (define (inc x) (+ x 1))
  19146. (let ([v (vector 0 41)])
  19147. (begin (map_inplace inc v) (vector-ref v 1)))
  19148. \end{lstlisting}
  19149. \fi}
  19150. {\if\edition\pythonEd\pythonColor
  19151. \begin{lstlisting}
  19152. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19153. i = 0
  19154. while i != len(v):
  19155. v[i] = f(v[i])
  19156. i = i + 1
  19157. def inc(x : int) -> int:
  19158. return x + 1
  19159. v = [0, 41]
  19160. map_inplace(inc, v)
  19161. print( v[1] )
  19162. \end{lstlisting}
  19163. \fi}
  19164. \end{tcolorbox}
  19165. \caption{An example involving casts on arrays.}
  19166. \label{fig:map-bang}
  19167. \end{figure}
  19168. Instead the interpreter needs to create a new kind of value, a
  19169. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19170. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19171. and then applies a
  19172. cast to the resulting value. On a write, the proxy casts the argument
  19173. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19174. \racket{
  19175. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19176. \code{0} from \INTTY{} to \CANYTY{}.
  19177. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19178. from \CANYTY{} to \INTTY{}.
  19179. }
  19180. \python{
  19181. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19182. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19183. For the subscript on the left of the assignment,
  19184. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19185. }
  19186. The final category of cast that we need to consider consist of casts between
  19187. the \CANYTY{} type and higher-order types such as functions and
  19188. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  19189. variant of \code{map\_inplace} in which parameter \code{v} does not
  19190. have a type annotation, so it is given type \CANYTY{}. In the call to
  19191. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19192. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19193. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19194. \code{Inject}, but that doesn't work because
  19195. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19196. a flat type. Instead, we must first cast to
  19197. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19198. and then inject to \CANYTY{}.
  19199. \begin{figure}[tbp]
  19200. \begin{tcolorbox}[colback=white]
  19201. {\if\edition\racketEd
  19202. \begin{lstlisting}
  19203. (define (map_inplace [f : (Any -> Any)] v) : Void
  19204. (begin
  19205. (vector-set! v 0 (f (vector-ref v 0)))
  19206. (vector-set! v 1 (f (vector-ref v 1)))))
  19207. (define (inc x) (+ x 1))
  19208. (let ([v (vector 0 41)])
  19209. (begin (map_inplace inc v) (vector-ref v 1)))
  19210. \end{lstlisting}
  19211. \fi}
  19212. {\if\edition\pythonEd\pythonColor
  19213. \begin{lstlisting}
  19214. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19215. i = 0
  19216. while i != len(v):
  19217. v[i] = f(v[i])
  19218. i = i + 1
  19219. def inc(x):
  19220. return x + 1
  19221. v = [0, 41]
  19222. map_inplace(inc, v)
  19223. print( v[1] )
  19224. \end{lstlisting}
  19225. \fi}
  19226. \end{tcolorbox}
  19227. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  19228. \label{fig:map-any}
  19229. \end{figure}
  19230. \begin{figure}[tbp]
  19231. \begin{tcolorbox}[colback=white]
  19232. {\if\edition\racketEd
  19233. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19234. (define/public (apply_cast v s t)
  19235. (match* (s t)
  19236. [(t1 t2) #:when (equal? t1 t2) v]
  19237. [('Any t2)
  19238. (match t2
  19239. [`(,ts ... -> ,rt)
  19240. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19241. (define v^ (apply-project v any->any))
  19242. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19243. [`(Vector ,ts ...)
  19244. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19245. (define v^ (apply-project v vec-any))
  19246. (apply_cast v^ vec-any `(Vector ,@ts))]
  19247. [else (apply-project v t2)])]
  19248. [(t1 'Any)
  19249. (match t1
  19250. [`(,ts ... -> ,rt)
  19251. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19252. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19253. (apply-inject v^ (any-tag any->any))]
  19254. [`(Vector ,ts ...)
  19255. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19256. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19257. (apply-inject v^ (any-tag vec-any))]
  19258. [else (apply-inject v (any-tag t1))])]
  19259. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19260. (define x (gensym 'x))
  19261. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19262. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19263. (define cast-writes
  19264. (for/list ([t1 ts1] [t2 ts2])
  19265. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19266. `(vector-proxy ,(vector v (apply vector cast-reads)
  19267. (apply vector cast-writes)))]
  19268. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19269. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19270. `(function ,xs ,(Cast
  19271. (Apply (Value v)
  19272. (for/list ([x xs][t1 ts1][t2 ts2])
  19273. (Cast (Var x) t2 t1)))
  19274. rt1 rt2) ())]
  19275. ))
  19276. \end{lstlisting}
  19277. \fi}
  19278. {\if\edition\pythonEd\pythonColor
  19279. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19280. def apply_cast(self, value, src, tgt):
  19281. match (src, tgt):
  19282. case (AnyType(), FunctionType(ps2, rt2)):
  19283. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19284. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19285. case (AnyType(), TupleType(ts2)):
  19286. anytup = TupleType([AnyType() for t1 in ts2])
  19287. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19288. case (AnyType(), ListType(t2)):
  19289. anylist = ListType([AnyType() for t1 in ts2])
  19290. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19291. case (AnyType(), AnyType()):
  19292. return value
  19293. case (AnyType(), _):
  19294. return self.apply_project(value, tgt)
  19295. case (FunctionType(ps1,rt1), AnyType()):
  19296. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19297. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19298. case (TupleType(ts1), AnyType()):
  19299. anytup = TupleType([AnyType() for t1 in ts1])
  19300. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19301. case (ListType(t1), AnyType()):
  19302. anylist = ListType(AnyType())
  19303. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19304. case (_, AnyType()):
  19305. return self.apply_inject(value, src)
  19306. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19307. params = [generate_name('x') for p in ps2]
  19308. args = [Cast(Name(x), t2, t1)
  19309. for (x,t1,t2) in zip(params, ps1, ps2)]
  19310. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19311. return Function('cast', params, [Return(body)], {})
  19312. case (TupleType(ts1), TupleType(ts2)):
  19313. x = generate_name('x')
  19314. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19315. for (t1,t2) in zip(ts1,ts2)]
  19316. return ProxiedTuple(value, reads)
  19317. case (ListType(t1), ListType(t2)):
  19318. x = generate_name('x')
  19319. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19320. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19321. return ProxiedList(value, read, write)
  19322. case (t1, t2) if t1 == t2:
  19323. return value
  19324. case (t1, t2):
  19325. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19326. def apply_inject(self, value, src):
  19327. return Tagged(value, self.type_to_tag(src))
  19328. def apply_project(self, value, tgt):
  19329. match value:
  19330. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19331. return val
  19332. case _:
  19333. raise Exception('apply_project, unexpected ' + repr(value))
  19334. \end{lstlisting}
  19335. \fi}
  19336. \end{tcolorbox}
  19337. \caption{The \code{apply\_cast} auxiliary method.}
  19338. \label{fig:apply_cast}
  19339. \end{figure}
  19340. The \LangCast{} interpreter uses an auxiliary function named
  19341. \code{apply\_cast} to cast a value from a source type to a target type,
  19342. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19343. the kinds of casts that we've discussed in this section.
  19344. %
  19345. The definition of the interpreter for \LangCast{} is shown in
  19346. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19347. dispatching to \code{apply\_cast}.
  19348. \racket{To handle the addition of tuple
  19349. proxies, we update the tuple primitives in \code{interp-op} using the
  19350. functions given in figure~\ref{fig:guarded-tuple}.}
  19351. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19352. \begin{figure}[tbp]
  19353. \begin{tcolorbox}[colback=white]
  19354. {\if\edition\racketEd
  19355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19356. (define interp-Lcast-class
  19357. (class interp-Llambda-class
  19358. (super-new)
  19359. (inherit apply-fun apply-inject apply-project)
  19360. (define/override (interp-op op)
  19361. (match op
  19362. ['vector-length guarded-vector-length]
  19363. ['vector-ref guarded-vector-ref]
  19364. ['vector-set! guarded-vector-set!]
  19365. ['any-vector-ref (lambda (v i)
  19366. (match v [`(tagged ,v^ ,tg)
  19367. (guarded-vector-ref v^ i)]))]
  19368. ['any-vector-set! (lambda (v i a)
  19369. (match v [`(tagged ,v^ ,tg)
  19370. (guarded-vector-set! v^ i a)]))]
  19371. ['any-vector-length (lambda (v)
  19372. (match v [`(tagged ,v^ ,tg)
  19373. (guarded-vector-length v^)]))]
  19374. [else (super interp-op op)]
  19375. ))
  19376. (define/override ((interp-exp env) e)
  19377. (define (recur e) ((interp-exp env) e))
  19378. (match e
  19379. [(Value v) v]
  19380. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19381. [else ((super interp-exp env) e)]))
  19382. ))
  19383. (define (interp-Lcast p)
  19384. (send (new interp-Lcast-class) interp-program p))
  19385. \end{lstlisting}
  19386. \fi}
  19387. {\if\edition\pythonEd\pythonColor
  19388. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19389. class InterpLcast(InterpLany):
  19390. def interp_exp(self, e, env):
  19391. match e:
  19392. case Cast(value, src, tgt):
  19393. v = self.interp_exp(value, env)
  19394. return self.apply_cast(v, src, tgt)
  19395. case ValueExp(value):
  19396. return value
  19397. ...
  19398. case _:
  19399. return super().interp_exp(e, env)
  19400. \end{lstlisting}
  19401. \fi}
  19402. \end{tcolorbox}
  19403. \caption{The interpreter for \LangCast{}.}
  19404. \label{fig:interp-Lcast}
  19405. \end{figure}
  19406. {\if\edition\racketEd
  19407. \begin{figure}[tbp]
  19408. \begin{tcolorbox}[colback=white]
  19409. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19410. (define (guarded-vector-ref vec i)
  19411. (match vec
  19412. [`(vector-proxy ,proxy)
  19413. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19414. (define rd (vector-ref (vector-ref proxy 1) i))
  19415. (apply-fun rd (list val) 'guarded-vector-ref)]
  19416. [else (vector-ref vec i)]))
  19417. (define (guarded-vector-set! vec i arg)
  19418. (match vec
  19419. [`(vector-proxy ,proxy)
  19420. (define wr (vector-ref (vector-ref proxy 2) i))
  19421. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19422. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19423. [else (vector-set! vec i arg)]))
  19424. (define (guarded-vector-length vec)
  19425. (match vec
  19426. [`(vector-proxy ,proxy)
  19427. (guarded-vector-length (vector-ref proxy 0))]
  19428. [else (vector-length vec)]))
  19429. \end{lstlisting}
  19430. %% {\if\edition\pythonEd\pythonColor
  19431. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19432. %% UNDER CONSTRUCTION
  19433. %% \end{lstlisting}
  19434. %% \fi}
  19435. \end{tcolorbox}
  19436. \caption{The \code{guarded-vector} auxiliary functions.}
  19437. \label{fig:guarded-tuple}
  19438. \end{figure}
  19439. \fi}
  19440. {\if\edition\pythonEd\pythonColor
  19441. \section{Overload Resolution}
  19442. \label{sec:gradual-resolution}
  19443. Recall that when we added support for arrays in
  19444. section~\ref{sec:arrays}, the syntax for the array operations were the
  19445. same as for tuple operations (e.g., accessing an element, getting the
  19446. length). So we performed overload resolution, with a pass named
  19447. \code{resolve}, to separate the array and tuple operations. In
  19448. particular, we introduced the primitives \code{array\_load},
  19449. \code{array\_store}, and \code{array\_len}.
  19450. For gradual typing, we further overload these operators to work on
  19451. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19452. updated with new cases for the \CANYTY{} type, translating the element
  19453. access and length operations to the primitives \code{any\_load},
  19454. \code{any\_store}, and \code{any\_len}.
  19455. \fi}
  19456. \section{Cast Insertion}
  19457. \label{sec:gradual-insert-casts}
  19458. In our discussion of type checking of \LangGrad{}, we mentioned how
  19459. the runtime aspect of type checking is carried out by the \code{Cast}
  19460. AST node, which is added to the program by a new pass named
  19461. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19462. language. We now discuss the details of this pass.
  19463. The \code{cast\_insert} pass is closely related to the type checker
  19464. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19465. In particular, the type checker allows implicit casts between
  19466. consistent types. The job of the \code{cast\_insert} pass is to make
  19467. those casts explicit. It does so by inserting
  19468. \code{Cast} nodes into the AST.
  19469. %
  19470. For the most part, the implicit casts occur in places where the type
  19471. checker checks two types for consistency. Consider the case for
  19472. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19473. checker requires that the type of the left operand is consistent with
  19474. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19475. \code{Cast} around the left operand, converting from its type to
  19476. \INTTY{}. The story is similar for the right operand. It is not always
  19477. necessary to insert a cast, e.g., if the left operand already has type
  19478. \INTTY{} then there is no need for a \code{Cast}.
  19479. Some of the implicit casts are not as straightforward. One such case
  19480. arises with the
  19481. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19482. see that the type checker requires that the two branches have
  19483. consistent types and that type of the conditional expression is the
  19484. meet of the branches' types. In the target language \LangCast{}, both
  19485. branches will need to have the same type, and that type
  19486. will be the type of the conditional expression. Thus, each branch requires
  19487. a \code{Cast} to convert from its type to the meet of the branches' types.
  19488. The case for the function call exhibits another interesting situation. If
  19489. the function expression is of type \CANYTY{}, then it needs to be cast
  19490. to a function type so that it can be used in a function call in
  19491. \LangCast{}. Which function type should it be cast to? The parameter
  19492. and return types are unknown, so we can simply use \CANYTY{} for all
  19493. of them. Furthermore, in \LangCast{} the argument types will need to
  19494. exactly match the parameter types, so we must cast all the arguments
  19495. to type \CANYTY{} (if they are not already of that type).
  19496. {\if\edition\racketEd
  19497. %
  19498. Likewise, the cases for the tuple operators \code{vector-length},
  19499. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19500. where the tuple expression is of type \CANYTY{}. Instead of
  19501. handling these situations with casts, we recommend translating
  19502. the special-purpose variants of the tuple operators that handle
  19503. tuples of type \CANYTY{}: \code{any-vector-length},
  19504. \code{any-vector-ref}, and \code{any-vector-set!}.
  19505. %
  19506. \fi}
  19507. \section{Lower Casts}
  19508. \label{sec:lower_casts}
  19509. The next step in the journey toward x86 is the \code{lower\_casts}
  19510. pass that translates the casts in \LangCast{} to the lower-level
  19511. \code{Inject} and \code{Project} operators and new operators for
  19512. proxies, extending the \LangLam{} language to \LangProxy{}.
  19513. The \LangProxy{} language can also be described as an extension of
  19514. \LangAny{}, with the addition of proxies. We recommend creating an
  19515. auxiliary function named \code{lower\_cast} that takes an expression
  19516. (in \LangCast{}), a source type, and a target type and translates it
  19517. to an expression in \LangProxy{}.
  19518. The \code{lower\_cast} function can follow a code structure similar to
  19519. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19520. the interpreter for \LangCast{}, because it must handle the same cases
  19521. as \code{apply\_cast} and it needs to mimic the behavior of
  19522. \code{apply\_cast}. The most interesting cases concern
  19523. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19524. {\if\edition\racketEd
  19525. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19526. type to another tuple type is accomplished by creating a proxy that
  19527. intercepts the operations on the underlying tuple. Here we make the
  19528. creation of the proxy explicit with the \code{vector-proxy} AST
  19529. node. It takes three arguments: the first is an expression for the
  19530. tuple, the second is tuple of functions for casting an element that is
  19531. being read from the tuple, and the third is a tuple of functions for
  19532. casting an element that is being written to the array. You can create
  19533. the functions for reading and writing using lambda expressions. Also,
  19534. as we show in the next section, we need to differentiate these tuples
  19535. of functions from the user-created ones, so we recommend using a new
  19536. AST node named \code{raw-vector} instead of \code{vector}.
  19537. %
  19538. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19539. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19540. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19541. \fi}
  19542. {\if\edition\pythonEd\pythonColor
  19543. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19544. type to another array type is accomplished by creating a proxy that
  19545. intercepts the operations on the underlying array. Here we make the
  19546. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19547. takes fives arguments: the first is an expression for the array, the
  19548. second is a function for casting an element that is being read from
  19549. the array, the third is a function for casting an element that is
  19550. being written to the array, the fourth is the type of the underlying
  19551. array, and the fifth is the type of the proxied array. You can create
  19552. the functions for reading and writing using lambda expressions.
  19553. A cast between two tuple types can be handled in a similar manner. We
  19554. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19555. immutable, so there is no need for a function to cast the value during
  19556. a write. Because there is a separate element type for each slot in
  19557. the tuple, we need not just one function for casting during a read,
  19558. but instead a tuple of functions.
  19559. %
  19560. Also, as we show in the next section, we need to differentiate these
  19561. tuples from the user-created ones, so we recommend using a new AST
  19562. node named \code{RawTuple} instead of \code{Tuple} to create the
  19563. tuples of functions.
  19564. %
  19565. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19566. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19567. that involved casting an array of integers to an array of \CANYTY{}.
  19568. \fi}
  19569. \begin{figure}[tbp]
  19570. \begin{tcolorbox}[colback=white]
  19571. {\if\edition\racketEd
  19572. \begin{lstlisting}
  19573. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19574. (begin
  19575. (vector-set! v 0 (f (vector-ref v 0)))
  19576. (vector-set! v 1 (f (vector-ref v 1)))))
  19577. (define (inc [x : Any]) : Any
  19578. (inject (+ (project x Integer) 1) Integer))
  19579. (let ([v (vector 0 41)])
  19580. (begin
  19581. (map_inplace inc (vector-proxy v
  19582. (raw-vector (lambda: ([x9 : Integer]) : Any
  19583. (inject x9 Integer))
  19584. (lambda: ([x9 : Integer]) : Any
  19585. (inject x9 Integer)))
  19586. (raw-vector (lambda: ([x9 : Any]) : Integer
  19587. (project x9 Integer))
  19588. (lambda: ([x9 : Any]) : Integer
  19589. (project x9 Integer)))))
  19590. (vector-ref v 1)))
  19591. \end{lstlisting}
  19592. \fi}
  19593. {\if\edition\pythonEd\pythonColor
  19594. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19595. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19596. i = 0
  19597. while i != array_len(v):
  19598. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19599. i = (i + 1)
  19600. def inc(x : int) -> int:
  19601. return (x + 1)
  19602. def main() -> int:
  19603. v = [0, 41]
  19604. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19605. print(array_load(v, 1))
  19606. return 0
  19607. \end{lstlisting}
  19608. \fi}
  19609. \end{tcolorbox}
  19610. \caption{Output of \code{lower\_casts} on the example shown in
  19611. figure~\ref{fig:map-bang}.}
  19612. \label{fig:map-bang-lower-cast}
  19613. \end{figure}
  19614. A cast from one function type to another function type is accomplished
  19615. by generating a \code{lambda} whose parameter and return types match
  19616. the target function type. The body of the \code{lambda} should cast
  19617. the parameters from the target type to the source type. (Yes,
  19618. backward! Functions are contravariant\index{subject}{contravariant}
  19619. in the parameters.). Afterward, call the underlying function and then
  19620. cast the result from the source return type to the target return type.
  19621. Figure~\ref{fig:map-lower-cast} shows the output of the
  19622. \code{lower\_casts} pass on the \code{map} example give in
  19623. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19624. call to \code{map} is wrapped in a \code{lambda}.
  19625. \begin{figure}[tbp]
  19626. \begin{tcolorbox}[colback=white]
  19627. {\if\edition\racketEd
  19628. \begin{lstlisting}
  19629. (define (map [f : (Integer -> Integer)]
  19630. [v : (Vector Integer Integer)])
  19631. : (Vector Integer Integer)
  19632. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19633. (define (inc [x : Any]) : Any
  19634. (inject (+ (project x Integer) 1) Integer))
  19635. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19636. (project (inc (inject x9 Integer)) Integer))
  19637. (vector 0 41)) 1)
  19638. \end{lstlisting}
  19639. \fi}
  19640. {\if\edition\pythonEd\pythonColor
  19641. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19642. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19643. return (f(v[0]), f(v[1]),)
  19644. def inc(x : any) -> any:
  19645. return inject((project(x, int) + 1), int)
  19646. def main() -> int:
  19647. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19648. print(t[1])
  19649. return 0
  19650. \end{lstlisting}
  19651. \fi}
  19652. \end{tcolorbox}
  19653. \caption{Output of \code{lower\_casts} on the example shown in
  19654. figure~\ref{fig:gradual-map}.}
  19655. \label{fig:map-lower-cast}
  19656. \end{figure}
  19657. \section{Differentiate Proxies}
  19658. \label{sec:differentiate-proxies}
  19659. So far, the responsibility of differentiating tuples and tuple proxies
  19660. has been the job of the interpreter.
  19661. %
  19662. \racket{For example, the interpreter for \LangCast{} implements
  19663. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19664. figure~\ref{fig:guarded-tuple}.}
  19665. %
  19666. In the \code{differentiate\_proxies} pass we shift this responsibility
  19667. to the generated code.
  19668. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19669. we used the type \TUPLETYPENAME{} for both
  19670. real tuples and tuple proxies.
  19671. \python{Similarly, we use the type \code{list} for both arrays and
  19672. array proxies.}
  19673. In \LangPVec{} we return the
  19674. \TUPLETYPENAME{} type to its original
  19675. meaning, as the type of just tuples, and we introduce a new type,
  19676. \PTUPLETYNAME{}, whose values
  19677. can be either real tuples or tuple
  19678. proxies.
  19679. %
  19680. {\if\edition\pythonEd\pythonColor
  19681. Likewise, we return the
  19682. \ARRAYTYPENAME{} type to its original
  19683. meaning, as the type of arrays, and we introduce a new type,
  19684. \PARRAYTYNAME{}, whose values
  19685. can be either arrays or array proxies.
  19686. These new types come with a suite of new primitive operations.
  19687. \fi}
  19688. {\if\edition\racketEd
  19689. A tuple proxy is represented by a tuple containing three things: (1) the
  19690. underlying tuple, (2) a tuple of functions for casting elements that
  19691. are read from the tuple, and (3) a tuple of functions for casting
  19692. values to be written to the tuple. So, we define the following
  19693. abbreviation for the type of a tuple proxy:
  19694. \[
  19695. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19696. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19697. \]
  19698. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19699. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19700. %
  19701. Next we describe each of the new primitive operations.
  19702. \begin{description}
  19703. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19704. (\key{PVector} $T \ldots$)]\ \\
  19705. %
  19706. This operation brands a vector as a value of the \code{PVector} type.
  19707. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19708. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19709. %
  19710. This operation brands a vector proxy as value of the \code{PVector} type.
  19711. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19712. \BOOLTY{}] \ \\
  19713. %
  19714. This returns true if the value is a tuple proxy and false if it is a
  19715. real tuple.
  19716. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19717. (\key{Vector} $T \ldots$)]\ \\
  19718. %
  19719. Assuming that the input is a tuple, this operation returns the
  19720. tuple.
  19721. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19722. $\to$ \BOOLTY{}]\ \\
  19723. %
  19724. Given a tuple proxy, this operation returns the length of the tuple.
  19725. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19726. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19727. %
  19728. Given a tuple proxy, this operation returns the $i$th element of the
  19729. tuple.
  19730. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19731. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19732. Given a tuple proxy, this operation writes a value to the $i$th element
  19733. of the tuple.
  19734. \end{description}
  19735. \fi}
  19736. {\if\edition\pythonEd\pythonColor
  19737. %
  19738. A tuple proxy is represented by a tuple containing 1) the underlying
  19739. tuple and 2) a tuple of functions for casting elements that are read
  19740. from the tuple. The \LangPVec{} language includes the following AST
  19741. classes and primitive functions.
  19742. \begin{description}
  19743. \item[\code{InjectTuple}] \ \\
  19744. %
  19745. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19746. \item[\code{InjectTupleProxy}]\ \\
  19747. %
  19748. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19749. \item[\code{is\_tuple\_proxy}]\ \\
  19750. %
  19751. This primitive returns true if the value is a tuple proxy and false
  19752. if it is a tuple.
  19753. \item[\code{project\_tuple}]\ \\
  19754. %
  19755. Converts a tuple that is branded as \PTUPLETYNAME{}
  19756. back to a tuple.
  19757. \item[\code{proxy\_tuple\_len}]\ \\
  19758. %
  19759. Given a tuple proxy, returns the length of the underlying tuple.
  19760. \item[\code{proxy\_tuple\_load}]\ \\
  19761. %
  19762. Given a tuple proxy, returns the $i$th element of the underlying
  19763. tuple.
  19764. \end{description}
  19765. An array proxy is represented by a tuple containing 1) the underlying
  19766. array, 2) a function for casting elements that are read from the
  19767. array, and 3) a function for casting elements that are written to the
  19768. array. The \LangPVec{} language includes the following AST classes
  19769. and primitive functions.
  19770. \begin{description}
  19771. \item[\code{InjectList}]\ \\
  19772. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19773. \item[\code{InjectListProxy}]\ \\
  19774. %
  19775. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19776. \item[\code{is\_array\_proxy}]\ \\
  19777. %
  19778. Returns true if the value is a array proxy and false if it is an
  19779. array.
  19780. \item[\code{project\_array}]\ \\
  19781. %
  19782. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19783. array.
  19784. \item[\code{proxy\_array\_len}]\ \\
  19785. %
  19786. Given a array proxy, returns the length of the underlying array.
  19787. \item[\code{proxy\_array\_load}]\ \\
  19788. %
  19789. Given a array proxy, returns the $i$th element of the underlying
  19790. array.
  19791. \item[\code{proxy\_array\_store}]\ \\
  19792. %
  19793. Given an array proxy, writes a value to the $i$th element of the
  19794. underlying array.
  19795. \end{description}
  19796. \fi}
  19797. Now we discuss the translation that differentiates tuples and arrays
  19798. from proxies. First, every type annotation in the program is
  19799. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19800. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19801. places. For example, we wrap every tuple creation with an
  19802. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19803. %
  19804. {\if\edition\racketEd
  19805. \begin{minipage}{0.96\textwidth}
  19806. \begin{lstlisting}
  19807. (vector |$e_1 \ldots e_n$|)
  19808. |$\Rightarrow$|
  19809. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19810. \end{lstlisting}
  19811. \end{minipage}
  19812. \fi}
  19813. {\if\edition\pythonEd\pythonColor
  19814. \begin{lstlisting}
  19815. Tuple(|$e_1, \ldots, e_n$|)
  19816. |$\Rightarrow$|
  19817. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19818. \end{lstlisting}
  19819. \fi}
  19820. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19821. AST node that we introduced in the previous
  19822. section does not get injected.
  19823. {\if\edition\racketEd
  19824. \begin{lstlisting}
  19825. (raw-vector |$e_1 \ldots e_n$|)
  19826. |$\Rightarrow$|
  19827. (vector |$e'_1 \ldots e'_n$|)
  19828. \end{lstlisting}
  19829. \fi}
  19830. {\if\edition\pythonEd\pythonColor
  19831. \begin{lstlisting}
  19832. RawTuple(|$e_1, \ldots, e_n$|)
  19833. |$\Rightarrow$|
  19834. Tuple(|$e'_1, \ldots, e'_n$|)
  19835. \end{lstlisting}
  19836. \fi}
  19837. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19838. translates as follows:
  19839. %
  19840. {\if\edition\racketEd
  19841. \begin{lstlisting}
  19842. (vector-proxy |$e_1~e_2~e_3$|)
  19843. |$\Rightarrow$|
  19844. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19845. \end{lstlisting}
  19846. \fi}
  19847. {\if\edition\pythonEd\pythonColor
  19848. \begin{lstlisting}
  19849. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19850. |$\Rightarrow$|
  19851. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19852. \end{lstlisting}
  19853. \fi}
  19854. We translate the element access operations into conditional
  19855. expressions that check whether the value is a proxy and then dispatch
  19856. to either the appropriate proxy tuple operation or the regular tuple
  19857. operation.
  19858. {\if\edition\racketEd
  19859. \begin{lstlisting}
  19860. (vector-ref |$e_1$| |$i$|)
  19861. |$\Rightarrow$|
  19862. (let ([|$v~e_1$|])
  19863. (if (proxy? |$v$|)
  19864. (proxy-vector-ref |$v$| |$i$|)
  19865. (vector-ref (project-vector |$v$|) |$i$|)
  19866. \end{lstlisting}
  19867. \fi}
  19868. %
  19869. Note that in the branch for a tuple, we must apply
  19870. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19871. from the tuple.
  19872. The translation of array operations is similar to the ones for tuples.
  19873. \section{Reveal Casts}
  19874. \label{sec:reveal-casts-gradual}
  19875. {\if\edition\racketEd
  19876. Recall that the \code{reveal\_casts} pass
  19877. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19878. \code{Inject} and \code{Project} into lower-level operations.
  19879. %
  19880. In particular, \code{Project} turns into a conditional expression that
  19881. inspects the tag and retrieves the underlying value. Here we need to
  19882. augment the translation of \code{Project} to handle the situation in which
  19883. the target type is \code{PVector}. Instead of using
  19884. \code{vector-length} we need to use \code{proxy-vector-length}.
  19885. \begin{lstlisting}
  19886. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19887. |$\Rightarrow$|
  19888. (let |$\itm{tmp}$| |$e'$|
  19889. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19890. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19891. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19892. (exit)))
  19893. \end{lstlisting}
  19894. \fi}
  19895. %
  19896. {\if\edition\pythonEd\pythonColor
  19897. Recall that the $\itm{tagof}$ function determines the bits used to
  19898. identify values of different types and it is used in the \code{reveal\_casts}
  19899. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19900. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19901. decimal), just like the tuple and array types.
  19902. \fi}
  19903. %
  19904. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19905. \section{Closure Conversion}
  19906. \label{sec:closure-conversion-gradual}
  19907. The auxiliary function that translates type annotations needs to be
  19908. updated to handle the \PTUPLETYNAME{}
  19909. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19910. %
  19911. Otherwise, the only other changes are adding cases that copy the new
  19912. AST nodes.
  19913. \section{Select Instructions}
  19914. \label{sec:select-instructions-gradual}
  19915. Recall that the \code{select\_instructions} pass is responsible for
  19916. lowering the primitive operations into x86 instructions. So, we need
  19917. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19918. to x86. To do so, the first question we need to answer is how to
  19919. differentiate between tuple and tuples proxies\python{, and likewise for
  19920. arrays and array proxies}. We need just one bit to accomplish this;
  19921. we use the bit in position $63$ of the 64-bit tag at the front of
  19922. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19923. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19924. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19925. it that way.
  19926. {\if\edition\racketEd
  19927. \begin{lstlisting}
  19928. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19929. |$\Rightarrow$|
  19930. movq |$e'_1$|, |$\itm{lhs'}$|
  19931. \end{lstlisting}
  19932. \fi}
  19933. {\if\edition\pythonEd\pythonColor
  19934. \begin{lstlisting}
  19935. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19936. |$\Rightarrow$|
  19937. movq |$e'_1$|, |$\itm{lhs'}$|
  19938. \end{lstlisting}
  19939. \fi}
  19940. \python{The translation for \code{InjectList} is also a move instruction.}
  19941. \noindent On the other hand,
  19942. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19943. $63$ to $1$.
  19944. %
  19945. {\if\edition\racketEd
  19946. \begin{lstlisting}
  19947. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19948. |$\Rightarrow$|
  19949. movq |$e'_1$|, %r11
  19950. movq |$(1 << 63)$|, %rax
  19951. orq 0(%r11), %rax
  19952. movq %rax, 0(%r11)
  19953. movq %r11, |$\itm{lhs'}$|
  19954. \end{lstlisting}
  19955. \fi}
  19956. {\if\edition\pythonEd\pythonColor
  19957. \begin{lstlisting}
  19958. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19959. |$\Rightarrow$|
  19960. movq |$e'_1$|, %r11
  19961. movq |$(1 << 63)$|, %rax
  19962. orq 0(%r11), %rax
  19963. movq %rax, 0(%r11)
  19964. movq %r11, |$\itm{lhs'}$|
  19965. \end{lstlisting}
  19966. \fi}
  19967. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19968. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19969. The \racket{\code{proxy?} operation consumes}%
  19970. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19971. consume}
  19972. the information so carefully stashed away by the injections. It
  19973. isolates bit $63$ to tell whether the value is a proxy.
  19974. %
  19975. {\if\edition\racketEd
  19976. \begin{lstlisting}
  19977. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19978. |$\Rightarrow$|
  19979. movq |$e_1'$|, %r11
  19980. movq 0(%r11), %rax
  19981. sarq $63, %rax
  19982. andq $1, %rax
  19983. movq %rax, |$\itm{lhs'}$|
  19984. \end{lstlisting}
  19985. \fi}%
  19986. %
  19987. {\if\edition\pythonEd\pythonColor
  19988. \begin{lstlisting}
  19989. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19990. |$\Rightarrow$|
  19991. movq |$e_1'$|, %r11
  19992. movq 0(%r11), %rax
  19993. sarq $63, %rax
  19994. andq $1, %rax
  19995. movq %rax, |$\itm{lhs'}$|
  19996. \end{lstlisting}
  19997. \fi}%
  19998. %
  19999. The \racket{\code{project-vector} operation is}
  20000. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20001. straightforward to translate, so we leave that to the reader.
  20002. Regarding the element access operations for tuples\python{ and arrays}, the
  20003. runtime provides procedures that implement them (they are recursive
  20004. functions!), so here we simply need to translate these tuple
  20005. operations into the appropriate function call. For example, here is
  20006. the translation for
  20007. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20008. {\if\edition\racketEd
  20009. \begin{minipage}{0.96\textwidth}
  20010. \begin{lstlisting}
  20011. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20012. |$\Rightarrow$|
  20013. movq |$e_1'$|, %rdi
  20014. movq |$e_2'$|, %rsi
  20015. callq proxy_vector_ref
  20016. movq %rax, |$\itm{lhs'}$|
  20017. \end{lstlisting}
  20018. \end{minipage}
  20019. \fi}
  20020. {\if\edition\pythonEd\pythonColor
  20021. \begin{lstlisting}
  20022. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20023. |$\Rightarrow$|
  20024. movq |$e_1'$|, %rdi
  20025. movq |$e_2'$|, %rsi
  20026. callq proxy_vector_ref
  20027. movq %rax, |$\itm{lhs'}$|
  20028. \end{lstlisting}
  20029. \fi}
  20030. {\if\edition\pythonEd\pythonColor
  20031. % TODO: revisit the names vecof for python -Jeremy
  20032. We translate
  20033. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20034. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20035. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20036. \fi}
  20037. We have another batch of operations to deal with: those for the
  20038. \CANYTY{} type. Recall that we generate an
  20039. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20040. there is a element access on something of type \CANYTY{}, and
  20041. similarly for
  20042. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20043. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20044. section~\ref{sec:select-Lany} we selected instructions for these
  20045. operations on the basis of the idea that the underlying value was a tuple or
  20046. array. But in the current setting, the underlying value is of type
  20047. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20048. functions to deal with this:
  20049. \code{proxy\_vector\_ref},
  20050. \code{proxy\_vector\_set}, and
  20051. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  20052. to determine whether the value is a proxy, and then
  20053. dispatches to the the appropriate code.
  20054. %
  20055. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20056. can be translated as follows.
  20057. We begin by projecting the underlying value out of the tagged value and
  20058. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20059. {\if\edition\racketEd
  20060. \begin{lstlisting}
  20061. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20062. |$\Rightarrow$|
  20063. movq |$\neg 111$|, %rdi
  20064. andq |$e_1'$|, %rdi
  20065. movq |$e_2'$|, %rsi
  20066. callq proxy_vector_ref
  20067. movq %rax, |$\itm{lhs'}$|
  20068. \end{lstlisting}
  20069. \fi}
  20070. {\if\edition\pythonEd\pythonColor
  20071. \begin{lstlisting}
  20072. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20073. |$\Rightarrow$|
  20074. movq |$\neg 111$|, %rdi
  20075. andq |$e_1'$|, %rdi
  20076. movq |$e_2'$|, %rsi
  20077. callq proxy_vector_ref
  20078. movq %rax, |$\itm{lhs'}$|
  20079. \end{lstlisting}
  20080. \fi}
  20081. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20082. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20083. are translated in a similar way. Alternatively, you could generate
  20084. instructions to open-code
  20085. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20086. and \code{proxy\_vector\_length} functions.
  20087. \begin{exercise}\normalfont\normalsize
  20088. Implement a compiler for the gradually typed \LangGrad{} language by
  20089. extending and adapting your compiler for \LangLam{}. Create ten new
  20090. partially typed test programs. In addition to testing with these
  20091. new programs, test your compiler on all the tests for \LangLam{}
  20092. and for \LangDyn{}.
  20093. %
  20094. \racket{Sometimes you may get a type checking error on the
  20095. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20096. the \CANYTY{} type around each subexpression that has caused a type
  20097. error. Although \LangDyn{} does not have explicit casts, you can
  20098. induce one by wrapping the subexpression \code{e} with a call to
  20099. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20100. %
  20101. \python{Sometimes you may get a type checking error on the
  20102. \LangDyn{} programs but you can adapt them by inserting a
  20103. temporary variable of type \CANYTY{} that is initialized with the
  20104. troublesome expression.}
  20105. \end{exercise}
  20106. \begin{figure}[p]
  20107. \begin{tcolorbox}[colback=white]
  20108. {\if\edition\racketEd
  20109. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20110. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20111. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20112. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20113. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20114. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20115. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20116. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20117. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20118. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20119. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20120. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20121. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20122. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20123. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20124. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20125. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20126. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20127. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20128. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20129. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20130. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20131. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20132. \path[->,bend left=15] (Lgradual) edge [above] node
  20133. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20134. \path[->,bend left=15] (Lgradual2) edge [above] node
  20135. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20136. \path[->,bend left=15] (Lgradual3) edge [above] node
  20137. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20138. \path[->,bend left=15] (Lgradual4) edge [left] node
  20139. {\ttfamily\footnotesize shrink} (Lgradualr);
  20140. \path[->,bend left=15] (Lgradualr) edge [above] node
  20141. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20142. \path[->,bend right=15] (Lgradualp) edge [above] node
  20143. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20144. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20145. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20146. \path[->,bend right=15] (Llambdapp) edge [above] node
  20147. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20148. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20149. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20150. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20151. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20152. \path[->,bend left=15] (F1-2) edge [above] node
  20153. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20154. \path[->,bend left=15] (F1-3) edge [left] node
  20155. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20156. \path[->,bend left=15] (F1-4) edge [below] node
  20157. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20158. \path[->,bend right=15] (F1-5) edge [above] node
  20159. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20160. \path[->,bend right=15] (F1-6) edge [above] node
  20161. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20162. \path[->,bend right=15] (C3-2) edge [right] node
  20163. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20164. \path[->,bend right=15] (x86-2) edge [right] node
  20165. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20166. \path[->,bend right=15] (x86-2-1) edge [below] node
  20167. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20168. \path[->,bend right=15] (x86-2-2) edge [right] node
  20169. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20170. \path[->,bend left=15] (x86-3) edge [above] node
  20171. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20172. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20173. \end{tikzpicture}
  20174. \fi}
  20175. {\if\edition\pythonEd\pythonColor
  20176. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20177. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20178. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20179. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20180. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20181. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20182. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20183. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20184. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20185. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20186. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20187. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20188. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20189. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20190. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20191. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20192. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20193. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20194. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20195. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20196. \path[->,bend left=15] (Lgradual) edge [above] node
  20197. {\ttfamily\footnotesize shrink} (Lgradual2);
  20198. \path[->,bend left=15] (Lgradual2) edge [above] node
  20199. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20200. \path[->,bend left=15] (Lgradual3) edge [above] node
  20201. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20202. \path[->,bend left=15] (Lgradual4) edge [left] node
  20203. {\ttfamily\footnotesize resolve} (Lgradualr);
  20204. \path[->,bend left=15] (Lgradualr) edge [below] node
  20205. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20206. \path[->,bend right=15] (Lgradualp) edge [above] node
  20207. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20208. \path[->,bend right=15] (Llambdapp) edge [above] node
  20209. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20210. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20211. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20212. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20213. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20214. \path[->,bend left=15] (F1-1) edge [above] node
  20215. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20216. \path[->,bend left=15] (F1-2) edge [above] node
  20217. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20218. \path[->,bend left=15] (F1-3) edge [right] node
  20219. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20220. \path[->,bend right=15] (F1-5) edge [above] node
  20221. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20222. \path[->,bend right=15] (F1-6) edge [above] node
  20223. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20224. \path[->,bend right=15] (C3-2) edge [right] node
  20225. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20226. \path[->,bend right=15] (x86-2) edge [below] node
  20227. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20228. \path[->,bend right=15] (x86-3) edge [below] node
  20229. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20230. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20231. \end{tikzpicture}
  20232. \fi}
  20233. \end{tcolorbox}
  20234. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20235. \label{fig:Lgradual-passes}
  20236. \end{figure}
  20237. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20238. needed for the compilation of \LangGrad{}.
  20239. \section{Further Reading}
  20240. This chapter just scratches the surface of gradual typing. The basic
  20241. approach described here is missing two key ingredients that one would
  20242. want in a implementation of gradual typing: blame
  20243. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20244. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20245. problem addressed by blame tracking is that when a cast on a
  20246. higher-order value fails, it often does so at a point in the program
  20247. that is far removed from the original cast. Blame tracking is a
  20248. technique for propagating extra information through casts and proxies
  20249. so that when a cast fails, the error message can point back to the
  20250. original location of the cast in the source program.
  20251. The problem addressed by space-efficient casts also relates to
  20252. higher-order casts. It turns out that in partially typed programs, a
  20253. function or tuple can flow through a great many casts at runtime. With
  20254. the approach described in this chapter, each cast adds another
  20255. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20256. considerable space, but it also makes the function calls and tuple
  20257. operations slow. For example, a partially typed version of quicksort
  20258. could, in the worst case, build a chain of proxies of length $O(n)$
  20259. around the tuple, changing the overall time complexity of the
  20260. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20261. solution to this problem by representing casts using the coercion
  20262. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20263. long chains of proxies by compressing them into a concise normal
  20264. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20265. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20266. the Grift compiler:
  20267. \begin{center}
  20268. \url{https://github.com/Gradual-Typing/Grift}
  20269. \end{center}
  20270. There are also interesting interactions between gradual typing and
  20271. other language features, such as generics, information-flow types, and
  20272. type inference, to name a few. We recommend to the reader the
  20273. online gradual typing bibliography for more material:
  20274. \begin{center}
  20275. \url{http://samth.github.io/gradual-typing-bib/}
  20276. \end{center}
  20277. % TODO: challenge problem:
  20278. % type analysis and type specialization?
  20279. % coercions?
  20280. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20281. \chapter{Generics}
  20282. \label{ch:Lpoly}
  20283. \index{subject}{parametric polymorphism}
  20284. \index{subject}{generics}
  20285. \setcounter{footnote}{0}
  20286. This chapter studies the compilation of
  20287. generics\index{subject}{generics} (aka parametric
  20288. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20289. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20290. enable programmers to make code more reusable by parameterizing
  20291. functions and data structures with respect to the types on which they
  20292. operate. For example, figure~\ref{fig:map-poly} revisits the
  20293. \code{map} example and this time gives it a more fitting type. This
  20294. \code{map} function is parameterized with respect to the element type
  20295. of the tuple. The type of \code{map} is the following generic type
  20296. specified by the \code{All} type with parameter \code{T}:
  20297. {\if\edition\racketEd
  20298. \begin{lstlisting}
  20299. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20300. \end{lstlisting}
  20301. \fi}
  20302. {\if\edition\pythonEd\pythonColor
  20303. \begin{lstlisting}
  20304. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20305. \end{lstlisting}
  20306. \fi}
  20307. %
  20308. The idea is that \code{map} can be used at \emph{all} choices of a
  20309. type for parameter \code{T}. In the example shown in
  20310. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20311. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20312. \code{T}, but we could have just as well applied \code{map} to a tuple
  20313. of Booleans.
  20314. %
  20315. A \emph{monomorphic} function is simply one that is not generic.
  20316. %
  20317. We use the term \emph{instantiation} for the process (within the
  20318. language implementation) of turning a generic function into a
  20319. monomorphic one, where the type parameters have been replaced by
  20320. types.
  20321. {\if\edition\pythonEd\pythonColor
  20322. %
  20323. In Python, when writing a generic function such as \code{map}, one
  20324. does not explicitly write down its generic type (using \code{All}).
  20325. Instead, the fact that it is generic is implied by the use of type
  20326. variables (such as \code{T}) in the type annotations of its
  20327. parameters.
  20328. %
  20329. \fi}
  20330. \begin{figure}[tbp]
  20331. % poly_test_2.rkt
  20332. \begin{tcolorbox}[colback=white]
  20333. {\if\edition\racketEd
  20334. \begin{lstlisting}
  20335. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20336. (define (map f v)
  20337. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20338. (define (inc [x : Integer]) : Integer (+ x 1))
  20339. (vector-ref (map inc (vector 0 41)) 1)
  20340. \end{lstlisting}
  20341. \fi}
  20342. {\if\edition\pythonEd\pythonColor
  20343. \begin{lstlisting}
  20344. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20345. return (f(tup[0]), f(tup[1]))
  20346. def add1(x : int) -> int:
  20347. return x + 1
  20348. t = map(add1, (0, 41))
  20349. print(t[1])
  20350. \end{lstlisting}
  20351. \fi}
  20352. \end{tcolorbox}
  20353. \caption{A generic version of the \code{map} function.}
  20354. \label{fig:map-poly}
  20355. \end{figure}
  20356. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20357. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20358. shows the definition of the abstract syntax.
  20359. %
  20360. {\if\edition\racketEd
  20361. We add a second form for function definitions in which a type
  20362. declaration comes before the \code{define}. In the abstract syntax,
  20363. the return type in the \code{Def} is \CANYTY{}, but that should be
  20364. ignored in favor of the return type in the type declaration. (The
  20365. \CANYTY{} comes from using the same parser as discussed in
  20366. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20367. enables the use of an \code{All} type for a function, thereby making
  20368. it generic.
  20369. \fi}
  20370. %
  20371. The grammar for types is extended to include the type of a generic
  20372. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20373. abstract syntax)}.
  20374. \newcommand{\LpolyGrammarRacket}{
  20375. \begin{array}{lcl}
  20376. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20377. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20378. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20379. \end{array}
  20380. }
  20381. \newcommand{\LpolyASTRacket}{
  20382. \begin{array}{lcl}
  20383. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20384. \Def &::=& \DECL{\Var}{\Type} \\
  20385. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20386. \end{array}
  20387. }
  20388. \newcommand{\LpolyGrammarPython}{
  20389. \begin{array}{lcl}
  20390. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20391. \end{array}
  20392. }
  20393. \newcommand{\LpolyASTPython}{
  20394. \begin{array}{lcl}
  20395. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20396. \MID \key{GenericVar}\LP\Var\RP
  20397. \end{array}
  20398. }
  20399. \begin{figure}[tp]
  20400. \centering
  20401. \begin{tcolorbox}[colback=white]
  20402. \footnotesize
  20403. {\if\edition\racketEd
  20404. \[
  20405. \begin{array}{l}
  20406. \gray{\LintGrammarRacket{}} \\ \hline
  20407. \gray{\LvarGrammarRacket{}} \\ \hline
  20408. \gray{\LifGrammarRacket{}} \\ \hline
  20409. \gray{\LwhileGrammarRacket} \\ \hline
  20410. \gray{\LtupGrammarRacket} \\ \hline
  20411. \gray{\LfunGrammarRacket} \\ \hline
  20412. \gray{\LlambdaGrammarRacket} \\ \hline
  20413. \LpolyGrammarRacket \\
  20414. \begin{array}{lcl}
  20415. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20416. \end{array}
  20417. \end{array}
  20418. \]
  20419. \fi}
  20420. {\if\edition\pythonEd\pythonColor
  20421. \[
  20422. \begin{array}{l}
  20423. \gray{\LintGrammarPython{}} \\ \hline
  20424. \gray{\LvarGrammarPython{}} \\ \hline
  20425. \gray{\LifGrammarPython{}} \\ \hline
  20426. \gray{\LwhileGrammarPython} \\ \hline
  20427. \gray{\LtupGrammarPython} \\ \hline
  20428. \gray{\LfunGrammarPython} \\ \hline
  20429. \gray{\LlambdaGrammarPython} \\\hline
  20430. \LpolyGrammarPython \\
  20431. \begin{array}{lcl}
  20432. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20433. \end{array}
  20434. \end{array}
  20435. \]
  20436. \fi}
  20437. \end{tcolorbox}
  20438. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20439. (figure~\ref{fig:Llam-concrete-syntax}).}
  20440. \label{fig:Lpoly-concrete-syntax}
  20441. \end{figure}
  20442. \begin{figure}[tp]
  20443. \centering
  20444. \begin{tcolorbox}[colback=white]
  20445. \footnotesize
  20446. {\if\edition\racketEd
  20447. \[
  20448. \begin{array}{l}
  20449. \gray{\LintOpAST} \\ \hline
  20450. \gray{\LvarASTRacket{}} \\ \hline
  20451. \gray{\LifASTRacket{}} \\ \hline
  20452. \gray{\LwhileASTRacket{}} \\ \hline
  20453. \gray{\LtupASTRacket{}} \\ \hline
  20454. \gray{\LfunASTRacket} \\ \hline
  20455. \gray{\LlambdaASTRacket} \\ \hline
  20456. \LpolyASTRacket \\
  20457. \begin{array}{lcl}
  20458. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20459. \end{array}
  20460. \end{array}
  20461. \]
  20462. \fi}
  20463. {\if\edition\pythonEd\pythonColor
  20464. \[
  20465. \begin{array}{l}
  20466. \gray{\LintASTPython} \\ \hline
  20467. \gray{\LvarASTPython{}} \\ \hline
  20468. \gray{\LifASTPython{}} \\ \hline
  20469. \gray{\LwhileASTPython{}} \\ \hline
  20470. \gray{\LtupASTPython{}} \\ \hline
  20471. \gray{\LfunASTPython} \\ \hline
  20472. \gray{\LlambdaASTPython} \\ \hline
  20473. \LpolyASTPython \\
  20474. \begin{array}{lcl}
  20475. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20476. \end{array}
  20477. \end{array}
  20478. \]
  20479. \fi}
  20480. \end{tcolorbox}
  20481. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20482. (figure~\ref{fig:Llam-syntax}).}
  20483. \label{fig:Lpoly-syntax}
  20484. \end{figure}
  20485. By including the \code{All} type in the $\Type$ nonterminal of the
  20486. grammar we choose to make generics first class, which has interesting
  20487. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20488. not include syntax for the \code{All} type. It is inferred for functions whose
  20489. type annotations contain type variables.} Many languages with generics, such as
  20490. C++~\citep{stroustrup88:_param_types} and Standard
  20491. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20492. may be helpful to see an example of first-class generics in action. In
  20493. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20494. whose parameter is a generic function. Indeed, because the grammar for
  20495. $\Type$ includes the \code{All} type, a generic function may also be
  20496. returned from a function or stored inside a tuple. The body of
  20497. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20498. and also to an integer, which would not be possible if \code{f} were
  20499. not generic.
  20500. \begin{figure}[tbp]
  20501. \begin{tcolorbox}[colback=white]
  20502. {\if\edition\racketEd
  20503. \begin{lstlisting}
  20504. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20505. (define (apply_twice f)
  20506. (if (f #t) (f 42) (f 777)))
  20507. (: id (All (T) (T -> T)))
  20508. (define (id x) x)
  20509. (apply_twice id)
  20510. \end{lstlisting}
  20511. \fi}
  20512. {\if\edition\pythonEd\pythonColor
  20513. \begin{lstlisting}
  20514. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20515. if f(True):
  20516. return f(42)
  20517. else:
  20518. return f(777)
  20519. def id(x: T) -> T:
  20520. return x
  20521. print(apply_twice(id))
  20522. \end{lstlisting}
  20523. \fi}
  20524. \end{tcolorbox}
  20525. \caption{An example illustrating first-class generics.}
  20526. \label{fig:apply-twice}
  20527. \end{figure}
  20528. The type checker for \LangPoly{} shown in
  20529. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20530. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20531. {\if\edition\pythonEd\pythonColor
  20532. %
  20533. Regarding function definitions, if the type annotations on its
  20534. parameters contain generic variables, then the function is generic and
  20535. therefore its type is an \code{All} type wrapped around a function
  20536. type. Otherwise the function is monomorphic and its type is simply
  20537. a function type.
  20538. %
  20539. \fi}
  20540. The type checking of a function application is extended to handle the
  20541. case in which the operator expression is a generic function. In that case
  20542. the type arguments are deduced by matching the type of the parameters
  20543. with the types of the arguments.
  20544. %
  20545. The \code{match\_types} auxiliary function
  20546. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20547. recursively descending through a parameter type \code{param\_ty} and
  20548. the corresponding argument type \code{arg\_ty}, making sure that they
  20549. are equal except when there is a type parameter in the parameter
  20550. type. Upon encountering a type parameter for the first time, the
  20551. algorithm deduces an association of the type parameter to the
  20552. corresponding part of the argument type. If it is not the first time
  20553. that the type parameter has been encountered, the algorithm looks up
  20554. its deduced type and makes sure that it is equal to the corresponding
  20555. part of the argument type. The return type of the application is the
  20556. return type of the generic function with the type parameters
  20557. replaced by the deduced type arguments, using the
  20558. \code{substitute\_type} auxiliary function, which is also listed in
  20559. figure~\ref{fig:type-check-Lpoly-aux}.
  20560. The type checker extends type equality to handle the \code{All} type.
  20561. This is not quite as simple as for other types, such as function and
  20562. tuple types, because two \code{All} types can be syntactically
  20563. different even though they are equivalent. For example,
  20564. %
  20565. \racket{\code{(All (T) (T -> T))}}
  20566. \python{\code{All[[T], Callable[[T], T]]}}
  20567. is equivalent to
  20568. \racket{\code{(All (U) (U -> U))}}
  20569. \python{\code{All[[U], Callable[[U], U]]}}.
  20570. %
  20571. Two generic types should be considered equal if they differ only in
  20572. the choice of the names of the type parameters. The definition of type
  20573. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20574. parameters in one type to match the type parameters of the other type.
  20575. {\if\edition\racketEd
  20576. %
  20577. The type checker also ensures that only defined type variables appear
  20578. in type annotations. The \code{check\_well\_formed} function for which
  20579. the definition is shown in figure~\ref{fig:well-formed-types}
  20580. recursively inspects a type, making sure that each type variable has
  20581. been defined.
  20582. %
  20583. \fi}
  20584. \begin{figure}[tbp]
  20585. \begin{tcolorbox}[colback=white]
  20586. {\if\edition\racketEd
  20587. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20588. (define type-check-poly-class
  20589. (class type-check-Llambda-class
  20590. (super-new)
  20591. (inherit check-type-equal?)
  20592. (define/override (type-check-apply env e1 es)
  20593. (define-values (e^ ty) ((type-check-exp env) e1))
  20594. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20595. ((type-check-exp env) e)))
  20596. (match ty
  20597. [`(,ty^* ... -> ,rt)
  20598. (for ([arg-ty ty*] [param-ty ty^*])
  20599. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20600. (values e^ es^ rt)]
  20601. [`(All ,xs (,tys ... -> ,rt))
  20602. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20603. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20604. (match_types env^^ param-ty arg-ty)))
  20605. (define targs
  20606. (for/list ([x xs])
  20607. (match (dict-ref env^^ x (lambda () #f))
  20608. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20609. x (Apply e1 es))]
  20610. [ty ty])))
  20611. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20612. [else (error 'type-check "expected a function, not ~a" ty)]))
  20613. (define/override ((type-check-exp env) e)
  20614. (match e
  20615. [(Lambda `([,xs : ,Ts] ...) rT body)
  20616. (for ([T Ts]) ((check_well_formed env) T))
  20617. ((check_well_formed env) rT)
  20618. ((super type-check-exp env) e)]
  20619. [(HasType e1 ty)
  20620. ((check_well_formed env) ty)
  20621. ((super type-check-exp env) e)]
  20622. [else ((super type-check-exp env) e)]))
  20623. (define/override ((type-check-def env) d)
  20624. (verbose 'type-check "poly/def" d)
  20625. (match d
  20626. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20627. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20628. (for ([p ps]) ((check_well_formed ts-env) p))
  20629. ((check_well_formed ts-env) rt)
  20630. (define new-env (append ts-env (map cons xs ps) env))
  20631. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20632. (check-type-equal? ty^ rt body)
  20633. (Generic ts (Def f p:t* rt info body^))]
  20634. [else ((super type-check-def env) d)]))
  20635. (define/override (type-check-program p)
  20636. (match p
  20637. [(Program info body)
  20638. (type-check-program (ProgramDefsExp info '() body))]
  20639. [(ProgramDefsExp info ds body)
  20640. (define ds^ (combine-decls-defs ds))
  20641. (define new-env (for/list ([d ds^])
  20642. (cons (def-name d) (fun-def-type d))))
  20643. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20644. (define-values (body^ ty) ((type-check-exp new-env) body))
  20645. (check-type-equal? ty 'Integer body)
  20646. (ProgramDefsExp info ds^^ body^)]))
  20647. ))
  20648. \end{lstlisting}
  20649. \fi}
  20650. {\if\edition\pythonEd\pythonColor
  20651. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20652. def type_check_exp(self, e, env):
  20653. match e:
  20654. case Call(Name(f), args) if f in builtin_functions:
  20655. return super().type_check_exp(e, env)
  20656. case Call(func, args):
  20657. func_t = self.type_check_exp(func, env)
  20658. func.has_type = func_t
  20659. match func_t:
  20660. case AllType(ps, FunctionType(p_tys, rt)):
  20661. for arg in args:
  20662. arg.has_type = self.type_check_exp(arg, env)
  20663. arg_tys = [arg.has_type for arg in args]
  20664. deduced = {}
  20665. for (p, a) in zip(p_tys, arg_tys):
  20666. self.match_types(p, a, deduced, e)
  20667. return self.substitute_type(rt, deduced)
  20668. case _:
  20669. return super().type_check_exp(e, env)
  20670. case _:
  20671. return super().type_check_exp(e, env)
  20672. def type_check(self, p):
  20673. match p:
  20674. case Module(body):
  20675. env = {}
  20676. for s in body:
  20677. match s:
  20678. case FunctionDef(name, params, bod, dl, returns, comment):
  20679. params_t = [t for (x,t) in params]
  20680. ty_params = set()
  20681. for t in params_t:
  20682. ty_params |$\mid$|= self.generic_variables(t)
  20683. ty = FunctionType(params_t, returns)
  20684. if len(ty_params) > 0:
  20685. ty = AllType(list(ty_params), ty)
  20686. env[name] = ty
  20687. self.check_stmts(body, IntType(), env)
  20688. case _:
  20689. raise Exception('type_check: unexpected ' + repr(p))
  20690. \end{lstlisting}
  20691. \fi}
  20692. \end{tcolorbox}
  20693. \caption{Type checker for the \LangPoly{} language.}
  20694. \label{fig:type-check-Lpoly}
  20695. \end{figure}
  20696. \begin{figure}[tbp]
  20697. \begin{tcolorbox}[colback=white]
  20698. {\if\edition\racketEd
  20699. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20700. (define/override (type-equal? t1 t2)
  20701. (match* (t1 t2)
  20702. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20703. (define env (map cons xs ys))
  20704. (type-equal? (substitute_type env T1) T2)]
  20705. [(other wise)
  20706. (super type-equal? t1 t2)]))
  20707. (define/public (match_types env pt at)
  20708. (match* (pt at)
  20709. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20710. [('Void 'Void) env] [('Any 'Any) env]
  20711. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20712. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20713. (match_types env^ pt1 at1))]
  20714. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20715. (define env^ (match_types env prt art))
  20716. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20717. (match_types env^^ pt1 at1))]
  20718. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20719. (define env^ (append (map cons pxs axs) env))
  20720. (match_types env^ pt1 at1)]
  20721. [((? symbol? x) at)
  20722. (match (dict-ref env x (lambda () #f))
  20723. [#f (error 'type-check "undefined type variable ~a" x)]
  20724. ['Type (cons (cons x at) env)]
  20725. [t^ (check-type-equal? at t^ 'matching) env])]
  20726. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20727. (define/public (substitute_type env pt)
  20728. (match pt
  20729. ['Integer 'Integer] ['Boolean 'Boolean]
  20730. ['Void 'Void] ['Any 'Any]
  20731. [`(Vector ,ts ...)
  20732. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20733. [`(,ts ... -> ,rt)
  20734. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20735. [`(All ,xs ,t)
  20736. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20737. [(? symbol? x) (dict-ref env x)]
  20738. [else (error 'type-check "expected a type not ~a" pt)]))
  20739. (define/public (combine-decls-defs ds)
  20740. (match ds
  20741. ['() '()]
  20742. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20743. (unless (equal? name f)
  20744. (error 'type-check "name mismatch, ~a != ~a" name f))
  20745. (match type
  20746. [`(All ,xs (,ps ... -> ,rt))
  20747. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20748. (cons (Generic xs (Def name params^ rt info body))
  20749. (combine-decls-defs ds^))]
  20750. [`(,ps ... -> ,rt)
  20751. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20752. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20753. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20754. [`(,(Def f params rt info body) . ,ds^)
  20755. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20756. \end{lstlisting}
  20757. \fi}
  20758. {\if\edition\pythonEd\pythonColor
  20759. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20760. def match_types(self, param_ty, arg_ty, deduced, e):
  20761. match (param_ty, arg_ty):
  20762. case (GenericVar(id), _):
  20763. if id in deduced:
  20764. self.check_type_equal(arg_ty, deduced[id], e)
  20765. else:
  20766. deduced[id] = arg_ty
  20767. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20768. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20769. new_arg_ty = self.substitute_type(arg_ty, rename)
  20770. self.match_types(ty, new_arg_ty, deduced, e)
  20771. case (TupleType(ps), TupleType(ts)):
  20772. for (p, a) in zip(ps, ts):
  20773. self.match_types(p, a, deduced, e)
  20774. case (ListType(p), ListType(a)):
  20775. self.match_types(p, a, deduced, e)
  20776. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20777. for (pp, ap) in zip(pps, aps):
  20778. self.match_types(pp, ap, deduced, e)
  20779. self.match_types(prt, art, deduced, e)
  20780. case (IntType(), IntType()):
  20781. pass
  20782. case (BoolType(), BoolType()):
  20783. pass
  20784. case _:
  20785. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20786. def substitute_type(self, ty, var_map):
  20787. match ty:
  20788. case GenericVar(id):
  20789. return var_map[id]
  20790. case AllType(ps, ty):
  20791. new_map = copy.deepcopy(var_map)
  20792. for p in ps:
  20793. new_map[p] = GenericVar(p)
  20794. return AllType(ps, self.substitute_type(ty, new_map))
  20795. case TupleType(ts):
  20796. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20797. case ListType(ty):
  20798. return ListType(self.substitute_type(ty, var_map))
  20799. case FunctionType(pts, rt):
  20800. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20801. self.substitute_type(rt, var_map))
  20802. case IntType():
  20803. return IntType()
  20804. case BoolType():
  20805. return BoolType()
  20806. case _:
  20807. raise Exception('substitute_type: unexpected ' + repr(ty))
  20808. def check_type_equal(self, t1, t2, e):
  20809. match (t1, t2):
  20810. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20811. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20812. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20813. case (_, _):
  20814. return super().check_type_equal(t1, t2, e)
  20815. \end{lstlisting}
  20816. \fi}
  20817. \end{tcolorbox}
  20818. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20819. \label{fig:type-check-Lpoly-aux}
  20820. \end{figure}
  20821. {\if\edition\racketEd
  20822. \begin{figure}[tbp]
  20823. \begin{tcolorbox}[colback=white]
  20824. \begin{lstlisting}
  20825. (define/public ((check_well_formed env) ty)
  20826. (match ty
  20827. ['Integer (void)]
  20828. ['Boolean (void)]
  20829. ['Void (void)]
  20830. [(? symbol? a)
  20831. (match (dict-ref env a (lambda () #f))
  20832. ['Type (void)]
  20833. [else (error 'type-check "undefined type variable ~a" a)])]
  20834. [`(Vector ,ts ...)
  20835. (for ([t ts]) ((check_well_formed env) t))]
  20836. [`(,ts ... -> ,t)
  20837. (for ([t ts]) ((check_well_formed env) t))
  20838. ((check_well_formed env) t)]
  20839. [`(All ,xs ,t)
  20840. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20841. ((check_well_formed env^) t)]
  20842. [else (error 'type-check "unrecognized type ~a" ty)]))
  20843. \end{lstlisting}
  20844. \end{tcolorbox}
  20845. \caption{Well-formed types.}
  20846. \label{fig:well-formed-types}
  20847. \end{figure}
  20848. \fi}
  20849. % TODO: interpreter for R'_10
  20850. \clearpage
  20851. \section{Compiling Generics}
  20852. \label{sec:compiling-poly}
  20853. Broadly speaking, there are four approaches to compiling generics, as
  20854. follows:
  20855. \begin{description}
  20856. \item[Monomorphization] generates a different version of a generic
  20857. function for each set of type arguments with which it is used,
  20858. producing type-specialized code. This approach results in the most
  20859. efficient code but requires whole-program compilation (no separate
  20860. compilation) and may increase code size. Unfortunately,
  20861. monomorphization is incompatible with first-class generics, because
  20862. it is not always possible to determine which generic functions are
  20863. used with which type arguments during compilation. (It can be done
  20864. at runtime, with just-in-time compilation.) Monomorphization is
  20865. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20866. generic functions in NESL~\citep{Blelloch:1993aa} and
  20867. ML~\citep{Weeks:2006aa}.
  20868. \item[Uniform representation] generates one version of each generic
  20869. function and requires all values to have a common \emph{boxed} format,
  20870. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20871. generic and monomorphic code is compiled similarly to code in a
  20872. dynamically typed language (like \LangDyn{}), in which primitive
  20873. operators require their arguments to be projected from \CANYTY{} and
  20874. their results to be injected into \CANYTY{}. (In object-oriented
  20875. languages, the projection is accomplished via virtual method
  20876. dispatch.) The uniform representation approach is compatible with
  20877. separate compilation and with first-class generics. However, it
  20878. produces the least efficient code because it introduces overhead in
  20879. the entire program. This approach is used in
  20880. Java~\citep{Bracha:1998fk},
  20881. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20882. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20883. \item[Mixed representation] generates one version of each generic
  20884. function, using a boxed representation for type variables. However,
  20885. monomorphic code is compiled as usual (as in \LangLam{}), and
  20886. conversions are performed at the boundaries between monomorphic code
  20887. and polymorphic code (e.g., when a generic function is instantiated
  20888. and called). This approach is compatible with separate compilation
  20889. and first-class generics and maintains efficiency in monomorphic
  20890. code. The trade-off is increased overhead at the boundary between
  20891. monomorphic and generic code. This approach is used in
  20892. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20893. Java 5 with the addition of autoboxing.
  20894. \item[Type passing] uses the unboxed representation in both
  20895. monomorphic and generic code. Each generic function is compiled to a
  20896. single function with extra parameters that describe the type
  20897. arguments. The type information is used by the generated code to
  20898. determine how to access the unboxed values at runtime. This approach is
  20899. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20900. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20901. compilation and first-class generics and maintains the
  20902. efficiency for monomorphic code. There is runtime overhead in
  20903. polymorphic code from dispatching on type information.
  20904. \end{description}
  20905. In this chapter we use the mixed representation approach, partly
  20906. because of its favorable attributes and partly because it is
  20907. straightforward to implement using the tools that we have already
  20908. built to support gradual typing. The work of compiling generic
  20909. functions is performed in two passes, \code{resolve} and
  20910. \code{erase\_types}, that we discuss next. The output of
  20911. \code{erase\_types} is \LangCast{}
  20912. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20913. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20914. \section{Resolve Instantiation}
  20915. \label{sec:generic-resolve}
  20916. Recall that the type checker for \LangPoly{} deduces the type
  20917. arguments at call sites to a generic function. The purpose of the
  20918. \code{resolve} pass is to turn this implicit instantiation into an
  20919. explicit one, by adding \code{inst} nodes to the syntax of the
  20920. intermediate language. An \code{inst} node records the mapping of
  20921. type parameters to type arguments. The semantics of the \code{inst}
  20922. node is to instantiate the result of its first argument, a generic
  20923. function, to produce a monomorphic function. However, because the
  20924. interpreter never analyzes type annotations, instantiation can be a
  20925. no-op and simply return the generic function.
  20926. %
  20927. The output language of the \code{resolve} pass is \LangInst{},
  20928. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20929. {\if\edition\racketEd
  20930. The \code{resolve} pass combines the type declaration and polymorphic
  20931. function into a single definition, using the \code{Poly} form, to make
  20932. polymorphic functions more convenient to process in the next pass of the
  20933. compiler.
  20934. \fi}
  20935. \newcommand{\LinstASTRacket}{
  20936. \begin{array}{lcl}
  20937. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20938. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20939. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20940. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20941. \end{array}
  20942. }
  20943. \newcommand{\LinstASTPython}{
  20944. \begin{array}{lcl}
  20945. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20946. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20947. \end{array}
  20948. }
  20949. \begin{figure}[tp]
  20950. \centering
  20951. \begin{tcolorbox}[colback=white]
  20952. \small
  20953. {\if\edition\racketEd
  20954. \[
  20955. \begin{array}{l}
  20956. \gray{\LintOpAST} \\ \hline
  20957. \gray{\LvarASTRacket{}} \\ \hline
  20958. \gray{\LifASTRacket{}} \\ \hline
  20959. \gray{\LwhileASTRacket{}} \\ \hline
  20960. \gray{\LtupASTRacket{}} \\ \hline
  20961. \gray{\LfunASTRacket} \\ \hline
  20962. \gray{\LlambdaASTRacket} \\ \hline
  20963. \LinstASTRacket \\
  20964. \begin{array}{lcl}
  20965. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20966. \end{array}
  20967. \end{array}
  20968. \]
  20969. \fi}
  20970. {\if\edition\pythonEd\pythonColor
  20971. \[
  20972. \begin{array}{l}
  20973. \gray{\LintASTPython} \\ \hline
  20974. \gray{\LvarASTPython{}} \\ \hline
  20975. \gray{\LifASTPython{}} \\ \hline
  20976. \gray{\LwhileASTPython{}} \\ \hline
  20977. \gray{\LtupASTPython{}} \\ \hline
  20978. \gray{\LfunASTPython} \\ \hline
  20979. \gray{\LlambdaASTPython} \\ \hline
  20980. \LinstASTPython \\
  20981. \begin{array}{lcl}
  20982. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20983. \end{array}
  20984. \end{array}
  20985. \]
  20986. \fi}
  20987. \end{tcolorbox}
  20988. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20989. (figure~\ref{fig:Llam-syntax}).}
  20990. \label{fig:Lpoly-prime-syntax}
  20991. \end{figure}
  20992. The output of the \code{resolve} pass on the generic \code{map}
  20993. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20994. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20995. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20996. \begin{figure}[tbp]
  20997. % poly_test_2.rkt
  20998. \begin{tcolorbox}[colback=white]
  20999. {\if\edition\racketEd
  21000. \begin{lstlisting}
  21001. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21002. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21003. (define (inc [x : Integer]) : Integer (+ x 1))
  21004. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21005. (Integer))
  21006. inc (vector 0 41)) 1)
  21007. \end{lstlisting}
  21008. \fi}
  21009. {\if\edition\pythonEd\pythonColor
  21010. \begin{lstlisting}
  21011. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21012. return (f(tup[0]), f(tup[1]))
  21013. def add1(x : int) -> int:
  21014. return x + 1
  21015. t = inst(map, {T: int})(add1, (0, 41))
  21016. print(t[1])
  21017. \end{lstlisting}
  21018. \fi}
  21019. \end{tcolorbox}
  21020. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21021. \label{fig:map-resolve}
  21022. \end{figure}
  21023. \section{Erase Generic Types}
  21024. \label{sec:erase_types}
  21025. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21026. represent type variables. For example, figure~\ref{fig:map-erase}
  21027. shows the output of the \code{erase\_types} pass on the generic
  21028. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21029. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21030. \code{All} types are removed from the type of \code{map}.
  21031. \begin{figure}[tbp]
  21032. \begin{tcolorbox}[colback=white]
  21033. {\if\edition\racketEd
  21034. \begin{lstlisting}
  21035. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21036. : (Vector Any Any)
  21037. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21038. (define (inc [x : Integer]) : Integer (+ x 1))
  21039. (vector-ref ((cast map
  21040. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21041. ((Integer -> Integer) (Vector Integer Integer)
  21042. -> (Vector Integer Integer)))
  21043. inc (vector 0 41)) 1)
  21044. \end{lstlisting}
  21045. \fi}
  21046. {\if\edition\pythonEd\pythonColor
  21047. \begin{lstlisting}
  21048. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21049. return (f(tup[0]), f(tup[1]))
  21050. def add1(x : int) -> int:
  21051. return (x + 1)
  21052. def main() -> int:
  21053. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21054. print(t[1])
  21055. return 0
  21056. \end{lstlisting}
  21057. {\small
  21058. where\\
  21059. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21060. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21061. }
  21062. \fi}
  21063. \end{tcolorbox}
  21064. \caption{The generic \code{map} example after type erasure.}
  21065. \label{fig:map-erase}
  21066. \end{figure}
  21067. This process of type erasure creates a challenge at points of
  21068. instantiation. For example, consider the instantiation of
  21069. \code{map} shown in figure~\ref{fig:map-resolve}.
  21070. The type of \code{map} is
  21071. %
  21072. {\if\edition\racketEd
  21073. \begin{lstlisting}
  21074. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21075. \end{lstlisting}
  21076. \fi}
  21077. {\if\edition\pythonEd\pythonColor
  21078. \begin{lstlisting}
  21079. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21080. \end{lstlisting}
  21081. \fi}
  21082. %
  21083. and it is instantiated to
  21084. %
  21085. {\if\edition\racketEd
  21086. \begin{lstlisting}
  21087. ((Integer -> Integer) (Vector Integer Integer)
  21088. -> (Vector Integer Integer))
  21089. \end{lstlisting}
  21090. \fi}
  21091. {\if\edition\pythonEd\pythonColor
  21092. \begin{lstlisting}
  21093. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21094. \end{lstlisting}
  21095. \fi}
  21096. %
  21097. After erasure, the type of \code{map} is
  21098. %
  21099. {\if\edition\racketEd
  21100. \begin{lstlisting}
  21101. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21102. \end{lstlisting}
  21103. \fi}
  21104. {\if\edition\pythonEd\pythonColor
  21105. \begin{lstlisting}
  21106. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21107. \end{lstlisting}
  21108. \fi}
  21109. %
  21110. but we need to convert it to the instantiated type. This is easy to
  21111. do in the language \LangCast{} with a single \code{cast}. In the
  21112. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21113. \code{map} has been compiled to a \code{cast} from the type of
  21114. \code{map} to the instantiated type. The source and the target type of a
  21115. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21116. the case because both the source and target are obtained from the same
  21117. generic type of \code{map}, replacing the type parameters with
  21118. \CANYTY{} in the former and with the deduced type arguments in the
  21119. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21120. To implement the \code{erase\_types} pass, we first recommend defining
  21121. a recursive function that translates types, named
  21122. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21123. follows.
  21124. %
  21125. {\if\edition\racketEd
  21126. \begin{lstlisting}
  21127. |$T$|
  21128. |$\Rightarrow$|
  21129. Any
  21130. \end{lstlisting}
  21131. \fi}
  21132. {\if\edition\pythonEd\pythonColor
  21133. \begin{lstlisting}
  21134. GenericVar(|$T$|)
  21135. |$\Rightarrow$|
  21136. Any
  21137. \end{lstlisting}
  21138. \fi}
  21139. %
  21140. \noindent The \code{erase\_type} function also removes the generic
  21141. \code{All} types.
  21142. %
  21143. {\if\edition\racketEd
  21144. \begin{lstlisting}
  21145. (All |$xs$| |$T_1$|)
  21146. |$\Rightarrow$|
  21147. |$T'_1$|
  21148. \end{lstlisting}
  21149. \fi}
  21150. {\if\edition\pythonEd\pythonColor
  21151. \begin{lstlisting}
  21152. AllType(|$xs$|, |$T_1$|)
  21153. |$\Rightarrow$|
  21154. |$T'_1$|
  21155. \end{lstlisting}
  21156. \fi}
  21157. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21158. %
  21159. In this compiler pass, apply the \code{erase\_type} function to all
  21160. the type annotations in the program.
  21161. Regarding the translation of expressions, the case for \code{Inst} is
  21162. the interesting one. We translate it into a \code{Cast}, as shown
  21163. next.
  21164. The type of the subexpression $e$ is a generic type of the form
  21165. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  21166. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  21167. cast is the erasure of $T$, the type $T_s$.
  21168. %
  21169. {\if\edition\racketEd
  21170. %
  21171. The target type $T_t$ is the result of substituting the argument types
  21172. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21173. erasure.
  21174. %
  21175. \begin{lstlisting}
  21176. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21177. |$\Rightarrow$|
  21178. (Cast |$e'$| |$T_s$| |$T_t$|)
  21179. \end{lstlisting}
  21180. %
  21181. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21182. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21183. \fi}
  21184. {\if\edition\pythonEd\pythonColor
  21185. %
  21186. The target type $T_t$ is the result of substituting the deduced
  21187. argument types $d$ in $T$ followed by doing type erasure.
  21188. %
  21189. \begin{lstlisting}
  21190. Inst(|$e$|, |$d$|)
  21191. |$\Rightarrow$|
  21192. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21193. \end{lstlisting}
  21194. %
  21195. where
  21196. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21197. \fi}
  21198. Finally, each generic function is translated to a regular
  21199. function in which type erasure has been applied to all the type
  21200. annotations and the body.
  21201. %% \begin{lstlisting}
  21202. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21203. %% |$\Rightarrow$|
  21204. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21205. %% \end{lstlisting}
  21206. \begin{exercise}\normalfont\normalsize
  21207. Implement a compiler for the polymorphic language \LangPoly{} by
  21208. extending and adapting your compiler for \LangGrad{}. Create six new
  21209. test programs that use polymorphic functions. Some of them should
  21210. make use of first-class generics.
  21211. \end{exercise}
  21212. \begin{figure}[tbp]
  21213. \begin{tcolorbox}[colback=white]
  21214. {\if\edition\racketEd
  21215. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21216. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21217. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21218. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21219. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21220. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21221. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21222. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21223. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21224. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21225. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21226. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21227. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21228. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21229. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21230. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21231. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21232. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21233. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21234. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21235. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21236. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21237. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21238. \path[->,bend left=15] (Lpoly) edge [above] node
  21239. {\ttfamily\footnotesize resolve} (Lpolyp);
  21240. \path[->,bend left=15] (Lpolyp) edge [above] node
  21241. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21242. \path[->,bend left=15] (Lgradualp) edge [above] node
  21243. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21244. \path[->,bend left=15] (Llambdapp) edge [left] node
  21245. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21246. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21247. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21248. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21249. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21250. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21251. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21252. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21253. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21254. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21255. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21256. \path[->,bend left=15] (F1-1) edge [above] node
  21257. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21258. \path[->,bend left=15] (F1-2) edge [above] node
  21259. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21260. \path[->,bend left=15] (F1-3) edge [left] node
  21261. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21262. \path[->,bend left=15] (F1-4) edge [below] node
  21263. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21264. \path[->,bend right=15] (F1-5) edge [above] node
  21265. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21266. \path[->,bend right=15] (F1-6) edge [above] node
  21267. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21268. \path[->,bend right=15] (C3-2) edge [right] node
  21269. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21270. \path[->,bend right=15] (x86-2) edge [right] node
  21271. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21272. \path[->,bend right=15] (x86-2-1) edge [below] node
  21273. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21274. \path[->,bend right=15] (x86-2-2) edge [right] node
  21275. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21276. \path[->,bend left=15] (x86-3) edge [above] node
  21277. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21278. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21279. \end{tikzpicture}
  21280. \fi}
  21281. {\if\edition\pythonEd\pythonColor
  21282. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21283. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21284. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21285. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21286. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21287. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21288. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21289. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21290. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21291. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21292. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21293. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21294. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21295. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21296. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21297. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21298. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21299. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21300. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21301. \path[->,bend left=15] (Lgradual) edge [above] node
  21302. {\ttfamily\footnotesize shrink} (Lgradual2);
  21303. \path[->,bend left=15] (Lgradual2) edge [above] node
  21304. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21305. \path[->,bend left=15] (Lgradual3) edge [above] node
  21306. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21307. \path[->,bend left=15] (Lgradual4) edge [left] node
  21308. {\ttfamily\footnotesize resolve} (Lgradualr);
  21309. \path[->,bend left=15] (Lgradualr) edge [below] node
  21310. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21311. \path[->,bend right=15] (Llambdapp) edge [above] node
  21312. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21313. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21314. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21315. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21316. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21317. \path[->,bend right=15] (F1-1) edge [below] node
  21318. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21319. \path[->,bend right=15] (F1-2) edge [below] node
  21320. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21321. \path[->,bend left=15] (F1-3) edge [above] node
  21322. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21323. \path[->,bend left=15] (F1-5) edge [left] node
  21324. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21325. \path[->,bend left=5] (F1-6) edge [below] node
  21326. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21327. \path[->,bend right=15] (C3-2) edge [right] node
  21328. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21329. \path[->,bend right=15] (x86-2) edge [below] node
  21330. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21331. \path[->,bend right=15] (x86-3) edge [below] node
  21332. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21333. \path[->,bend left=15] (x86-4) edge [above] node
  21334. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21335. \end{tikzpicture}
  21336. \fi}
  21337. \end{tcolorbox}
  21338. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21339. \label{fig:Lpoly-passes}
  21340. \end{figure}
  21341. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21342. needed to compile \LangPoly{}.
  21343. % TODO: challenge problem: specialization of instantiations
  21344. % Further Reading
  21345. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21346. \clearpage
  21347. \appendix
  21348. \chapter{Appendix}
  21349. \setcounter{footnote}{0}
  21350. {\if\edition\racketEd
  21351. \section{Interpreters}
  21352. \label{appendix:interp}
  21353. \index{subject}{interpreter}
  21354. We provide interpreters for each of the source languages \LangInt{},
  21355. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21356. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21357. intermediate languages \LangCVar{} and \LangCIf{} are in
  21358. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21359. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21360. \key{interp.rkt} file.
  21361. \section{Utility Functions}
  21362. \label{appendix:utilities}
  21363. The utility functions described in this section are in the
  21364. \key{utilities.rkt} file of the support code.
  21365. \paragraph{\code{interp-tests}}
  21366. This function runs the compiler passes and the interpreters on each of
  21367. the specified tests to check whether each pass is correct. The
  21368. \key{interp-tests} function has the following parameters:
  21369. \begin{description}
  21370. \item[name (a string)] A name to identify the compiler,
  21371. \item[typechecker] A function of exactly one argument that either
  21372. raises an error using the \code{error} function when it encounters a
  21373. type error or returns \code{\#f} when it encounters a type
  21374. error. If there is no type error, the type checker returns the
  21375. program.
  21376. \item[passes] A list with one entry per pass. An entry is a list
  21377. consisting of four things:
  21378. \begin{enumerate}
  21379. \item a string giving the name of the pass;
  21380. \item the function that implements the pass (a translator from AST
  21381. to AST);
  21382. \item a function that implements the interpreter (a function from
  21383. AST to result value) for the output language; and,
  21384. \item a type checker for the output language. Type checkers for
  21385. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21386. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21387. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21388. type checker entry is optional. The support code does not provide
  21389. type checkers for the x86 languages.
  21390. \end{enumerate}
  21391. \item[source-interp] An interpreter for the source language. The
  21392. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21393. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21394. \item[tests] A list of test numbers that specifies which tests to
  21395. run (explained next).
  21396. \end{description}
  21397. %
  21398. The \key{interp-tests} function assumes that the subdirectory
  21399. \key{tests} has a collection of Racket programs whose names all start
  21400. with the family name, followed by an underscore and then the test
  21401. number, and ending with the file extension \key{.rkt}. Also, for each test
  21402. program that calls \code{read} one or more times, there is a file with
  21403. the same name except that the file extension is \key{.in}, which
  21404. provides the input for the Racket program. If the test program is
  21405. expected to fail type checking, then there should be an empty file of
  21406. the same name with extension \key{.tyerr}.
  21407. \paragraph{\code{compiler-tests}}
  21408. This function runs the compiler passes to generate x86 (a \key{.s}
  21409. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21410. It runs the machine code and checks that the output is $42$. The
  21411. parameters to the \code{compiler-tests} function are similar to those
  21412. of the \code{interp-tests} function, and they consist of
  21413. \begin{itemize}
  21414. \item a compiler name (a string),
  21415. \item a type checker,
  21416. \item description of the passes,
  21417. \item name of a test-family, and
  21418. \item a list of test numbers.
  21419. \end{itemize}
  21420. \paragraph{\code{compile-file}}
  21421. This function takes a description of the compiler passes (see the
  21422. comment for \key{interp-tests}) and returns a function that, given a
  21423. program file name (a string ending in \key{.rkt}), applies all the
  21424. passes and writes the output to a file whose name is the same as the
  21425. program file name with extension \key{.rkt} replaced by \key{.s}.
  21426. \paragraph{\code{read-program}}
  21427. This function takes a file path and parses that file (it must be a
  21428. Racket program) into an abstract syntax tree.
  21429. \paragraph{\code{parse-program}}
  21430. This function takes an S-expression representation of an abstract
  21431. syntax tree and converts it into the struct-based representation.
  21432. \paragraph{\code{assert}}
  21433. This function takes two parameters, a string (\code{msg}) and Boolean
  21434. (\code{bool}), and displays the message \key{msg} if the Boolean
  21435. \key{bool} is false.
  21436. \paragraph{\code{lookup}}
  21437. % remove discussion of lookup? -Jeremy
  21438. This function takes a key and an alist and returns the first value that is
  21439. associated with the given key, if there is one. If not, an error is
  21440. triggered. The alist may contain both immutable pairs (built with
  21441. \key{cons}) and mutable pairs (built with \key{mcons}).
  21442. %The \key{map2} function ...
  21443. \fi} %\racketEd
  21444. \section{x86 Instruction Set Quick Reference}
  21445. \label{sec:x86-quick-reference}
  21446. \index{subject}{x86}
  21447. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21448. do. We write $A \to B$ to mean that the value of $A$ is written into
  21449. location $B$. Address offsets are given in bytes. The instruction
  21450. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21451. registers (such as \code{\%rax}), or memory references (such as
  21452. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21453. reference per instruction. Other operands must be immediates or
  21454. registers.
  21455. \begin{table}[tbp]
  21456. \centering
  21457. \begin{tabular}{l|l}
  21458. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21459. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21460. \texttt{negq} $A$ & $- A \to A$ \\
  21461. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21462. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21463. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21464. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21465. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21466. \texttt{retq} & Pops the return address and jumps to it \\
  21467. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21468. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21469. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21470. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21471. be an immediate) \\
  21472. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21473. matches the condition code of the instruction; otherwise go to the
  21474. next instructions. The condition codes are \key{e} for \emph{equal},
  21475. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21476. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21477. \texttt{jl} $L$ & \\
  21478. \texttt{jle} $L$ & \\
  21479. \texttt{jg} $L$ & \\
  21480. \texttt{jge} $L$ & \\
  21481. \texttt{jmp} $L$ & Jump to label $L$ \\
  21482. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21483. \texttt{movzbq} $A$, $B$ &
  21484. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21485. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21486. and the extra bytes of $B$ are set to zero.} \\
  21487. & \\
  21488. & \\
  21489. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21490. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21491. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21492. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21493. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21494. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21495. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21496. description of the condition codes. $A$ must be a single byte register
  21497. (e.g., \texttt{al} or \texttt{cl}).} \\
  21498. \texttt{setl} $A$ & \\
  21499. \texttt{setle} $A$ & \\
  21500. \texttt{setg} $A$ & \\
  21501. \texttt{setge} $A$ &
  21502. \end{tabular}
  21503. \vspace{5pt}
  21504. \caption{Quick reference for the x86 instructions used in this book.}
  21505. \label{tab:x86-instr}
  21506. \end{table}
  21507. %% \if\edition\racketEd
  21508. %% \cleardoublepage
  21509. %% \section{Concrete Syntax for Intermediate Languages}
  21510. %% The concrete syntax of \LangAny{} is defined in
  21511. %% figure~\ref{fig:Lany-concrete-syntax}.
  21512. %% \begin{figure}[tp]
  21513. %% \centering
  21514. %% \fbox{
  21515. %% \begin{minipage}{0.97\textwidth}\small
  21516. %% \[
  21517. %% \begin{array}{lcl}
  21518. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  21519. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  21520. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  21521. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  21522. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  21523. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  21524. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  21525. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  21526. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  21527. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  21528. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  21529. %% \MID \LP\key{void?}\;\Exp\RP \\
  21530. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  21531. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  21532. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  21533. %% \end{array}
  21534. %% \]
  21535. %% \end{minipage}
  21536. %% }
  21537. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  21538. %% (figure~\ref{fig:Llam-syntax}).}
  21539. %% \label{fig:Lany-concrete-syntax}
  21540. %% \end{figure}
  21541. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  21542. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  21543. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  21544. %% \ref{fig:c3-concrete-syntax}, respectively.
  21545. %% \begin{figure}[tbp]
  21546. %% \fbox{
  21547. %% \begin{minipage}{0.96\textwidth}
  21548. %% \small
  21549. %% \[
  21550. %% \begin{array}{lcl}
  21551. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  21552. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21553. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  21554. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  21555. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  21556. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  21557. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  21558. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  21559. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  21560. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  21561. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  21562. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  21563. %% \end{array}
  21564. %% \]
  21565. %% \end{minipage}
  21566. %% }
  21567. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  21568. %% \label{fig:c2-concrete-syntax}
  21569. %% \end{figure}
  21570. %% \begin{figure}[tp]
  21571. %% \fbox{
  21572. %% \begin{minipage}{0.96\textwidth}
  21573. %% \small
  21574. %% \[
  21575. %% \begin{array}{lcl}
  21576. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  21577. %% \\
  21578. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21579. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  21580. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  21581. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  21582. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  21583. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  21584. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  21585. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  21586. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  21587. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  21588. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  21589. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  21590. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  21591. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  21592. %% \LangCFunM{} & ::= & \Def\ldots
  21593. %% \end{array}
  21594. %% \]
  21595. %% \end{minipage}
  21596. %% }
  21597. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  21598. %% \label{fig:c3-concrete-syntax}
  21599. %% \end{figure}
  21600. %% \fi % racketEd
  21601. \backmatter
  21602. \addtocontents{toc}{\vspace{11pt}}
  21603. %% \addtocontents{toc}{\vspace{11pt}}
  21604. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  21605. \nocite{*}\let\bibname\refname
  21606. \addcontentsline{toc}{fmbm}{\refname}
  21607. \printbibliography
  21608. %\printindex{authors}{Author Index}
  21609. \printindex{subject}{Index}
  21610. \end{document}
  21611. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21612. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21613. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21614. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21615. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21616. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21617. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21618. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21619. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21620. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21621. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21622. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21623. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21624. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21625. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21626. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21627. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21628. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21629. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21630. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21631. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21632. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21633. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21634. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21635. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21636. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21637. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21638. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21639. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21640. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21641. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21642. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21643. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21644. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21645. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21646. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21647. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21648. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21649. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21650. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21651. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21652. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21653. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21654. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21655. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21656. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21657. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21658. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21659. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21660. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21661. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21662. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21663. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21664. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21665. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21666. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21667. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21668. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21669. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21670. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21671. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21672. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21673. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21674. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21675. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21676. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21677. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21678. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21679. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21680. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21681. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21682. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21683. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21684. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21685. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21686. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21687. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21688. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21689. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21690. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21691. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21692. % LocalWords: pseudocode underapproximation underapproximations LALR
  21693. % LocalWords: semilattices overapproximate incrementing Earley docs
  21694. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21695. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21696. % LocalWords: subparses