book.tex 819 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563
  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. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  32. %% For multiple indices:
  33. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  34. \makeindex{subject}
  35. %\makeindex{authors}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. \if\edition\racketEd
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  42. deletekeywords={read,mapping,vector},
  43. escapechar=|,
  44. columns=flexible,
  45. %moredelim=[is][\color{red}]{~}{~},
  46. showstringspaces=false
  47. }
  48. \fi
  49. \if\edition\pythonEd
  50. \lstset{%
  51. language=Python,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={match,case,bool,int,let},
  54. deletekeywords={},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. %%% Any shortcut own defined macros place here
  62. %% sample of author macro:
  63. \input{defs}
  64. \newtheorem{exercise}[theorem]{Exercise}
  65. \numberwithin{theorem}{chapter}
  66. \numberwithin{definition}{chapter}
  67. \numberwithin{equation}{chapter}
  68. % Adjusted settings
  69. \setlength{\columnsep}{4pt}
  70. %% \begingroup
  71. %% \setlength{\intextsep}{0pt}%
  72. %% \setlength{\columnsep}{0pt}%
  73. %% \begin{wrapfigure}{r}{0.5\textwidth}
  74. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  75. %% \caption{Basic layout}
  76. %% \end{wrapfigure}
  77. %% \lipsum[1]
  78. %% \endgroup
  79. \newbox\oiintbox
  80. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  81. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  82. \def\oiint{\copy\oiintbox}
  83. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  84. %\usepackage{showframe}
  85. \def\ShowFrameLinethickness{0.125pt}
  86. \addbibresource{book.bib}
  87. \if\edition\pythonEd
  88. \addbibresource{python.bib}
  89. \fi
  90. \begin{document}
  91. \frontmatter
  92. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  93. \HalfTitle{Essentials of Compilation}
  94. \halftitlepage
  95. \clearemptydoublepage
  96. \Title{Essentials of Compilation}
  97. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  98. %\edition{First Edition}
  99. \BookAuthor{Jeremy G. Siek}
  100. \imprint{The MIT Press\\
  101. Cambridge, Massachusetts\\
  102. London, England}
  103. \begin{copyrightpage}
  104. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  105. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  106. Subject to such license, all rights are reserved. \\[2ex]
  107. \includegraphics{CCBY-logo}
  108. The MIT Press would like to thank the anonymous peer reviewers who
  109. provided comments on drafts of this book. The generous work of
  110. academic experts is essential for establishing the authority and
  111. quality of our publications. We acknowledge with gratitude the
  112. contributions of these otherwise uncredited readers.
  113. This book was set in Times LT Std Roman by the author. Printed and
  114. bound in the United States of America.
  115. Library of Congress Cataloging-in-Publication Data is available.
  116. ISBN:
  117. 10 9 8 7 6 5 4 3 2 1
  118. %% Jeremy G. Siek. Available for free viewing
  119. %% or personal downloading under the
  120. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  121. %% license.
  122. %% Copyright in this monograph has been licensed exclusively to The MIT
  123. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  124. %% version to the public in 2022. All inquiries regarding rights should
  125. %% be addressed to The MIT Press, Rights and Permissions Department.
  126. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  127. %% All rights reserved. No part of this book may be reproduced in any
  128. %% form by any electronic or mechanical means (including photocopying,
  129. %% recording, or information storage and retrieval) without permission in
  130. %% writing from the publisher.
  131. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  132. %% United States of America.
  133. %% Library of Congress Cataloging-in-Publication Data is available.
  134. %% ISBN:
  135. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  136. \end{copyrightpage}
  137. \dedication{This book is dedicated to Katie, my partner in everything,
  138. my children, who grew up during the writing of this book, and the
  139. programming language students at Indiana University, whose
  140. thoughtful questions made this a better book.}
  141. %% \begin{epigraphpage}
  142. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  143. %% \textit{Book Name if any}}
  144. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  145. %% \end{epigraphpage}
  146. \tableofcontents
  147. %\listoffigures
  148. %\listoftables
  149. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  150. \chapter*{Preface}
  151. \addcontentsline{toc}{fmbm}{Preface}
  152. There is a magical moment when a programmer presses the run button
  153. and the software begins to execute. Somehow a program written in a
  154. high-level language is running on a computer that is capable only of
  155. shuffling bits. Here we reveal the wizardry that makes that moment
  156. possible. Beginning with the groundbreaking work of Backus and
  157. colleagues in the 1950s, computer scientists developed techniques for
  158. constructing programs called \emph{compilers} that automatically
  159. translate high-level programs into machine code.
  160. We take you on a journey through constructing your own compiler for a
  161. small but powerful language. Along the way we explain the essential
  162. concepts, algorithms, and data structures that underlie compilers. We
  163. develop your understanding of how programs are mapped onto computer
  164. hardware, which is helpful in reasoning about properties at the
  165. junction of hardware and software, such as execution time, software
  166. errors, and security vulnerabilities. For those interested in
  167. pursuing compiler construction as a career, our goal is to provide a
  168. stepping-stone to advanced topics such as just-in-time compilation,
  169. program analysis, and program optimization. For those interested in
  170. designing and implementing programming languages, we connect language
  171. design choices to their impact on the compiler and the generated code.
  172. A compiler is typically organized as a sequence of stages that
  173. progressively translate a program to the code that runs on
  174. hardware. We take this approach to the extreme by partitioning our
  175. compiler into a large number of \emph{nanopasses}, each of which
  176. performs a single task. This enables the testing of each pass in
  177. isolation and focuses our attention, making the compiler far easier to
  178. understand.
  179. The most familiar approach to describing compilers is to dedicate each
  180. chapter to one pass. The problem with that approach is that it
  181. obfuscates how language features motivate design choices in a
  182. compiler. We instead take an \emph{incremental} approach in which we
  183. build a complete compiler in each chapter, starting with a small input
  184. language that includes only arithmetic and variables. We add new
  185. language features in subsequent chapters, extending the compiler as
  186. necessary.
  187. Our choice of language features is designed to elicit fundamental
  188. concepts and algorithms used in compilers.
  189. \begin{itemize}
  190. \item We begin with integer arithmetic and local variables in
  191. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  192. the fundamental tools of compiler construction: \emph{abstract
  193. syntax trees} and \emph{recursive functions}.
  194. {\if\edition\pythonEd
  195. \item In Chapter~\ref{ch:parsing} we learn how to use the Lark
  196. parser generator to create a parser for the language of integer
  197. arithmetic and local variables. We learn about the parsing
  198. algorithms inside Lark, including Earley and LALR(1).
  199. %
  200. \fi}
  201. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  202. \emph{graph coloring} to assign variables to machine registers.
  203. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  204. motivates an elegant recursive algorithm for translating them into
  205. conditional \code{goto} statements.
  206. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  207. variables}. This elicits the need for \emph{dataflow
  208. analysis} in the register allocator.
  209. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  210. \emph{garbage collection}.
  211. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  212. without lexical scoping, similar to functions in the C programming
  213. language~\citep{Kernighan:1988nx}. The reader learns about the
  214. procedure call stack and \emph{calling conventions} and how they interact
  215. with register allocation and garbage collection. The chapter also
  216. describes how to generate efficient tail calls.
  217. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  218. scoping, that is, \emph{lambda} expressions. The reader learns about
  219. \emph{closure conversion}, in which lambdas are translated into a
  220. combination of functions and tuples.
  221. % Chapter about classes and objects?
  222. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  223. point the input languages are statically typed. The reader extends
  224. the statically typed language with an \code{Any} type that serves
  225. as a target for compiling the dynamically typed language.
  226. %% {\if\edition\pythonEd
  227. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  228. %% \emph{classes}.
  229. %% \fi}
  230. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  231. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  232. in which different regions of a program may be static or dynamically
  233. typed. The reader implements runtime support for \emph{proxies} that
  234. allow values to safely move between regions.
  235. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  236. leveraging the \code{Any} type and type casts developed in chapters
  237. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  238. \end{itemize}
  239. There are many language features that we do not include. Our choices
  240. balance the incidental complexity of a feature versus the fundamental
  241. concepts that it exposes. For example, we include tuples and not
  242. records because although they both elicit the study of heap allocation and
  243. garbage collection, records come with more incidental complexity.
  244. Since 2009, drafts of this book have served as the textbook for
  245. sixteen week compiler courses for upper-level undergraduates and
  246. first-year graduate students at the University of Colorado and Indiana
  247. University.
  248. %
  249. Students come into the course having learned the basics of
  250. programming, data structures and algorithms, and discrete
  251. mathematics.
  252. %
  253. At the beginning of the course, students form groups of two to four
  254. people. The groups complete approximately one chapter every two
  255. weeks, starting with chapter~\ref{ch:Lvar}. The last two weeks of the
  256. course involve a final project in which students design and implement
  257. a compiler extension of their choosing. The last few chapters can be
  258. used in support of these projects. Many chapters include a challenge
  259. problem that we assign to the graduate students. For compiler courses
  260. at universities on the quarter system (about ten weeks in length), we
  261. recommend completing the course through chapter~\ref{ch:Lvec} or
  262. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  263. students for each compiler pass.
  264. %
  265. The course can be adapted to emphasize functional languages by
  266. skipping chapter~\ref{ch:Lwhile} (loops) and including
  267. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  268. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  269. %
  270. %% \python{A course that emphasizes object-oriented languages would
  271. %% include Chapter~\ref{ch:Lobject}.}
  272. %
  273. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  274. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  275. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  276. tail calls.
  277. This book has been used in compiler courses at California Polytechnic
  278. State University, Portland State University, Rose–Hulman Institute of
  279. Technology, University of Freiburg, University of Massachusetts
  280. Lowell, and the University of Vermont.
  281. \begin{figure}[tp]
  282. \begin{tcolorbox}[colback=white]
  283. {\if\edition\racketEd
  284. \begin{tikzpicture}[baseline=(current bounding box.center)]
  285. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  286. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  287. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  288. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  289. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  290. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  291. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  292. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  293. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  294. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  295. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  296. \path[->] (C1) edge [above] node {} (C2);
  297. \path[->] (C2) edge [above] node {} (C3);
  298. \path[->] (C3) edge [above] node {} (C4);
  299. \path[->] (C4) edge [above] node {} (C5);
  300. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  301. \path[->] (C5) edge [above] node {} (C7);
  302. \path[->] (C6) edge [above] node {} (C7);
  303. \path[->] (C4) edge [above] node {} (C8);
  304. \path[->] (C4) edge [above] node {} (C9);
  305. \path[->] (C7) edge [above] node {} (C10);
  306. \path[->] (C8) edge [above] node {} (C10);
  307. \path[->] (C10) edge [above] node {} (C11);
  308. \end{tikzpicture}
  309. \fi}
  310. {\if\edition\pythonEd
  311. \begin{tikzpicture}[baseline=(current bounding box.center)]
  312. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  313. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  314. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  315. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  316. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  317. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  318. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  319. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  320. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  321. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  322. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  323. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  324. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  325. \path[->] (Prelim) edge [above] node {} (Var);
  326. \path[->] (Var) edge [above] node {} (Reg);
  327. \path[->] (Var) edge [above] node {} (Parse);
  328. \path[->] (Reg) edge [above] node {} (Cond);
  329. \path[->] (Cond) edge [above] node {} (Tuple);
  330. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  331. \path[->] (Cond) edge [above] node {} (Fun);
  332. \path[->] (Tuple) edge [above] node {} (Lam);
  333. \path[->] (Fun) edge [above] node {} (Lam);
  334. \path[->] (Cond) edge [above] node {} (Dyn);
  335. \path[->] (Cond) edge [above] node {} (Loop);
  336. \path[->] (Lam) edge [above] node {} (Gradual);
  337. \path[->] (Dyn) edge [above] node {} (Gradual);
  338. % \path[->] (Dyn) edge [above] node {} (CO);
  339. \path[->] (Gradual) edge [above] node {} (Generic);
  340. \end{tikzpicture}
  341. \fi}
  342. \end{tcolorbox}
  343. \caption{Diagram of chapter dependencies.}
  344. \label{fig:chapter-dependences}
  345. \end{figure}
  346. \racket{
  347. We use the \href{https://racket-lang.org/}{Racket} language both for
  348. the implementation of the compiler and for the input language, so the
  349. reader should be proficient with Racket or Scheme. There are many
  350. excellent resources for learning Scheme and
  351. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  352. }
  353. \python{
  354. This edition of the book uses \href{https://www.python.org/}{Python}
  355. both for the implementation of the compiler and for the input language, so the
  356. reader should be proficient with Python. There are many
  357. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  358. }
  359. The support code for this book is in the GitHub repository at
  360. the following location:
  361. \begin{center}\small\texttt
  362. https://github.com/IUCompilerCourse/
  363. \end{center}
  364. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  365. is helpful but not necessary for the reader to have taken a computer
  366. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  367. assembly language that are needed in the compiler.
  368. %
  369. We follow the System V calling
  370. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  371. that we generate works with the runtime system (written in C) when it
  372. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  373. operating systems on Intel hardware.
  374. %
  375. On the Windows operating system, \code{gcc} uses the Microsoft x64
  376. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  377. assembly code that we generate does \emph{not} work with the runtime
  378. system on Windows. One workaround is to use a virtual machine with
  379. Linux as the guest operating system.
  380. \section*{Acknowledgments}
  381. The tradition of compiler construction at Indiana University goes back
  382. to research and courses on programming languages by Daniel Friedman in
  383. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  384. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  385. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  386. the compiler course and continued the development of Chez Scheme.
  387. %
  388. The compiler course evolved to incorporate novel pedagogical ideas
  389. while also including elements of real-world compilers. One of
  390. Friedman's ideas was to split the compiler into many small
  391. passes. Another idea, called ``the game,'' was to test the code
  392. generated by each pass using interpreters.
  393. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  394. developed infrastructure to support this approach and evolved the
  395. course to use even smaller
  396. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  397. design decisions in this book are inspired by the assignment
  398. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  399. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  400. organization of the course made it difficult for students to
  401. understand the rationale for the compiler design. Ghuloum proposed the
  402. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  403. based.
  404. We thank the many students who served as teaching assistants for the
  405. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  406. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  407. garbage collector and x86 interpreter, Michael Vollmer for work on
  408. efficient tail calls, and Michael Vitousek for help with the first
  409. offering of the incremental compiler course at IU.
  410. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  411. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  412. Michael Wollowski for teaching courses based on drafts of this book
  413. and for their feedback. We thank the National Science Foundation for
  414. the grants that helped to support this work: Grant Numbers 1518844,
  415. 1763922, and 1814460.
  416. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  417. course in the early 2000s and especially for finding the bug that
  418. sent our garbage collector on a wild goose chase!
  419. \mbox{}\\
  420. \noindent Jeremy G. Siek \\
  421. Bloomington, Indiana
  422. \mainmatter
  423. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  424. \chapter{Preliminaries}
  425. \label{ch:trees-recur}
  426. \setcounter{footnote}{0}
  427. In this chapter we review the basic tools needed to implement a
  428. compiler. Programs are typically input by a programmer as text, that
  429. is, a sequence of characters. The program-as-text representation is
  430. called \emph{concrete syntax}. We use concrete syntax to concisely
  431. write down and talk about programs. Inside the compiler, we use
  432. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  433. that efficiently supports the operations that the compiler needs to
  434. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  435. syntax}\index{subject}{abstract syntax
  436. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  437. The process of translating from concrete syntax to abstract syntax is
  438. called \emph{parsing}\python{ and is studied in
  439. chapter~\ref{ch:parsing}}.
  440. \racket{This book does not cover the theory and implementation of parsing.
  441. We refer the readers interested in parsing to the thorough treatment
  442. of parsing by \citet{Aho:2006wb}.}%
  443. %
  444. \racket{A parser is provided in the support code for translating from
  445. concrete to abstract syntax.}%
  446. %
  447. \python{For now we use Python's \code{ast} module to translate from concrete
  448. to abstract syntax.}
  449. ASTs can be represented inside the compiler in many different ways,
  450. depending on the programming language used to write the compiler.
  451. %
  452. \racket{We use Racket's
  453. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  454. feature to represent ASTs (section~\ref{sec:ast}).}
  455. %
  456. \python{We use Python classes and objects to represent ASTs, especially the
  457. classes defined in the standard \code{ast} module for the Python
  458. source language.}
  459. %
  460. We use grammars to define the abstract syntax of programming languages
  461. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  462. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  463. recursive functions to construct and deconstruct ASTs
  464. (section~\ref{sec:recursion}). This chapter provides a brief
  465. introduction to these components.
  466. \racket{\index{subject}{struct}}
  467. \python{\index{subject}{class}\index{subject}{object}}
  468. \section{Abstract Syntax Trees}
  469. \label{sec:ast}
  470. Compilers use abstract syntax trees to represent programs because they
  471. often need to ask questions such as, for a given part of a program,
  472. what kind of language feature is it? What are its subparts? Consider
  473. the program on the left and the diagram of its AST on the
  474. right~\eqref{eq:arith-prog}. This program is an addition operation
  475. that has two subparts, a \racket{read}\python{input} operation and a
  476. negation. The negation has another subpart, the integer constant
  477. \code{8}. By using a tree to represent the program, we can easily
  478. follow the links to go from one part of a program to its subparts.
  479. \begin{center}
  480. \begin{minipage}{0.4\textwidth}
  481. \if\edition\racketEd
  482. \begin{lstlisting}
  483. (+ (read) (- 8))
  484. \end{lstlisting}
  485. \fi
  486. \if\edition\pythonEd
  487. \begin{lstlisting}
  488. input_int() + -8
  489. \end{lstlisting}
  490. \fi
  491. \end{minipage}
  492. \begin{minipage}{0.4\textwidth}
  493. \begin{equation}
  494. \begin{tikzpicture}
  495. \node[draw] (plus) at (0 , 0) {\key{+}};
  496. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  497. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  498. \node[draw] (8) at (1 , -3) {\key{8}};
  499. \draw[->] (plus) to (read);
  500. \draw[->] (plus) to (minus);
  501. \draw[->] (minus) to (8);
  502. \end{tikzpicture}
  503. \label{eq:arith-prog}
  504. \end{equation}
  505. \end{minipage}
  506. \end{center}
  507. We use the standard terminology for trees to describe ASTs: each
  508. rectangle above is called a \emph{node}. The arrows connect a node to its
  509. \emph{children}, which are also nodes. The top-most node is the
  510. \emph{root}. Every node except for the root has a \emph{parent} (the
  511. node of which it is the child). If a node has no children, it is a
  512. \emph{leaf} node; otherwise it is an \emph{internal} node.
  513. \index{subject}{node}
  514. \index{subject}{children}
  515. \index{subject}{root}
  516. \index{subject}{parent}
  517. \index{subject}{leaf}
  518. \index{subject}{internal node}
  519. %% Recall that an \emph{symbolic expression} (S-expression) is either
  520. %% \begin{enumerate}
  521. %% \item an atom, or
  522. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  523. %% where $e_1$ and $e_2$ are each an S-expression.
  524. %% \end{enumerate}
  525. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  526. %% null value \code{'()}, etc. We can create an S-expression in Racket
  527. %% simply by writing a backquote (called a quasi-quote in Racket)
  528. %% followed by the textual representation of the S-expression. It is
  529. %% quite common to use S-expressions to represent a list, such as $a, b
  530. %% ,c$ in the following way:
  531. %% \begin{lstlisting}
  532. %% `(a . (b . (c . ())))
  533. %% \end{lstlisting}
  534. %% Each element of the list is in the first slot of a pair, and the
  535. %% second slot is either the rest of the list or the null value, to mark
  536. %% the end of the list. Such lists are so common that Racket provides
  537. %% special notation for them that removes the need for the periods
  538. %% and so many parenthesis:
  539. %% \begin{lstlisting}
  540. %% `(a b c)
  541. %% \end{lstlisting}
  542. %% The following expression creates an S-expression that represents AST
  543. %% \eqref{eq:arith-prog}.
  544. %% \begin{lstlisting}
  545. %% `(+ (read) (- 8))
  546. %% \end{lstlisting}
  547. %% When using S-expressions to represent ASTs, the convention is to
  548. %% represent each AST node as a list and to put the operation symbol at
  549. %% the front of the list. The rest of the list contains the children. So
  550. %% in the above case, the root AST node has operation \code{`+} and its
  551. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  552. %% diagram \eqref{eq:arith-prog}.
  553. %% To build larger S-expressions one often needs to splice together
  554. %% several smaller S-expressions. Racket provides the comma operator to
  555. %% splice an S-expression into a larger one. For example, instead of
  556. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  557. %% we could have first created an S-expression for AST
  558. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  559. %% S-expression.
  560. %% \begin{lstlisting}
  561. %% (define ast1.4 `(- 8))
  562. %% (define ast1_1 `(+ (read) ,ast1.4))
  563. %% \end{lstlisting}
  564. %% In general, the Racket expression that follows the comma (splice)
  565. %% can be any expression that produces an S-expression.
  566. {\if\edition\racketEd
  567. We define a Racket \code{struct} for each kind of node. For this
  568. chapter we require just two kinds of nodes: one for integer constants
  569. and one for primitive operations. The following is the \code{struct}
  570. definition for integer constants.\footnote{All the AST structures are
  571. defined in the file \code{utilities.rkt} in the support code.}
  572. \begin{lstlisting}
  573. (struct Int (value))
  574. \end{lstlisting}
  575. An integer node contains just one thing: the integer value.
  576. We establish the convention that \code{struct} names, such
  577. as \code{Int}, are capitalized.
  578. To create an AST node for the integer $8$, we write \INT{8}.
  579. \begin{lstlisting}
  580. (define eight (Int 8))
  581. \end{lstlisting}
  582. We say that the value created by \INT{8} is an
  583. \emph{instance} of the
  584. \code{Int} structure.
  585. The following is the \code{struct} definition for primitive operations.
  586. \begin{lstlisting}
  587. (struct Prim (op args))
  588. \end{lstlisting}
  589. A primitive operation node includes an operator symbol \code{op} and a
  590. list of child arguments called \code{args}. For example, to create an
  591. AST that negates the number $8$, we write the following.
  592. \begin{lstlisting}
  593. (define neg-eight (Prim '- (list eight)))
  594. \end{lstlisting}
  595. Primitive operations may have zero or more children. The \code{read}
  596. operator has zero:
  597. \begin{lstlisting}
  598. (define rd (Prim 'read '()))
  599. \end{lstlisting}
  600. The addition operator has two children:
  601. \begin{lstlisting}
  602. (define ast1_1 (Prim '+ (list rd neg-eight)))
  603. \end{lstlisting}
  604. We have made a design choice regarding the \code{Prim} structure.
  605. Instead of using one structure for many different operations
  606. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  607. structure for each operation, as follows:
  608. \begin{lstlisting}
  609. (struct Read ())
  610. (struct Add (left right))
  611. (struct Neg (value))
  612. \end{lstlisting}
  613. The reason that we choose to use just one structure is that many parts
  614. of the compiler can use the same code for the different primitive
  615. operators, so we might as well just write that code once by using a
  616. single structure.
  617. %
  618. \fi}
  619. {\if\edition\pythonEd
  620. We use a Python \code{class} for each kind of node.
  621. The following is the class definition for
  622. constants from the Python \code{ast} module.
  623. \begin{lstlisting}
  624. class Constant:
  625. def __init__(self, value):
  626. self.value = value
  627. \end{lstlisting}
  628. An integer constant node includes just one thing: the integer value.
  629. To create an AST node for the integer $8$, we write \INT{8}.
  630. \begin{lstlisting}
  631. eight = Constant(8)
  632. \end{lstlisting}
  633. We say that the value created by \INT{8} is an
  634. \emph{instance} of the \code{Constant} class.
  635. The following is the class definition for unary operators.
  636. \begin{lstlisting}
  637. class UnaryOp:
  638. def __init__(self, op, operand):
  639. self.op = op
  640. self.operand = operand
  641. \end{lstlisting}
  642. The specific operation is specified by the \code{op} parameter. For
  643. example, the class \code{USub} is for unary subtraction.
  644. (More unary operators are introduced in later chapters.) To create an AST that
  645. negates the number $8$, we write the following.
  646. \begin{lstlisting}
  647. neg_eight = UnaryOp(USub(), eight)
  648. \end{lstlisting}
  649. The call to the \code{input\_int} function is represented by the
  650. \code{Call} and \code{Name} classes.
  651. \begin{lstlisting}
  652. class Call:
  653. def __init__(self, func, args):
  654. self.func = func
  655. self.args = args
  656. class Name:
  657. def __init__(self, id):
  658. self.id = id
  659. \end{lstlisting}
  660. To create an AST node that calls \code{input\_int}, we write
  661. \begin{lstlisting}
  662. read = Call(Name('input_int'), [])
  663. \end{lstlisting}
  664. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  665. the \code{BinOp} class for binary operators.
  666. \begin{lstlisting}
  667. class BinOp:
  668. def __init__(self, left, op, right):
  669. self.op = op
  670. self.left = left
  671. self.right = right
  672. \end{lstlisting}
  673. Similar to \code{UnaryOp}, the specific operation is specified by the
  674. \code{op} parameter, which for now is just an instance of the
  675. \code{Add} class. So to create the AST
  676. node that adds negative eight to some user input, we write the following.
  677. \begin{lstlisting}
  678. ast1_1 = BinOp(read, Add(), neg_eight)
  679. \end{lstlisting}
  680. \fi}
  681. To compile a program such as \eqref{eq:arith-prog}, we need to know
  682. that the operation associated with the root node is addition and we
  683. need to be able to access its two
  684. children. \racket{Racket}\python{Python} provides pattern matching to
  685. support these kinds of queries, as we see in
  686. section~\ref{sec:pattern-matching}.
  687. We often write down the concrete syntax of a program even when we
  688. actually have in mind the AST, because the concrete syntax is more
  689. concise. We recommend that you always think of programs as abstract
  690. syntax trees.
  691. \section{Grammars}
  692. \label{sec:grammar}
  693. \index{subject}{integer}
  694. \index{subject}{literal}
  695. %\index{subject}{constant}
  696. A programming language can be thought of as a \emph{set} of programs.
  697. The set is infinite (that is, one can always create larger programs),
  698. so one cannot simply describe a language by listing all the
  699. programs in the language. Instead we write down a set of rules, a
  700. \emph{context-free grammar}, for building programs. Grammars are often used to
  701. define the concrete syntax of a language, but they can also be used to
  702. describe the abstract syntax. We write our rules in a variant of
  703. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  704. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  705. we describe a small language, named \LangInt{}, that consists of
  706. integers and arithmetic operations.\index{subject}{grammar}
  707. \index{subject}{context-free grammar}
  708. The first grammar rule for the abstract syntax of \LangInt{} says that an
  709. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  710. \begin{equation}
  711. \Exp ::= \INT{\Int} \label{eq:arith-int}
  712. \end{equation}
  713. %
  714. Each rule has a left-hand side and a right-hand side.
  715. If you have an AST node that matches the
  716. right-hand side, then you can categorize it according to the
  717. left-hand side.
  718. %
  719. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  720. are \emph{terminal} symbols and must literally appear in the program for the
  721. rule to be applicable.\index{subject}{terminal}
  722. %
  723. Our grammars do not mention \emph{white space}, that is, delimiter
  724. characters like spaces, tabs, and new lines. White space may be
  725. inserted between symbols for disambiguation and to improve
  726. readability. \index{subject}{white space}
  727. %
  728. A name such as $\Exp$ that is defined by the grammar rules is a
  729. \emph{nonterminal}. \index{subject}{nonterminal}
  730. %
  731. The name $\Int$ is also a nonterminal, but instead of defining it with
  732. a grammar rule, we define it with the following explanation. An
  733. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  734. $-$ (for negative integers), such that the sequence of decimals
  735. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  736. enables the representation of integers using 63 bits, which simplifies
  737. several aspects of compilation.
  738. %
  739. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  740. datatype on a 64-bit machine.}
  741. %
  742. \python{In contrast, integers in Python have unlimited precision, but
  743. the techniques needed to handle unlimited precision fall outside the
  744. scope of this book.}
  745. The second grammar rule is the \READOP{} operation, which receives an
  746. input integer from the user of the program.
  747. \begin{equation}
  748. \Exp ::= \READ{} \label{eq:arith-read}
  749. \end{equation}
  750. The third rule categorizes the negation of an $\Exp$ node as an
  751. $\Exp$.
  752. \begin{equation}
  753. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  754. \end{equation}
  755. We can apply these rules to categorize the ASTs that are in the
  756. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  757. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  758. following AST is an $\Exp$.
  759. \begin{center}
  760. \begin{minipage}{0.5\textwidth}
  761. \NEG{\INT{\code{8}}}
  762. \end{minipage}
  763. \begin{minipage}{0.25\textwidth}
  764. \begin{equation}
  765. \begin{tikzpicture}
  766. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  767. \node[draw, circle] (8) at (0, -1.2) {$8$};
  768. \draw[->] (minus) to (8);
  769. \end{tikzpicture}
  770. \label{eq:arith-neg8}
  771. \end{equation}
  772. \end{minipage}
  773. \end{center}
  774. The next two grammar rules are for addition and subtraction expressions:
  775. \begin{align}
  776. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  777. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  778. \end{align}
  779. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  780. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  781. \eqref{eq:arith-read}, and we have already categorized
  782. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  783. to show that
  784. \[
  785. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  786. \]
  787. is an $\Exp$ in the \LangInt{} language.
  788. If you have an AST for which these rules do not apply, then the
  789. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  790. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  791. because there is no rule for the \key{*} operator. Whenever we
  792. define a language with a grammar, the language includes only those
  793. programs that are justified by the grammar rules.
  794. {\if\edition\pythonEd
  795. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  796. There is a statement for printing the value of an expression
  797. \[
  798. \Stmt{} ::= \PRINT{\Exp}
  799. \]
  800. and a statement that evaluates an expression but ignores the result.
  801. \[
  802. \Stmt{} ::= \EXPR{\Exp}
  803. \]
  804. \fi}
  805. {\if\edition\racketEd
  806. The last grammar rule for \LangInt{} states that there is a
  807. \code{Program} node to mark the top of the whole program:
  808. \[
  809. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  810. \]
  811. The \code{Program} structure is defined as follows:
  812. \begin{lstlisting}
  813. (struct Program (info body))
  814. \end{lstlisting}
  815. where \code{body} is an expression. In further chapters, the \code{info}
  816. part is used to store auxiliary information, but for now it is
  817. just the empty list.
  818. \fi}
  819. {\if\edition\pythonEd
  820. The last grammar rule for \LangInt{} states that there is a
  821. \code{Module} node to mark the top of the whole program:
  822. \[
  823. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  824. \]
  825. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  826. this case, a list of statements.
  827. %
  828. The \code{Module} class is defined as follows
  829. \begin{lstlisting}
  830. class Module:
  831. def __init__(self, body):
  832. self.body = body
  833. \end{lstlisting}
  834. where \code{body} is a list of statements.
  835. \fi}
  836. It is common to have many grammar rules with the same left-hand side
  837. but different right-hand sides, such as the rules for $\Exp$ in the
  838. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  839. combine several right-hand sides into a single rule.
  840. The concrete syntax for \LangInt{} is shown in
  841. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  842. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  843. %
  844. \racket{The \code{read-program} function provided in
  845. \code{utilities.rkt} of the support code reads a program from a file
  846. (the sequence of characters in the concrete syntax of Racket) and
  847. parses it into an abstract syntax tree. Refer to the description of
  848. \code{read-program} in appendix~\ref{appendix:utilities} for more
  849. details.}
  850. %
  851. \python{The \code{parse} function in Python's \code{ast} module
  852. converts the concrete syntax (represented as a string) into an
  853. abstract syntax tree.}
  854. \newcommand{\LintGrammarRacket}{
  855. \begin{array}{rcl}
  856. \Type &::=& \key{Integer} \\
  857. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  858. \MID \CSUB{\Exp}{\Exp}
  859. \end{array}
  860. }
  861. \newcommand{\LintASTRacket}{
  862. \begin{array}{rcl}
  863. \Type &::=& \key{Integer} \\
  864. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  865. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  866. \end{array}
  867. }
  868. \newcommand{\LintGrammarPython}{
  869. \begin{array}{rcl}
  870. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  871. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  872. \end{array}
  873. }
  874. \newcommand{\LintASTPython}{
  875. \begin{array}{rcl}
  876. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  877. \itm{unaryop} &::= & \code{USub()} \\
  878. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  879. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  880. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  881. \end{array}
  882. }
  883. \begin{figure}[tp]
  884. \begin{tcolorbox}[colback=white]
  885. {\if\edition\racketEd
  886. \[
  887. \begin{array}{l}
  888. \LintGrammarRacket \\
  889. \begin{array}{rcl}
  890. \LangInt{} &::=& \Exp
  891. \end{array}
  892. \end{array}
  893. \]
  894. \fi}
  895. {\if\edition\pythonEd
  896. \[
  897. \begin{array}{l}
  898. \LintGrammarPython \\
  899. \begin{array}{rcl}
  900. \LangInt{} &::=& \Stmt^{*}
  901. \end{array}
  902. \end{array}
  903. \]
  904. \fi}
  905. \end{tcolorbox}
  906. \caption{The concrete syntax of \LangInt{}.}
  907. \label{fig:r0-concrete-syntax}
  908. \end{figure}
  909. \begin{figure}[tp]
  910. \begin{tcolorbox}[colback=white]
  911. {\if\edition\racketEd
  912. \[
  913. \begin{array}{l}
  914. \LintASTRacket{} \\
  915. \begin{array}{rcl}
  916. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  917. \end{array}
  918. \end{array}
  919. \]
  920. \fi}
  921. {\if\edition\pythonEd
  922. \[
  923. \begin{array}{l}
  924. \LintASTPython\\
  925. \begin{array}{rcl}
  926. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  927. \end{array}
  928. \end{array}
  929. \]
  930. \fi}
  931. \end{tcolorbox}
  932. \python{
  933. \index{subject}{Constant@\texttt{Constant}}
  934. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  935. \index{subject}{USub@\texttt{USub}}
  936. \index{subject}{inputint@\texttt{input\_int}}
  937. \index{subject}{Call@\texttt{Call}}
  938. \index{subject}{Name@\texttt{Name}}
  939. \index{subject}{BinOp@\texttt{BinOp}}
  940. \index{subject}{Add@\texttt{Add}}
  941. \index{subject}{Sub@\texttt{Sub}}
  942. \index{subject}{print@\texttt{print}}
  943. \index{subject}{Expr@\texttt{Expr}}
  944. \index{subject}{Module@\texttt{Module}}
  945. }
  946. \caption{The abstract syntax of \LangInt{}.}
  947. \label{fig:r0-syntax}
  948. \end{figure}
  949. \section{Pattern Matching}
  950. \label{sec:pattern-matching}
  951. As mentioned in section~\ref{sec:ast}, compilers often need to access
  952. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  953. provides the \texttt{match} feature to access the parts of a value.
  954. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  955. \begin{center}
  956. \begin{minipage}{0.5\textwidth}
  957. {\if\edition\racketEd
  958. \begin{lstlisting}
  959. (match ast1_1
  960. [(Prim op (list child1 child2))
  961. (print op)])
  962. \end{lstlisting}
  963. \fi}
  964. {\if\edition\pythonEd
  965. \begin{lstlisting}
  966. match ast1_1:
  967. case BinOp(child1, op, child2):
  968. print(op)
  969. \end{lstlisting}
  970. \fi}
  971. \end{minipage}
  972. \end{center}
  973. {\if\edition\racketEd
  974. %
  975. In this example, the \texttt{match} form checks whether the AST
  976. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  977. three pattern variables \texttt{op}, \texttt{child1}, and
  978. \texttt{child2}. In general, a match clause consists of a
  979. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  980. recursively defined to be a pattern variable, a structure name
  981. followed by a pattern for each of the structure's arguments, or an
  982. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  983. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  984. and chapter 9 of The Racket
  985. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  986. for complete descriptions of \code{match}.)
  987. %
  988. The body of a match clause may contain arbitrary Racket code. The
  989. pattern variables can be used in the scope of the body, such as
  990. \code{op} in \code{(print op)}.
  991. %
  992. \fi}
  993. %
  994. %
  995. {\if\edition\pythonEd
  996. %
  997. In the above example, the \texttt{match} form checks whether the AST
  998. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  999. three pattern variables \texttt{child1}, \texttt{op}, and
  1000. \texttt{child2}, and then prints out the operator. In general, each
  1001. \code{case} consists of a \emph{pattern} and a
  1002. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  1003. to be either a pattern variable, a class name followed by a pattern
  1004. for each of its constructor's arguments, or other literals such as
  1005. strings, lists, etc.
  1006. %
  1007. The body of each \code{case} may contain arbitrary Python code. The
  1008. pattern variables can be used in the body, such as \code{op} in
  1009. \code{print(op)}.
  1010. %
  1011. \fi}
  1012. A \code{match} form may contain several clauses, as in the following
  1013. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1014. the AST. The \code{match} proceeds through the clauses in order,
  1015. checking whether the pattern can match the input AST. The body of the
  1016. first clause that matches is executed. The output of \code{leaf} for
  1017. several ASTs is shown on the right side of the following:
  1018. \begin{center}
  1019. \begin{minipage}{0.6\textwidth}
  1020. {\if\edition\racketEd
  1021. \begin{lstlisting}
  1022. (define (leaf arith)
  1023. (match arith
  1024. [(Int n) #t]
  1025. [(Prim 'read '()) #t]
  1026. [(Prim '- (list e1)) #f]
  1027. [(Prim '+ (list e1 e2)) #f]
  1028. [(Prim '- (list e1 e2)) #f]))
  1029. (leaf (Prim 'read '()))
  1030. (leaf (Prim '- (list (Int 8))))
  1031. (leaf (Int 8))
  1032. \end{lstlisting}
  1033. \fi}
  1034. {\if\edition\pythonEd
  1035. \begin{lstlisting}
  1036. def leaf(arith):
  1037. match arith:
  1038. case Constant(n):
  1039. return True
  1040. case Call(Name('input_int'), []):
  1041. return True
  1042. case UnaryOp(USub(), e1):
  1043. return False
  1044. case BinOp(e1, Add(), e2):
  1045. return False
  1046. case BinOp(e1, Sub(), e2):
  1047. return False
  1048. print(leaf(Call(Name('input_int'), [])))
  1049. print(leaf(UnaryOp(USub(), eight)))
  1050. print(leaf(Constant(8)))
  1051. \end{lstlisting}
  1052. \fi}
  1053. \end{minipage}
  1054. \vrule
  1055. \begin{minipage}{0.25\textwidth}
  1056. {\if\edition\racketEd
  1057. \begin{lstlisting}
  1058. #t
  1059. #f
  1060. #t
  1061. \end{lstlisting}
  1062. \fi}
  1063. {\if\edition\pythonEd
  1064. \begin{lstlisting}
  1065. True
  1066. False
  1067. True
  1068. \end{lstlisting}
  1069. \fi}
  1070. \end{minipage}
  1071. \end{center}
  1072. When constructing a \code{match} expression, we refer to the grammar
  1073. definition to identify which nonterminal we are expecting to match
  1074. against, and then we make sure that (1) we have one
  1075. \racket{clause}\python{case} for each alternative of that nonterminal
  1076. and (2) the pattern in each \racket{clause}\python{case}
  1077. corresponds to the corresponding right-hand side of a grammar
  1078. rule. For the \code{match} in the \code{leaf} function, we refer to
  1079. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1080. nonterminal has four alternatives, so the \code{match} has four
  1081. \racket{clauses}\python{cases}. The pattern in each
  1082. \racket{clause}\python{case} corresponds to the right-hand side of a
  1083. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1084. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1085. translating from grammars to patterns, replace nonterminals such as
  1086. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1087. \code{e2}).
  1088. \section{Recursive Functions}
  1089. \label{sec:recursion}
  1090. \index{subject}{recursive function}
  1091. Programs are inherently recursive. For example, an expression is often
  1092. made of smaller expressions. Thus, the natural way to process an
  1093. entire program is to use a recursive function. As a first example of
  1094. such a recursive function, we define the function \code{is\_exp} as
  1095. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1096. value and determine whether or not it is an expression in \LangInt{}.
  1097. %
  1098. We say that a function is defined by \emph{structural recursion} if
  1099. it is defined using a sequence of match \racket{clauses}\python{cases}
  1100. that correspond to a grammar and the body of each
  1101. \racket{clause}\python{case} makes a recursive call on each child
  1102. node.\footnote{This principle of structuring code according to the
  1103. data definition is advocated in the book \emph{How to Design
  1104. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1105. second function, named \code{stmt}, that recognizes whether a value
  1106. is a \LangInt{} statement.} \python{Finally, }
  1107. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1108. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1109. In general, we can write one recursive function to handle each
  1110. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1111. two examples at the bottom of the figure, the first is in
  1112. \LangInt{} and the second is not.
  1113. \begin{figure}[tp]
  1114. \begin{tcolorbox}[colback=white]
  1115. {\if\edition\racketEd
  1116. \begin{lstlisting}
  1117. (define (is_exp ast)
  1118. (match ast
  1119. [(Int n) #t]
  1120. [(Prim 'read '()) #t]
  1121. [(Prim '- (list e)) (is_exp e)]
  1122. [(Prim '+ (list e1 e2))
  1123. (and (is_exp e1) (is_exp e2))]
  1124. [(Prim '- (list e1 e2))
  1125. (and (is_exp e1) (is_exp e2))]
  1126. [else #f]))
  1127. (define (is_Lint ast)
  1128. (match ast
  1129. [(Program '() e) (is_exp e)]
  1130. [else #f]))
  1131. (is_Lint (Program '() ast1_1)
  1132. (is_Lint (Program '()
  1133. (Prim '* (list (Prim 'read '())
  1134. (Prim '+ (list (Int 8)))))))
  1135. \end{lstlisting}
  1136. \fi}
  1137. {\if\edition\pythonEd
  1138. \begin{lstlisting}
  1139. def is_exp(e):
  1140. match e:
  1141. case Constant(n):
  1142. return True
  1143. case Call(Name('input_int'), []):
  1144. return True
  1145. case UnaryOp(USub(), e1):
  1146. return is_exp(e1)
  1147. case BinOp(e1, Add(), e2):
  1148. return is_exp(e1) and is_exp(e2)
  1149. case BinOp(e1, Sub(), e2):
  1150. return is_exp(e1) and is_exp(e2)
  1151. case _:
  1152. return False
  1153. def stmt(s):
  1154. match s:
  1155. case Expr(Call(Name('print'), [e])):
  1156. return is_exp(e)
  1157. case Expr(e):
  1158. return is_exp(e)
  1159. case _:
  1160. return False
  1161. def is_Lint(p):
  1162. match p:
  1163. case Module(body):
  1164. return all([stmt(s) for s in body])
  1165. case _:
  1166. return False
  1167. print(is_Lint(Module([Expr(ast1_1)])))
  1168. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1169. UnaryOp(Add(), Constant(8))))])))
  1170. \end{lstlisting}
  1171. \fi}
  1172. \end{tcolorbox}
  1173. \caption{Example of recursive functions for \LangInt{}. These functions
  1174. recognize whether an AST is in \LangInt{}.}
  1175. \label{fig:exp-predicate}
  1176. \end{figure}
  1177. %% You may be tempted to merge the two functions into one, like this:
  1178. %% \begin{center}
  1179. %% \begin{minipage}{0.5\textwidth}
  1180. %% \begin{lstlisting}
  1181. %% (define (Lint ast)
  1182. %% (match ast
  1183. %% [(Int n) #t]
  1184. %% [(Prim 'read '()) #t]
  1185. %% [(Prim '- (list e)) (Lint e)]
  1186. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1187. %% [(Program '() e) (Lint e)]
  1188. %% [else #f]))
  1189. %% \end{lstlisting}
  1190. %% \end{minipage}
  1191. %% \end{center}
  1192. %% %
  1193. %% Sometimes such a trick will save a few lines of code, especially when
  1194. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1195. %% \emph{not} recommended because it can get you into trouble.
  1196. %% %
  1197. %% For example, the above function is subtly wrong:
  1198. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1199. %% returns true when it should return false.
  1200. \section{Interpreters}
  1201. \label{sec:interp_Lint}
  1202. \index{subject}{interpreter}
  1203. The behavior of a program is defined by the specification of the
  1204. programming language.
  1205. %
  1206. \racket{For example, the Scheme language is defined in the report by
  1207. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1208. reference manual~\citep{plt-tr}.}
  1209. %
  1210. \python{For example, the Python language is defined in the Python
  1211. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1212. %
  1213. In this book we use interpreters to specify each language that we
  1214. consider. An interpreter that is designated as the definition of a
  1215. language is called a \emph{definitional
  1216. interpreter}~\citep{reynolds72:_def_interp}.
  1217. \index{subject}{definitional interpreter} We warm up by creating a
  1218. definitional interpreter for the \LangInt{} language. This interpreter
  1219. serves as a second example of structural recursion. The definition of the
  1220. \code{interp\_Lint} function is shown in
  1221. figure~\ref{fig:interp_Lint}.
  1222. %
  1223. \racket{The body of the function is a match on the input program
  1224. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1225. which in turn has one match clause per grammar rule for \LangInt{}
  1226. expressions.}
  1227. %
  1228. \python{The body of the function matches on the \code{Module} AST node
  1229. and then invokes \code{interp\_stmt} on each statement in the
  1230. module. The \code{interp\_stmt} function includes a case for each
  1231. grammar rule of the \Stmt{} nonterminal and it calls
  1232. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1233. function includes a case for each grammar rule of the \Exp{}
  1234. nonterminal.}
  1235. \begin{figure}[tp]
  1236. \begin{tcolorbox}[colback=white]
  1237. {\if\edition\racketEd
  1238. \begin{lstlisting}
  1239. (define (interp_exp e)
  1240. (match e
  1241. [(Int n) n]
  1242. [(Prim 'read '())
  1243. (define r (read))
  1244. (cond [(fixnum? r) r]
  1245. [else (error 'interp_exp "read expected an integer" r)])]
  1246. [(Prim '- (list e))
  1247. (define v (interp_exp e))
  1248. (fx- 0 v)]
  1249. [(Prim '+ (list e1 e2))
  1250. (define v1 (interp_exp e1))
  1251. (define v2 (interp_exp e2))
  1252. (fx+ v1 v2)]
  1253. [(Prim '- (list e1 e2))
  1254. (define v1 ((interp-exp env) e1))
  1255. (define v2 ((interp-exp env) e2))
  1256. (fx- v1 v2)]))
  1257. (define (interp_Lint p)
  1258. (match p
  1259. [(Program '() e) (interp_exp e)]))
  1260. \end{lstlisting}
  1261. \fi}
  1262. {\if\edition\pythonEd
  1263. \begin{lstlisting}
  1264. def interp_exp(e):
  1265. match e:
  1266. case BinOp(left, Add(), right):
  1267. l = interp_exp(left); r = interp_exp(right)
  1268. return l + r
  1269. case BinOp(left, Sub(), right):
  1270. l = interp_exp(left); r = interp_exp(right)
  1271. return l - r
  1272. case UnaryOp(USub(), v):
  1273. return - interp_exp(v)
  1274. case Constant(value):
  1275. return value
  1276. case Call(Name('input_int'), []):
  1277. return int(input())
  1278. def interp_stmt(s):
  1279. match s:
  1280. case Expr(Call(Name('print'), [arg])):
  1281. print(interp_exp(arg))
  1282. case Expr(value):
  1283. interp_exp(value)
  1284. def interp_Lint(p):
  1285. match p:
  1286. case Module(body):
  1287. for s in body:
  1288. interp_stmt(s)
  1289. \end{lstlisting}
  1290. \fi}
  1291. \end{tcolorbox}
  1292. \caption{Interpreter for the \LangInt{} language.}
  1293. \label{fig:interp_Lint}
  1294. \end{figure}
  1295. Let us consider the result of interpreting a few \LangInt{} programs. The
  1296. following program adds two integers:
  1297. {\if\edition\racketEd
  1298. \begin{lstlisting}
  1299. (+ 10 32)
  1300. \end{lstlisting}
  1301. \fi}
  1302. {\if\edition\pythonEd
  1303. \begin{lstlisting}
  1304. print(10 + 32)
  1305. \end{lstlisting}
  1306. \fi}
  1307. %
  1308. \noindent The result is \key{42}, the answer to life, the universe,
  1309. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1310. the Galaxy} by Douglas Adams.}
  1311. %
  1312. We wrote this program in concrete syntax, whereas the parsed
  1313. abstract syntax is
  1314. {\if\edition\racketEd
  1315. \begin{lstlisting}
  1316. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1317. \end{lstlisting}
  1318. \fi}
  1319. {\if\edition\pythonEd
  1320. \begin{lstlisting}
  1321. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1322. \end{lstlisting}
  1323. \fi}
  1324. The following program demonstrates that expressions may be nested within
  1325. each other, in this case nesting several additions and negations.
  1326. {\if\edition\racketEd
  1327. \begin{lstlisting}
  1328. (+ 10 (- (+ 12 20)))
  1329. \end{lstlisting}
  1330. \fi}
  1331. {\if\edition\pythonEd
  1332. \begin{lstlisting}
  1333. print(10 + -(12 + 20))
  1334. \end{lstlisting}
  1335. \fi}
  1336. %
  1337. \noindent What is the result of this program?
  1338. {\if\edition\racketEd
  1339. As mentioned previously, the \LangInt{} language does not support
  1340. arbitrarily large integers but only $63$-bit integers, so we
  1341. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1342. in Racket.
  1343. Suppose that
  1344. \[
  1345. n = 999999999999999999
  1346. \]
  1347. which indeed fits in $63$ bits. What happens when we run the
  1348. following program in our interpreter?
  1349. \begin{lstlisting}
  1350. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1351. \end{lstlisting}
  1352. It produces the following error:
  1353. \begin{lstlisting}
  1354. fx+: result is not a fixnum
  1355. \end{lstlisting}
  1356. We establish the convention that if running the definitional
  1357. interpreter on a program produces an error, then the meaning of that
  1358. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1359. error is a \code{trapped-error}. A compiler for the language is under
  1360. no obligation regarding programs with unspecified behavior; it does
  1361. not have to produce an executable, and if it does, that executable can
  1362. do anything. On the other hand, if the error is a
  1363. \code{trapped-error}, then the compiler must produce an executable and
  1364. it is required to report that an error occurred. To signal an error,
  1365. exit with a return code of \code{255}. The interpreters in chapters
  1366. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1367. \code{trapped-error}.
  1368. \fi}
  1369. % TODO: how to deal with too-large integers in the Python interpreter?
  1370. %% This convention applies to the languages defined in this
  1371. %% book, as a way to simplify the student's task of implementing them,
  1372. %% but this convention is not applicable to all programming languages.
  1373. %%
  1374. The last feature of the \LangInt{} language, the \READOP{} operation,
  1375. prompts the user of the program for an integer. Recall that program
  1376. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1377. \code{8}. So, if we run {\if\edition\racketEd
  1378. \begin{lstlisting}
  1379. (interp_Lint (Program '() ast1_1))
  1380. \end{lstlisting}
  1381. \fi}
  1382. {\if\edition\pythonEd
  1383. \begin{lstlisting}
  1384. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1385. \end{lstlisting}
  1386. \fi}
  1387. \noindent and if the input is \code{50}, the result is \code{42}.
  1388. We include the \READOP{} operation in \LangInt{} so that a clever
  1389. student cannot implement a compiler for \LangInt{} that simply runs
  1390. the interpreter during compilation to obtain the output and then
  1391. generates the trivial code to produce the output.\footnote{Yes, a
  1392. clever student did this in the first instance of this course!}
  1393. The job of a compiler is to translate a program in one language into a
  1394. program in another language so that the output program behaves the
  1395. same way as the input program. This idea is depicted in the
  1396. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1397. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1398. Given a compiler that translates from language $\mathcal{L}_1$ to
  1399. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1400. compiler must translate it into some program $P_2$ such that
  1401. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1402. same input $i$ yields the same output $o$.
  1403. \begin{equation} \label{eq:compile-correct}
  1404. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1405. \node (p1) at (0, 0) {$P_1$};
  1406. \node (p2) at (3, 0) {$P_2$};
  1407. \node (o) at (3, -2.5) {$o$};
  1408. \path[->] (p1) edge [above] node {compile} (p2);
  1409. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1410. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1411. \end{tikzpicture}
  1412. \end{equation}
  1413. In the next section we see our first example of a compiler.
  1414. \section{Example Compiler: A Partial Evaluator}
  1415. \label{sec:partial-evaluation}
  1416. In this section we consider a compiler that translates \LangInt{}
  1417. programs into \LangInt{} programs that may be more efficient. The
  1418. compiler eagerly computes the parts of the program that do not depend
  1419. on any inputs, a process known as \emph{partial
  1420. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1421. For example, given the following program
  1422. {\if\edition\racketEd
  1423. \begin{lstlisting}
  1424. (+ (read) (- (+ 5 3)))
  1425. \end{lstlisting}
  1426. \fi}
  1427. {\if\edition\pythonEd
  1428. \begin{lstlisting}
  1429. print(input_int() + -(5 + 3) )
  1430. \end{lstlisting}
  1431. \fi}
  1432. \noindent our compiler translates it into the program
  1433. {\if\edition\racketEd
  1434. \begin{lstlisting}
  1435. (+ (read) -8)
  1436. \end{lstlisting}
  1437. \fi}
  1438. {\if\edition\pythonEd
  1439. \begin{lstlisting}
  1440. print(input_int() + -8)
  1441. \end{lstlisting}
  1442. \fi}
  1443. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1444. evaluator for the \LangInt{} language. The output of the partial evaluator
  1445. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1446. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1447. whereas the code for partially evaluating the negation and addition
  1448. operations is factored into three auxiliary functions:
  1449. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1450. functions is the output of partially evaluating the children.
  1451. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1452. arguments are integers and if they are, perform the appropriate
  1453. arithmetic. Otherwise, they create an AST node for the arithmetic
  1454. operation.
  1455. \begin{figure}[tp]
  1456. \begin{tcolorbox}[colback=white]
  1457. {\if\edition\racketEd
  1458. \begin{lstlisting}
  1459. (define (pe_neg r)
  1460. (match r
  1461. [(Int n) (Int (fx- 0 n))]
  1462. [else (Prim '- (list r))]))
  1463. (define (pe_add r1 r2)
  1464. (match* (r1 r2)
  1465. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1466. [(_ _) (Prim '+ (list r1 r2))]))
  1467. (define (pe_sub r1 r2)
  1468. (match* (r1 r2)
  1469. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1470. [(_ _) (Prim '- (list r1 r2))]))
  1471. (define (pe_exp e)
  1472. (match e
  1473. [(Int n) (Int n)]
  1474. [(Prim 'read '()) (Prim 'read '())]
  1475. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1476. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1477. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1478. (define (pe_Lint p)
  1479. (match p
  1480. [(Program '() e) (Program '() (pe_exp e))]))
  1481. \end{lstlisting}
  1482. \fi}
  1483. {\if\edition\pythonEd
  1484. \begin{lstlisting}
  1485. def pe_neg(r):
  1486. match r:
  1487. case Constant(n):
  1488. return Constant(-n)
  1489. case _:
  1490. return UnaryOp(USub(), r)
  1491. def pe_add(r1, r2):
  1492. match (r1, r2):
  1493. case (Constant(n1), Constant(n2)):
  1494. return Constant(n1 + n2)
  1495. case _:
  1496. return BinOp(r1, Add(), r2)
  1497. def pe_sub(r1, r2):
  1498. match (r1, r2):
  1499. case (Constant(n1), Constant(n2)):
  1500. return Constant(n1 - n2)
  1501. case _:
  1502. return BinOp(r1, Sub(), r2)
  1503. def pe_exp(e):
  1504. match e:
  1505. case BinOp(left, Add(), right):
  1506. return pe_add(pe_exp(left), pe_exp(right))
  1507. case BinOp(left, Sub(), right):
  1508. return pe_sub(pe_exp(left), pe_exp(right))
  1509. case UnaryOp(USub(), v):
  1510. return pe_neg(pe_exp(v))
  1511. case Constant(value):
  1512. return e
  1513. case Call(Name('input_int'), []):
  1514. return e
  1515. def pe_stmt(s):
  1516. match s:
  1517. case Expr(Call(Name('print'), [arg])):
  1518. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1519. case Expr(value):
  1520. return Expr(pe_exp(value))
  1521. def pe_P_int(p):
  1522. match p:
  1523. case Module(body):
  1524. new_body = [pe_stmt(s) for s in body]
  1525. return Module(new_body)
  1526. \end{lstlisting}
  1527. \fi}
  1528. \end{tcolorbox}
  1529. \caption{A partial evaluator for \LangInt{}.}
  1530. \label{fig:pe-arith}
  1531. \end{figure}
  1532. To gain some confidence that the partial evaluator is correct, we can
  1533. test whether it produces programs that produce the same result as the
  1534. input programs. That is, we can test whether it satisfies the diagram
  1535. of \eqref{eq:compile-correct}.
  1536. %
  1537. {\if\edition\racketEd
  1538. The following code runs the partial evaluator on several examples and
  1539. tests the output program. The \texttt{parse-program} and
  1540. \texttt{assert} functions are defined in
  1541. appendix~\ref{appendix:utilities}.\\
  1542. \begin{minipage}{1.0\textwidth}
  1543. \begin{lstlisting}
  1544. (define (test_pe p)
  1545. (assert "testing pe_Lint"
  1546. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1547. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1548. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1549. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1550. \end{lstlisting}
  1551. \end{minipage}
  1552. \fi}
  1553. % TODO: python version of testing the PE
  1554. \begin{exercise}\normalfont\normalsize
  1555. Create three programs in the \LangInt{} language and test whether
  1556. partially evaluating them with \code{pe\_Lint} and then
  1557. interpreting them with \code{interp\_Lint} gives the same result
  1558. as directly interpreting them with \code{interp\_Lint}.
  1559. \end{exercise}
  1560. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1561. \chapter{Integers and Variables}
  1562. \label{ch:Lvar}
  1563. \setcounter{footnote}{0}
  1564. This chapter covers compiling a subset of
  1565. \racket{Racket}\python{Python} to x86-64 assembly
  1566. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1567. integer arithmetic and local variables. We often refer to x86-64
  1568. simply as x86. The chapter first describes the \LangVar{} language
  1569. (section~\ref{sec:s0}) and then introduces x86 assembly
  1570. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1571. discuss only the instructions needed for compiling \LangVar{}. We
  1572. introduce more x86 instructions in subsequent chapters. After
  1573. introducing \LangVar{} and x86, we reflect on their differences and
  1574. create a plan to break down the translation from \LangVar{} to x86
  1575. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1576. the chapter gives detailed hints regarding each step. We aim to give
  1577. enough hints that the well-prepared reader, together with a few
  1578. friends, can implement a compiler from \LangVar{} to x86 in a short
  1579. time. To suggest the scale of this first compiler, we note that the
  1580. instructor solution for the \LangVar{} compiler is approximately
  1581. \racket{500}\python{300} lines of code.
  1582. \section{The \LangVar{} Language}
  1583. \label{sec:s0}
  1584. \index{subject}{variable}
  1585. The \LangVar{} language extends the \LangInt{} language with
  1586. variables. The concrete syntax of the \LangVar{} language is defined
  1587. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1588. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1589. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1590. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1591. \key{-} is a unary operator, and \key{+} is a binary operator.
  1592. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1593. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1594. the top of the program.
  1595. %% The $\itm{info}$
  1596. %% field of the \key{Program} structure contains an \emph{association
  1597. %% list} (a list of key-value pairs) that is used to communicate
  1598. %% auxiliary data from one compiler pass the next.
  1599. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1600. exhibit several compilation techniques.
  1601. \newcommand{\LvarGrammarRacket}{
  1602. \begin{array}{rcl}
  1603. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1604. \end{array}
  1605. }
  1606. \newcommand{\LvarASTRacket}{
  1607. \begin{array}{rcl}
  1608. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1609. \end{array}
  1610. }
  1611. \newcommand{\LvarGrammarPython}{
  1612. \begin{array}{rcl}
  1613. \Exp &::=& \Var{} \\
  1614. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1615. \end{array}
  1616. }
  1617. \newcommand{\LvarASTPython}{
  1618. \begin{array}{rcl}
  1619. \Exp{} &::=& \VAR{\Var{}} \\
  1620. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1621. \end{array}
  1622. }
  1623. \begin{figure}[tp]
  1624. \centering
  1625. \begin{tcolorbox}[colback=white]
  1626. {\if\edition\racketEd
  1627. \[
  1628. \begin{array}{l}
  1629. \gray{\LintGrammarRacket{}} \\ \hline
  1630. \LvarGrammarRacket{} \\
  1631. \begin{array}{rcl}
  1632. \LangVarM{} &::=& \Exp
  1633. \end{array}
  1634. \end{array}
  1635. \]
  1636. \fi}
  1637. {\if\edition\pythonEd
  1638. \[
  1639. \begin{array}{l}
  1640. \gray{\LintGrammarPython} \\ \hline
  1641. \LvarGrammarPython \\
  1642. \begin{array}{rcl}
  1643. \LangVarM{} &::=& \Stmt^{*}
  1644. \end{array}
  1645. \end{array}
  1646. \]
  1647. \fi}
  1648. \end{tcolorbox}
  1649. \caption{The concrete syntax of \LangVar{}.}
  1650. \label{fig:Lvar-concrete-syntax}
  1651. \end{figure}
  1652. \begin{figure}[tp]
  1653. \centering
  1654. \begin{tcolorbox}[colback=white]
  1655. {\if\edition\racketEd
  1656. \[
  1657. \begin{array}{l}
  1658. \gray{\LintASTRacket{}} \\ \hline
  1659. \LvarASTRacket \\
  1660. \begin{array}{rcl}
  1661. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1662. \end{array}
  1663. \end{array}
  1664. \]
  1665. \fi}
  1666. {\if\edition\pythonEd
  1667. \[
  1668. \begin{array}{l}
  1669. \gray{\LintASTPython}\\ \hline
  1670. \LvarASTPython \\
  1671. \begin{array}{rcl}
  1672. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1673. \end{array}
  1674. \end{array}
  1675. \]
  1676. \fi}
  1677. \end{tcolorbox}
  1678. \caption{The abstract syntax of \LangVar{}.}
  1679. \label{fig:Lvar-syntax}
  1680. \end{figure}
  1681. {\if\edition\racketEd
  1682. Let us dive further into the syntax and semantics of the \LangVar{}
  1683. language. The \key{let} feature defines a variable for use within its
  1684. body and initializes the variable with the value of an expression.
  1685. The abstract syntax for \key{let} is shown in
  1686. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1687. \begin{lstlisting}
  1688. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1689. \end{lstlisting}
  1690. For example, the following program initializes \code{x} to $32$ and then
  1691. evaluates the body \code{(+ 10 x)}, producing $42$.
  1692. \begin{lstlisting}
  1693. (let ([x (+ 12 20)]) (+ 10 x))
  1694. \end{lstlisting}
  1695. \fi}
  1696. %
  1697. {\if\edition\pythonEd
  1698. %
  1699. The \LangVar{} language includes assignment statements, which define a
  1700. variable for use in later statements and initializes the variable with
  1701. the value of an expression. The abstract syntax for assignment is
  1702. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1703. assignment is \index{subject}{Assign@\texttt{Assign}}
  1704. \begin{lstlisting}
  1705. |$\itm{var}$| = |$\itm{exp}$|
  1706. \end{lstlisting}
  1707. For example, the following program initializes the variable \code{x}
  1708. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1709. \begin{lstlisting}
  1710. x = 12 + 20
  1711. print(10 + x)
  1712. \end{lstlisting}
  1713. \fi}
  1714. {\if\edition\racketEd
  1715. %
  1716. When there are multiple \key{let}s for the same variable, the closest
  1717. enclosing \key{let} is used. That is, variable definitions overshadow
  1718. prior definitions. Consider the following program with two \key{let}s
  1719. that define two variables named \code{x}. Can you figure out the
  1720. result?
  1721. \begin{lstlisting}
  1722. (let ([x 32]) (+ (let ([x 10]) x) x))
  1723. \end{lstlisting}
  1724. For the purposes of depicting which variable occurrences correspond to
  1725. which definitions, the following shows the \code{x}'s annotated with
  1726. subscripts to distinguish them. Double check that your answer for the
  1727. previous program is the same as your answer for this annotated version
  1728. of the program.
  1729. \begin{lstlisting}
  1730. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1731. \end{lstlisting}
  1732. The initializing expression is always evaluated before the body of the
  1733. \key{let}, so in the following, the \key{read} for \code{x} is
  1734. performed before the \key{read} for \code{y}. Given the input
  1735. $52$ then $10$, the following produces $42$ (not $-42$).
  1736. \begin{lstlisting}
  1737. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1738. \end{lstlisting}
  1739. \fi}
  1740. \subsection{Extensible Interpreters via Method Overriding}
  1741. \label{sec:extensible-interp}
  1742. To prepare for discussing the interpreter of \LangVar{}, we explain
  1743. why we implement it in an object-oriented style. Throughout this book
  1744. we define many interpreters, one for each language that we
  1745. study. Because each language builds on the prior one, there is a lot
  1746. of commonality between these interpreters. We want to write down the
  1747. common parts just once instead of many times. A naive interpreter for
  1748. \LangVar{} would handle the \racket{cases for variables and
  1749. \code{let}} \python{case for variables} but dispatch to an
  1750. interpreter for \LangInt{} in the rest of the cases. The following
  1751. code sketches this idea. (We explain the \code{env} parameter in
  1752. section~\ref{sec:interp-Lvar}.)
  1753. \begin{center}
  1754. {\if\edition\racketEd
  1755. \begin{minipage}{0.45\textwidth}
  1756. \begin{lstlisting}
  1757. (define ((interp_Lint env) e)
  1758. (match e
  1759. [(Prim '- (list e1))
  1760. (fx- 0 ((interp_Lint env) e1))]
  1761. ...))
  1762. \end{lstlisting}
  1763. \end{minipage}
  1764. \begin{minipage}{0.45\textwidth}
  1765. \begin{lstlisting}
  1766. (define ((interp_Lvar env) e)
  1767. (match e
  1768. [(Var x)
  1769. (dict-ref env x)]
  1770. [(Let x e body)
  1771. (define v ((interp_exp env) e))
  1772. (define env^ (dict-set env x v))
  1773. ((interp_exp env^) body)]
  1774. [else ((interp_Lint env) e)]))
  1775. \end{lstlisting}
  1776. \end{minipage}
  1777. \fi}
  1778. {\if\edition\pythonEd
  1779. \begin{minipage}{0.45\textwidth}
  1780. \begin{lstlisting}
  1781. def interp_Lint(e, env):
  1782. match e:
  1783. case UnaryOp(USub(), e1):
  1784. return - interp_Lint(e1, env)
  1785. ...
  1786. \end{lstlisting}
  1787. \end{minipage}
  1788. \begin{minipage}{0.45\textwidth}
  1789. \begin{lstlisting}
  1790. def interp_Lvar(e, env):
  1791. match e:
  1792. case Name(id):
  1793. return env[id]
  1794. case _:
  1795. return interp_Lint(e, env)
  1796. \end{lstlisting}
  1797. \end{minipage}
  1798. \fi}
  1799. \end{center}
  1800. The problem with this naive approach is that it does not handle
  1801. situations in which an \LangVar{} feature, such as a variable, is
  1802. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1803. in the following program.
  1804. {\if\edition\racketEd
  1805. \begin{lstlisting}
  1806. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1807. \end{lstlisting}
  1808. \fi}
  1809. {\if\edition\pythonEd
  1810. \begin{minipage}{0.96\textwidth}
  1811. \begin{lstlisting}
  1812. y = 10
  1813. print(-y)
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \fi}
  1817. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1818. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1819. then it recursively calls \code{interp\_Lint} again on its argument.
  1820. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1821. an error!
  1822. To make our interpreters extensible we need something called
  1823. \emph{open recursion}\index{subject}{open recursion}, in which the
  1824. tying of the recursive knot is delayed until the functions are
  1825. composed. Object-oriented languages provide open recursion via method
  1826. overriding\index{subject}{method overriding}. The following code uses
  1827. method overriding to interpret \LangInt{} and \LangVar{} using
  1828. %
  1829. \racket{the
  1830. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1831. \index{subject}{class} feature of Racket.}
  1832. %
  1833. \python{a Python \code{class} definition.}
  1834. %
  1835. We define one class for each language and define a method for
  1836. interpreting expressions inside each class. The class for \LangVar{}
  1837. inherits from the class for \LangInt{}, and the method
  1838. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1839. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1840. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1841. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1842. \code{interp\_exp} in \LangInt{}.
  1843. \begin{center}
  1844. \hspace{-20pt}
  1845. {\if\edition\racketEd
  1846. \begin{minipage}{0.45\textwidth}
  1847. \begin{lstlisting}
  1848. (define interp-Lint-class
  1849. (class object%
  1850. (define/public ((interp_exp env) e)
  1851. (match e
  1852. [(Prim '- (list e))
  1853. (fx- 0 ((interp_exp env) e))]
  1854. ...))
  1855. ...))
  1856. \end{lstlisting}
  1857. \end{minipage}
  1858. \begin{minipage}{0.45\textwidth}
  1859. \begin{lstlisting}
  1860. (define interp-Lvar-class
  1861. (class interp-Lint-class
  1862. (define/override ((interp_exp env) e)
  1863. (match e
  1864. [(Var x)
  1865. (dict-ref env x)]
  1866. [(Let x e body)
  1867. (define v ((interp_exp env) e))
  1868. (define env^ (dict-set env x v))
  1869. ((interp_exp env^) body)]
  1870. [else
  1871. (super (interp_exp env) e)]))
  1872. ...
  1873. ))
  1874. \end{lstlisting}
  1875. \end{minipage}
  1876. \fi}
  1877. {\if\edition\pythonEd
  1878. \begin{minipage}{0.45\textwidth}
  1879. \begin{lstlisting}
  1880. class InterpLint:
  1881. def interp_exp(e):
  1882. match e:
  1883. case UnaryOp(USub(), e1):
  1884. return -self.interp_exp(e1)
  1885. ...
  1886. ...
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. \begin{minipage}{0.45\textwidth}
  1890. \begin{lstlisting}
  1891. def InterpLvar(InterpLint):
  1892. def interp_exp(e):
  1893. match e:
  1894. case Name(id):
  1895. return env[id]
  1896. case _:
  1897. return super().interp_exp(e)
  1898. ...
  1899. \end{lstlisting}
  1900. \end{minipage}
  1901. \fi}
  1902. \end{center}
  1903. Getting back to the troublesome example, repeated here
  1904. {\if\edition\racketEd
  1905. \begin{lstlisting}
  1906. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1907. \end{lstlisting}
  1908. \fi}
  1909. {\if\edition\pythonEd
  1910. \begin{lstlisting}
  1911. y = 10
  1912. print(-y)
  1913. \end{lstlisting}
  1914. \fi}
  1915. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1916. \racket{on this expression,}
  1917. \python{on the \code{-y} expression,}
  1918. %
  1919. which we call \code{e0}, by creating an object of the \LangVar{} class
  1920. and calling the \code{interp\_exp} method
  1921. {\if\edition\racketEd
  1922. \begin{lstlisting}
  1923. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1924. \end{lstlisting}
  1925. \fi}
  1926. {\if\edition\pythonEd
  1927. \begin{lstlisting}
  1928. InterpLvar().interp_exp(e0)
  1929. \end{lstlisting}
  1930. \fi}
  1931. \noindent To process the \code{-} operator, the default case of
  1932. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1933. method in \LangInt{}. But then for the recursive method call, it
  1934. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1935. \code{Var} node is handled correctly. Thus, method overriding gives us
  1936. the open recursion that we need to implement our interpreters in an
  1937. extensible way.
  1938. \subsection{Definitional Interpreter for \LangVar{}}
  1939. \label{sec:interp-Lvar}
  1940. Having justified the use of classes and methods to implement
  1941. interpreters, we revisit the definitional interpreter for \LangInt{}
  1942. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1943. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1944. The interpreter for \LangVar{} adds two new \key{match} cases for
  1945. variables and \racket{\key{let}}\python{assignment}. For
  1946. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1947. value bound to a variable to all the uses of the variable. To
  1948. accomplish this, we maintain a mapping from variables to values called
  1949. an \emph{environment}\index{subject}{environment}.
  1950. %
  1951. We use
  1952. %
  1953. \racket{an association list (alist) }%
  1954. %
  1955. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1956. %
  1957. to represent the environment.
  1958. %
  1959. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1960. and the \code{racket/dict} package.}
  1961. %
  1962. The \code{interp\_exp} function takes the current environment,
  1963. \code{env}, as an extra parameter. When the interpreter encounters a
  1964. variable, it looks up the corresponding value in the dictionary.
  1965. %
  1966. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1967. initializing expression, extends the environment with the result
  1968. value bound to the variable, using \code{dict-set}, then evaluates
  1969. the body of the \key{Let}.}
  1970. %
  1971. \python{When the interpreter encounters an assignment, it evaluates
  1972. the initializing expression and then associates the resulting value
  1973. with the variable in the environment.}
  1974. \begin{figure}[tp]
  1975. \begin{tcolorbox}[colback=white]
  1976. {\if\edition\racketEd
  1977. \begin{lstlisting}
  1978. (define interp-Lint-class
  1979. (class object%
  1980. (super-new)
  1981. (define/public ((interp_exp env) e)
  1982. (match e
  1983. [(Int n) n]
  1984. [(Prim 'read '())
  1985. (define r (read))
  1986. (cond [(fixnum? r) r]
  1987. [else (error 'interp_exp "expected an integer" r)])]
  1988. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1989. [(Prim '+ (list e1 e2))
  1990. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1991. [(Prim '- (list e1 e2))
  1992. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1993. (define/public (interp_program p)
  1994. (match p
  1995. [(Program '() e) ((interp_exp '()) e)]))
  1996. ))
  1997. \end{lstlisting}
  1998. \fi}
  1999. {\if\edition\pythonEd
  2000. \begin{lstlisting}
  2001. class InterpLint:
  2002. def interp_exp(self, e, env):
  2003. match e:
  2004. case BinOp(left, Add(), right):
  2005. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2006. case BinOp(left, Sub(), right):
  2007. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2008. case UnaryOp(USub(), v):
  2009. return - self.interp_exp(v, env)
  2010. case Constant(value):
  2011. return value
  2012. case Call(Name('input_int'), []):
  2013. return int(input())
  2014. def interp_stmts(self, ss, env):
  2015. if len(ss) == 0:
  2016. return
  2017. match ss[0]:
  2018. case Expr(Call(Name('print'), [arg])):
  2019. print(self.interp_exp(arg, env), end='')
  2020. return self.interp_stmts(ss[1:], env)
  2021. case Expr(value):
  2022. self.interp_exp(value, env)
  2023. return self.interp_stmts(ss[1:], env)
  2024. def interp(self, p):
  2025. match p:
  2026. case Module(body):
  2027. self.interp_stmts(body, {})
  2028. def interp_Lint(p):
  2029. return InterpLint().interp(p)
  2030. \end{lstlisting}
  2031. \fi}
  2032. \end{tcolorbox}
  2033. \caption{Interpreter for \LangInt{} as a class.}
  2034. \label{fig:interp-Lint-class}
  2035. \end{figure}
  2036. \begin{figure}[tp]
  2037. \begin{tcolorbox}[colback=white]
  2038. {\if\edition\racketEd
  2039. \begin{lstlisting}
  2040. (define interp-Lvar-class
  2041. (class interp-Lint-class
  2042. (super-new)
  2043. (define/override ((interp_exp env) e)
  2044. (match e
  2045. [(Var x) (dict-ref env x)]
  2046. [(Let x e body)
  2047. (define new-env (dict-set env x ((interp_exp env) e)))
  2048. ((interp_exp new-env) body)]
  2049. [else ((super interp-exp env) e)]))
  2050. ))
  2051. (define (interp_Lvar p)
  2052. (send (new interp-Lvar-class) interp_program p))
  2053. \end{lstlisting}
  2054. \fi}
  2055. {\if\edition\pythonEd
  2056. \begin{lstlisting}
  2057. class InterpLvar(InterpLint):
  2058. def interp_exp(self, e, env):
  2059. match e:
  2060. case Name(id):
  2061. return env[id]
  2062. case _:
  2063. return super().interp_exp(e, env)
  2064. def interp_stmts(self, ss, env):
  2065. if len(ss) == 0:
  2066. return
  2067. match ss[0]:
  2068. case Assign([lhs], value):
  2069. env[lhs.id] = self.interp_exp(value, env)
  2070. return self.interp_stmts(ss[1:], env)
  2071. case _:
  2072. return super().interp_stmts(ss, env)
  2073. def interp_Lvar(p):
  2074. return InterpLvar().interp(p)
  2075. \end{lstlisting}
  2076. \fi}
  2077. \end{tcolorbox}
  2078. \caption{Interpreter for the \LangVar{} language.}
  2079. \label{fig:interp-Lvar}
  2080. \end{figure}
  2081. {\if\edition\racketEd
  2082. \begin{figure}[tp]
  2083. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2084. \small
  2085. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2086. An \emph{association list} (called an alist) is a list of key-value pairs.
  2087. For example, we can map people to their ages with an alist
  2088. \index{subject}{alist}\index{subject}{association list}
  2089. \begin{lstlisting}[basicstyle=\ttfamily]
  2090. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2091. \end{lstlisting}
  2092. The \emph{dictionary} interface is for mapping keys to values.
  2093. Every alist implements this interface. \index{subject}{dictionary}
  2094. The package
  2095. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2096. provides many functions for working with dictionaries, such as
  2097. \begin{description}
  2098. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2099. returns the value associated with the given $\itm{key}$.
  2100. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2101. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2102. and otherwise is the same as $\itm{dict}$.
  2103. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2104. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2105. of keys and values in $\itm{dict}$. For example, the following
  2106. creates a new alist in which the ages are incremented:
  2107. \end{description}
  2108. \vspace{-10pt}
  2109. \begin{lstlisting}[basicstyle=\ttfamily]
  2110. (for/list ([(k v) (in-dict ages)])
  2111. (cons k (add1 v)))
  2112. \end{lstlisting}
  2113. \end{tcolorbox}
  2114. %\end{wrapfigure}
  2115. \caption{Association lists implement the dictionary interface.}
  2116. \label{fig:alist}
  2117. \end{figure}
  2118. \fi}
  2119. The goal for this chapter is to implement a compiler that translates
  2120. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2121. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2122. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2123. That is, they output the same integer $n$. We depict this correctness
  2124. criteria in the following diagram:
  2125. \[
  2126. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2127. \node (p1) at (0, 0) {$P_1$};
  2128. \node (p2) at (4, 0) {$P_2$};
  2129. \node (o) at (4, -2) {$n$};
  2130. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2131. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2132. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2133. \end{tikzpicture}
  2134. \]
  2135. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2136. compiling \LangVar{}.
  2137. \section{The \LangXInt{} Assembly Language}
  2138. \label{sec:x86}
  2139. \index{subject}{x86}
  2140. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2141. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2142. assembler.
  2143. %
  2144. A program begins with a \code{main} label followed by a sequence of
  2145. instructions. The \key{globl} directive makes the \key{main} procedure
  2146. externally visible so that the operating system can call it.
  2147. %
  2148. An x86 program is stored in the computer's memory. For our purposes,
  2149. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2150. values. The computer has a \emph{program counter}
  2151. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2152. \code{rip} register that points to the address of the next instruction
  2153. to be executed. For most instructions, the program counter is
  2154. incremented after the instruction is executed so that it points to the
  2155. next instruction in memory. Most x86 instructions take two operands,
  2156. each of which is an integer constant (called an \emph{immediate
  2157. value}\index{subject}{immediate value}), a
  2158. \emph{register}\index{subject}{register}, or a memory location.
  2159. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2160. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2161. && \key{r8} \MID \key{r9} \MID \key{r10}
  2162. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2163. \MID \key{r14} \MID \key{r15}}
  2164. \newcommand{\GrammarXInt}{
  2165. \begin{array}{rcl}
  2166. \Reg &::=& \allregisters{} \\
  2167. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2168. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2169. \key{subq} \; \Arg\key{,} \Arg \MID
  2170. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2171. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2172. \key{callq} \; \mathit{label} \MID
  2173. \key{retq} \MID
  2174. \key{jmp}\,\itm{label} \MID \\
  2175. && \itm{label}\key{:}\; \Instr
  2176. \end{array}
  2177. }
  2178. \begin{figure}[tp]
  2179. \begin{tcolorbox}[colback=white]
  2180. {\if\edition\racketEd
  2181. \[
  2182. \begin{array}{l}
  2183. \GrammarXInt \\
  2184. \begin{array}{lcl}
  2185. \LangXIntM{} &::= & \key{.globl main}\\
  2186. & & \key{main:} \; \Instr\ldots
  2187. \end{array}
  2188. \end{array}
  2189. \]
  2190. \fi}
  2191. {\if\edition\pythonEd
  2192. \[
  2193. \begin{array}{lcl}
  2194. \Reg &::=& \allregisters{} \\
  2195. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2196. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2197. \key{subq} \; \Arg\key{,} \Arg \MID
  2198. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2199. && \key{callq} \; \mathit{label} \MID
  2200. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2201. \LangXIntM{} &::= & \key{.globl main}\\
  2202. & & \key{main:} \; \Instr^{*}
  2203. \end{array}
  2204. \]
  2205. \fi}
  2206. \end{tcolorbox}
  2207. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2208. \label{fig:x86-int-concrete}
  2209. \end{figure}
  2210. A register is a special kind of variable that holds a 64-bit
  2211. value. There are 16 general-purpose registers in the computer; their
  2212. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2213. written with a percent sign, \key{\%}, followed by the register name,
  2214. for example \key{\%rax}.
  2215. An immediate value is written using the notation \key{\$}$n$ where $n$
  2216. is an integer.
  2217. %
  2218. %
  2219. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2220. which obtains the address stored in register $r$ and then adds $n$
  2221. bytes to the address. The resulting address is used to load or to store
  2222. to memory depending on whether it occurs as a source or destination
  2223. argument of an instruction.
  2224. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2225. the source $s$ and destination $d$, applies the arithmetic operation,
  2226. and then writes the result to the destination $d$. \index{subject}{instruction}
  2227. %
  2228. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2229. stores the result in $d$.
  2230. %
  2231. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2232. specified by the label, and $\key{retq}$ returns from a procedure to
  2233. its caller.
  2234. %
  2235. We discuss procedure calls in more detail further in this chapter and
  2236. in chapter~\ref{ch:Lfun}.
  2237. %
  2238. The last letter \key{q} indicates that these instructions operate on
  2239. quadwords which are 64-bit values.
  2240. %
  2241. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2242. counter to the address of the instruction immediately after the
  2243. specified label.}
  2244. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2245. all the x86 instructions used in this book.
  2246. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2247. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2248. \lstinline{movq $10, %rax}
  2249. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2250. adds $32$ to the $10$ in \key{rax} and
  2251. puts the result, $42$, into \key{rax}.
  2252. %
  2253. The last instruction \key{retq} finishes the \key{main} function by
  2254. returning the integer in \key{rax} to the operating system. The
  2255. operating system interprets this integer as the program's exit
  2256. code. By convention, an exit code of 0 indicates that a program has
  2257. completed successfully, and all other exit codes indicate various
  2258. errors.
  2259. %
  2260. \racket{However, in this book we return the result of the program
  2261. as the exit code.}
  2262. \begin{figure}[tbp]
  2263. \begin{minipage}{0.45\textwidth}
  2264. \begin{tcolorbox}[colback=white]
  2265. \begin{lstlisting}
  2266. .globl main
  2267. main:
  2268. movq $10, %rax
  2269. addq $32, %rax
  2270. retq
  2271. \end{lstlisting}
  2272. \end{tcolorbox}
  2273. \end{minipage}
  2274. \caption{An x86 program that computes
  2275. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2276. \label{fig:p0-x86}
  2277. \end{figure}
  2278. We exhibit the use of memory for storing intermediate results in the
  2279. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2280. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2281. uses a region of memory called the \emph{procedure call stack}
  2282. (\emph{stack} for
  2283. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2284. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2285. for each procedure call. The memory layout for an individual frame is
  2286. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2287. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2288. address of the item at the top of the stack. In general, we use the
  2289. term \emph{pointer}\index{subject}{pointer} for something that
  2290. contains an address. The stack grows downward in memory, so we
  2291. increase the size of the stack by subtracting from the stack pointer.
  2292. In the context of a procedure call, the \emph{return
  2293. address}\index{subject}{return address} is the location of the
  2294. instruction that immediately follows the call instruction on the
  2295. caller side. The function call instruction, \code{callq}, pushes the
  2296. return address onto the stack prior to jumping to the procedure. The
  2297. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2298. pointer} and is used to access variables that are stored in the
  2299. frame of the current procedure call. The base pointer of the caller
  2300. is stored immediately after the return address.
  2301. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2302. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2303. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2304. $-16\key{(\%rbp)}$, and so on.
  2305. \begin{figure}[tbp]
  2306. \begin{minipage}{0.66\textwidth}
  2307. \begin{tcolorbox}[colback=white]
  2308. {\if\edition\racketEd
  2309. \begin{lstlisting}
  2310. start:
  2311. movq $10, -8(%rbp)
  2312. negq -8(%rbp)
  2313. movq -8(%rbp), %rax
  2314. addq $52, %rax
  2315. jmp conclusion
  2316. .globl main
  2317. main:
  2318. pushq %rbp
  2319. movq %rsp, %rbp
  2320. subq $16, %rsp
  2321. jmp start
  2322. conclusion:
  2323. addq $16, %rsp
  2324. popq %rbp
  2325. retq
  2326. \end{lstlisting}
  2327. \fi}
  2328. {\if\edition\pythonEd
  2329. \begin{lstlisting}
  2330. .globl main
  2331. main:
  2332. pushq %rbp
  2333. movq %rsp, %rbp
  2334. subq $16, %rsp
  2335. movq $10, -8(%rbp)
  2336. negq -8(%rbp)
  2337. movq -8(%rbp), %rax
  2338. addq $52, %rax
  2339. addq $16, %rsp
  2340. popq %rbp
  2341. retq
  2342. \end{lstlisting}
  2343. \fi}
  2344. \end{tcolorbox}
  2345. \end{minipage}
  2346. \caption{An x86 program that computes
  2347. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2348. \label{fig:p1-x86}
  2349. \end{figure}
  2350. \begin{figure}[tbp]
  2351. \begin{minipage}{0.66\textwidth}
  2352. \begin{tcolorbox}[colback=white]
  2353. \centering
  2354. \begin{tabular}{|r|l|} \hline
  2355. Position & Contents \\ \hline
  2356. $8$(\key{\%rbp}) & return address \\
  2357. $0$(\key{\%rbp}) & old \key{rbp} \\
  2358. $-8$(\key{\%rbp}) & variable $1$ \\
  2359. $-16$(\key{\%rbp}) & variable $2$ \\
  2360. \ldots & \ldots \\
  2361. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2362. \end{tabular}
  2363. \end{tcolorbox}
  2364. \end{minipage}
  2365. \caption{Memory layout of a frame.}
  2366. \label{fig:frame}
  2367. \end{figure}
  2368. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2369. is transferred from the operating system to the \code{main} function.
  2370. The operating system issues a \code{callq main} instruction that
  2371. pushes its return address on the stack and then jumps to
  2372. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2373. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2374. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2375. out of alignment (because the \code{callq} pushed the return address).
  2376. The first three instructions are the typical
  2377. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2378. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2379. pointer \code{rsp} and then saves the base pointer of the caller at
  2380. address \code{rsp} on the stack. The next instruction \code{movq
  2381. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2382. which is pointing to the location of the old base pointer. The
  2383. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2384. make enough room for storing variables. This program needs one
  2385. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2386. 16-byte-aligned, and then we are ready to make calls to other functions.
  2387. \racket{The last instruction of the prelude is \code{jmp start}, which
  2388. transfers control to the instructions that were generated from the
  2389. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2390. \racket{The first instruction under the \code{start} label is}
  2391. %
  2392. \python{The first instruction after the prelude is}
  2393. %
  2394. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2395. %
  2396. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2397. $1$ to $-10$.
  2398. %
  2399. The next instruction moves the $-10$ from variable $1$ into the
  2400. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2401. the value in \code{rax}, updating its contents to $42$.
  2402. \racket{The three instructions under the label \code{conclusion} are the
  2403. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2404. %
  2405. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2406. \code{main} function consists of the last three instructions.}
  2407. %
  2408. The first two restore the \code{rsp} and \code{rbp} registers to their
  2409. states at the beginning of the procedure. In particular,
  2410. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2411. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2412. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2413. \key{retq}, jumps back to the procedure that called this one and adds
  2414. $8$ to the stack pointer.
  2415. Our compiler needs a convenient representation for manipulating x86
  2416. programs, so we define an abstract syntax for x86, shown in
  2417. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2418. \LangXInt{}.
  2419. %
  2420. {\if\edition\pythonEd%
  2421. The main difference between this and the concrete syntax of \LangXInt{}
  2422. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2423. names, and register names are explicitly represented by strings.
  2424. \fi} %
  2425. {\if\edition\racketEd
  2426. The main difference between this and the concrete syntax of \LangXInt{}
  2427. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2428. front of every instruction. Instead instructions are grouped into
  2429. \emph{basic blocks}\index{subject}{basic block} with a
  2430. label associated with every basic block; this is why the \key{X86Program}
  2431. struct includes an alist mapping labels to basic blocks. The reason for this
  2432. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2433. introduce conditional branching. The \code{Block} structure includes
  2434. an $\itm{info}$ field that is not needed in this chapter but becomes
  2435. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2436. $\itm{info}$ field should contain an empty list.
  2437. \fi}
  2438. %
  2439. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2440. node includes an integer for representing the arity of the function,
  2441. that is, the number of arguments, which is helpful to know during
  2442. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2443. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2444. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2445. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2446. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2447. \MID \skey{r14} \MID \skey{r15}}
  2448. \newcommand{\ASTXIntRacket}{
  2449. \begin{array}{lcl}
  2450. \Reg &::=& \allregisters{} \\
  2451. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2452. \MID \DEREF{\Reg}{\Int} \\
  2453. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2454. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2455. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2456. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2457. &\MID& \PUSHQ{\Arg}
  2458. \MID \POPQ{\Arg} \\
  2459. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2460. \MID \RETQ{}
  2461. \MID \JMP{\itm{label}} \\
  2462. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2463. \end{array}
  2464. }
  2465. \begin{figure}[tp]
  2466. \begin{tcolorbox}[colback=white]
  2467. \small
  2468. {\if\edition\racketEd
  2469. \[\arraycolsep=3pt
  2470. \begin{array}{l}
  2471. \ASTXIntRacket \\
  2472. \begin{array}{lcl}
  2473. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2474. \end{array}
  2475. \end{array}
  2476. \]
  2477. \fi}
  2478. {\if\edition\pythonEd
  2479. \[
  2480. \begin{array}{lcl}
  2481. \Reg &::=& \allastregisters{} \\
  2482. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2483. \MID \DEREF{\Reg}{\Int} \\
  2484. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2485. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2486. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2487. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2488. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2489. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2490. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2491. \end{array}
  2492. \]
  2493. \fi}
  2494. \end{tcolorbox}
  2495. \caption{The abstract syntax of \LangXInt{} assembly.}
  2496. \label{fig:x86-int-ast}
  2497. \end{figure}
  2498. \section{Planning the Trip to x86}
  2499. \label{sec:plan-s0-x86}
  2500. To compile one language to another, it helps to focus on the
  2501. differences between the two languages because the compiler will need
  2502. to bridge those differences. What are the differences between \LangVar{}
  2503. and x86 assembly? Here are some of the most important ones:
  2504. \begin{enumerate}
  2505. \item x86 arithmetic instructions typically have two arguments and
  2506. update the second argument in place. In contrast, \LangVar{}
  2507. arithmetic operations take two arguments and produce a new value.
  2508. An x86 instruction may have at most one memory-accessing argument.
  2509. Furthermore, some x86 instructions place special restrictions on
  2510. their arguments.
  2511. \item An argument of an \LangVar{} operator can be a deeply nested
  2512. expression, whereas x86 instructions restrict their arguments to be
  2513. integer constants, registers, and memory locations.
  2514. {\if\edition\racketEd
  2515. \item The order of execution in x86 is explicit in the syntax, which
  2516. is a sequence of instructions and jumps to labeled positions,
  2517. whereas in \LangVar{} the order of evaluation is a left-to-right
  2518. depth-first traversal of the abstract syntax tree. \fi}
  2519. \item A program in \LangVar{} can have any number of variables,
  2520. whereas x86 has 16 registers and the procedure call stack.
  2521. {\if\edition\racketEd
  2522. \item Variables in \LangVar{} can shadow other variables with the
  2523. same name. In x86, registers have unique names, and memory locations
  2524. have unique addresses.
  2525. \fi}
  2526. \end{enumerate}
  2527. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2528. down the problem into several steps, which deal with these differences
  2529. one at a time. Each of these steps is called a \emph{pass} of the
  2530. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2531. %
  2532. This term indicates that each step passes over, or traverses, the AST
  2533. of the program.
  2534. %
  2535. Furthermore, we follow the nanopass approach, which means that we
  2536. strive for each pass to accomplish one clear objective rather than two
  2537. or three at the same time.
  2538. %
  2539. We begin by sketching how we might implement each pass and give each
  2540. pass a name. We then figure out an ordering of the passes and the
  2541. input/output language for each pass. The very first pass has
  2542. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2543. its output language. In between these two passes, we can choose
  2544. whichever language is most convenient for expressing the output of
  2545. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2546. \emph{intermediate languages} of our own design. Finally, to
  2547. implement each pass we write one recursive function per nonterminal in
  2548. the grammar of the input language of the pass.
  2549. \index{subject}{intermediate language}
  2550. Our compiler for \LangVar{} consists of the following passes:
  2551. %
  2552. \begin{description}
  2553. {\if\edition\racketEd
  2554. \item[\key{uniquify}] deals with the shadowing of variables by
  2555. renaming every variable to a unique name.
  2556. \fi}
  2557. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2558. of a primitive operation or function call is a variable or integer,
  2559. that is, an \emph{atomic} expression. We refer to nonatomic
  2560. expressions as \emph{complex}. This pass introduces temporary
  2561. variables to hold the results of complex
  2562. subexpressions.\index{subject}{atomic
  2563. expression}\index{subject}{complex expression}%
  2564. {\if\edition\racketEd
  2565. \item[\key{explicate\_control}] makes the execution order of the
  2566. program explicit. It converts the abstract syntax tree
  2567. representation into a graph in which each node is a labeled sequence
  2568. of statements and the edges are \code{goto} statements.
  2569. \fi}
  2570. \item[\key{select\_instructions}] handles the difference between
  2571. \LangVar{} operations and x86 instructions. This pass converts each
  2572. \LangVar{} operation to a short sequence of instructions that
  2573. accomplishes the same task.
  2574. \item[\key{assign\_homes}] replaces variables with registers or stack
  2575. locations.
  2576. \end{description}
  2577. %
  2578. {\if\edition\racketEd
  2579. %
  2580. Our treatment of \code{remove\_complex\_operands} and
  2581. \code{explicate\_control} as separate passes is an example of the
  2582. nanopass approach\footnote{For analogous decompositions of the
  2583. translation into continuation passing style, see the work of
  2584. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2585. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2586. %
  2587. \fi}
  2588. The next question is, in what order should we apply these passes? This
  2589. question can be challenging because it is difficult to know ahead of
  2590. time which orderings will be better (that is, will be easier to
  2591. implement, produce more efficient code, and so on), and therefore
  2592. ordering often involves trial and error. Nevertheless, we can plan
  2593. ahead and make educated choices regarding the ordering.
  2594. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2595. \key{uniquify}? The \key{uniquify} pass should come first because
  2596. \key{explicate\_control} changes all the \key{let}-bound variables to
  2597. become local variables whose scope is the entire program, which would
  2598. confuse variables with the same name.}
  2599. %
  2600. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2601. because the later removes the \key{let} form, but it is convenient to
  2602. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2603. %
  2604. \racket{The ordering of \key{uniquify} with respect to
  2605. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2606. \key{uniquify} to come first.}
  2607. The \key{select\_instructions} and \key{assign\_homes} passes are
  2608. intertwined.
  2609. %
  2610. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2611. passing arguments to functions and that it is preferable to assign
  2612. parameters to their corresponding registers. This suggests that it
  2613. would be better to start with the \key{select\_instructions} pass,
  2614. which generates the instructions for argument passing, before
  2615. performing register allocation.
  2616. %
  2617. On the other hand, by selecting instructions first we may run into a
  2618. dead end in \key{assign\_homes}. Recall that only one argument of an
  2619. x86 instruction may be a memory access, but \key{assign\_homes} might
  2620. be forced to assign both arguments to memory locations.
  2621. %
  2622. A sophisticated approach is to repeat the two passes until a solution
  2623. is found. However, to reduce implementation complexity we recommend
  2624. placing \key{select\_instructions} first, followed by the
  2625. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2626. that uses a reserved register to fix outstanding problems.
  2627. \begin{figure}[tbp]
  2628. \begin{tcolorbox}[colback=white]
  2629. {\if\edition\racketEd
  2630. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2631. \node (Lvar) at (0,2) {\large \LangVar{}};
  2632. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2633. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2634. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2635. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2636. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2637. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2638. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2639. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2640. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2641. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2642. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2643. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2644. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2645. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2646. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2647. \end{tikzpicture}
  2648. \fi}
  2649. {\if\edition\pythonEd
  2650. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2651. \node (Lvar) at (0,2) {\large \LangVar{}};
  2652. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2653. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2654. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2655. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2656. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2657. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2658. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2659. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2660. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2661. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2662. \end{tikzpicture}
  2663. \fi}
  2664. \end{tcolorbox}
  2665. \caption{Diagram of the passes for compiling \LangVar{}. }
  2666. \label{fig:Lvar-passes}
  2667. \end{figure}
  2668. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2669. passes and identifies the input and output language of each pass.
  2670. %
  2671. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2672. language, which extends \LangXInt{} with an unbounded number of
  2673. program-scope variables and removes the restrictions regarding
  2674. instruction arguments.
  2675. %
  2676. The last pass, \key{prelude\_and\_conclusion}, places the program
  2677. instructions inside a \code{main} function with instructions for the
  2678. prelude and conclusion.
  2679. %
  2680. \racket{In the next section we discuss the \LangCVar{} intermediate
  2681. language that serves as the output of \code{explicate\_control}.}
  2682. %
  2683. The remainder of this chapter provides guidance on the implementation
  2684. of each of the compiler passes represented in
  2685. figure~\ref{fig:Lvar-passes}.
  2686. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2687. %% are programs that are still in the \LangVar{} language, though the
  2688. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2689. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2690. %% %
  2691. %% The output of \code{explicate\_control} is in an intermediate language
  2692. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2693. %% syntax, which we introduce in the next section. The
  2694. %% \key{select-instruction} pass translates from \LangCVar{} to
  2695. %% \LangXVar{}. The \key{assign-homes} and
  2696. %% \key{patch-instructions}
  2697. %% passes input and output variants of x86 assembly.
  2698. \newcommand{\CvarGrammarRacket}{
  2699. \begin{array}{lcl}
  2700. \Atm &::=& \Int \MID \Var \\
  2701. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2702. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2703. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2704. \end{array}
  2705. }
  2706. \newcommand{\CvarASTRacket}{
  2707. \begin{array}{lcl}
  2708. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2709. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2710. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2711. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2712. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2713. \end{array}
  2714. }
  2715. {\if\edition\racketEd
  2716. \subsection{The \LangCVar{} Intermediate Language}
  2717. The output of \code{explicate\_control} is similar to the C
  2718. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2719. categories for expressions and statements, so we name it \LangCVar{}.
  2720. This style of intermediate language is also known as
  2721. \emph{three-address code}, to emphasize that the typical form of a
  2722. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2723. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2724. The concrete syntax for \LangCVar{} is shown in
  2725. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2726. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2727. %
  2728. The \LangCVar{} language supports the same operators as \LangVar{} but
  2729. the arguments of operators are restricted to atomic
  2730. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2731. assignment statements that can be executed in sequence using the
  2732. \key{Seq} form. A sequence of statements always ends with
  2733. \key{Return}, a guarantee that is baked into the grammar rules for
  2734. \itm{tail}. The naming of this nonterminal comes from the term
  2735. \emph{tail position}\index{subject}{tail position}, which refers to an
  2736. expression that is the last one to execute within a function or
  2737. program.
  2738. A \LangCVar{} program consists of an alist mapping labels to
  2739. tails. This is more general than necessary for the present chapter, as
  2740. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2741. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2742. there is just one label, \key{start}, and the whole program is
  2743. its tail.
  2744. %
  2745. The $\itm{info}$ field of the \key{CProgram} form, after the
  2746. \code{explicate\_control} pass, contains an alist that associates the
  2747. symbol \key{locals} with a list of all the variables used in the
  2748. program. At the start of the program, these variables are
  2749. uninitialized; they become initialized on their first assignment.
  2750. \begin{figure}[tbp]
  2751. \begin{tcolorbox}[colback=white]
  2752. \[
  2753. \begin{array}{l}
  2754. \CvarGrammarRacket \\
  2755. \begin{array}{lcl}
  2756. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2757. \end{array}
  2758. \end{array}
  2759. \]
  2760. \end{tcolorbox}
  2761. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2762. \label{fig:c0-concrete-syntax}
  2763. \end{figure}
  2764. \begin{figure}[tbp]
  2765. \begin{tcolorbox}[colback=white]
  2766. \[
  2767. \begin{array}{l}
  2768. \CvarASTRacket \\
  2769. \begin{array}{lcl}
  2770. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2771. \end{array}
  2772. \end{array}
  2773. \]
  2774. \end{tcolorbox}
  2775. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2776. \label{fig:c0-syntax}
  2777. \end{figure}
  2778. The definitional interpreter for \LangCVar{} is in the support code,
  2779. in the file \code{interp-Cvar.rkt}.
  2780. \fi}
  2781. {\if\edition\racketEd
  2782. \section{Uniquify Variables}
  2783. \label{sec:uniquify-Lvar}
  2784. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2785. programs in which every \key{let} binds a unique variable name. For
  2786. example, the \code{uniquify} pass should translate the program on the
  2787. left into the program on the right.
  2788. \begin{transformation}
  2789. \begin{lstlisting}
  2790. (let ([x 32])
  2791. (+ (let ([x 10]) x) x))
  2792. \end{lstlisting}
  2793. \compilesto
  2794. \begin{lstlisting}
  2795. (let ([x.1 32])
  2796. (+ (let ([x.2 10]) x.2) x.1))
  2797. \end{lstlisting}
  2798. \end{transformation}
  2799. The following is another example translation, this time of a program
  2800. with a \key{let} nested inside the initializing expression of another
  2801. \key{let}.
  2802. \begin{transformation}
  2803. \begin{lstlisting}
  2804. (let ([x (let ([x 4])
  2805. (+ x 1))])
  2806. (+ x 2))
  2807. \end{lstlisting}
  2808. \compilesto
  2809. \begin{lstlisting}
  2810. (let ([x.2 (let ([x.1 4])
  2811. (+ x.1 1))])
  2812. (+ x.2 2))
  2813. \end{lstlisting}
  2814. \end{transformation}
  2815. We recommend implementing \code{uniquify} by creating a structurally
  2816. recursive function named \code{uniquify\_exp} that does little other
  2817. than copy an expression. However, when encountering a \key{let}, it
  2818. should generate a unique name for the variable and associate the old
  2819. name with the new name in an alist.\footnote{The Racket function
  2820. \code{gensym} is handy for generating unique variable names.} The
  2821. \code{uniquify\_exp} function needs to access this alist when it gets
  2822. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2823. for the alist.
  2824. The skeleton of the \code{uniquify\_exp} function is shown in
  2825. figure~\ref{fig:uniquify-Lvar}.
  2826. %% The function is curried so that it is
  2827. %% convenient to partially apply it to an alist and then apply it to
  2828. %% different expressions, as in the last case for primitive operations in
  2829. %% figure~\ref{fig:uniquify-Lvar}.
  2830. The
  2831. %
  2832. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2833. %
  2834. form of Racket is useful for transforming the element of a list to
  2835. produce a new list.\index{subject}{for/list}
  2836. \begin{figure}[tbp]
  2837. \begin{tcolorbox}[colback=white]
  2838. \begin{lstlisting}
  2839. (define (uniquify_exp env)
  2840. (lambda (e)
  2841. (match e
  2842. [(Var x) ___]
  2843. [(Int n) (Int n)]
  2844. [(Let x e body) ___]
  2845. [(Prim op es)
  2846. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2847. (define (uniquify p)
  2848. (match p
  2849. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2850. \end{lstlisting}
  2851. \end{tcolorbox}
  2852. \caption{Skeleton for the \key{uniquify} pass.}
  2853. \label{fig:uniquify-Lvar}
  2854. \end{figure}
  2855. \begin{exercise}
  2856. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2857. Complete the \code{uniquify} pass by filling in the blanks in
  2858. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2859. variables and for the \key{let} form in the file \code{compiler.rkt}
  2860. in the support code.
  2861. \end{exercise}
  2862. \begin{exercise}
  2863. \normalfont\normalsize
  2864. \label{ex:Lvar}
  2865. Create five \LangVar{} programs that exercise the most interesting
  2866. parts of the \key{uniquify} pass; that is, the programs should include
  2867. \key{let} forms, variables, and variables that shadow each other.
  2868. The five programs should be placed in the subdirectory named
  2869. \key{tests}, and the file names should start with \code{var\_test\_}
  2870. followed by a unique integer and end with the file extension
  2871. \key{.rkt}.
  2872. %
  2873. The \key{run-tests.rkt} script in the support code checks whether the
  2874. output programs produce the same result as the input programs. The
  2875. script uses the \key{interp-tests} function
  2876. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2877. your \key{uniquify} pass on the example programs. The \code{passes}
  2878. parameter of \key{interp-tests} is a list that should have one entry
  2879. for each pass in your compiler. For now, define \code{passes} to
  2880. contain just one entry for \code{uniquify} as follows:
  2881. \begin{lstlisting}
  2882. (define passes
  2883. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2884. \end{lstlisting}
  2885. Run the \key{run-tests.rkt} script in the support code to check
  2886. whether the output programs produce the same result as the input
  2887. programs.
  2888. \end{exercise}
  2889. \fi}
  2890. \section{Remove Complex Operands}
  2891. \label{sec:remove-complex-opera-Lvar}
  2892. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2893. into a restricted form in which the arguments of operations are atomic
  2894. expressions. Put another way, this pass removes complex
  2895. operands\index{subject}{complex operand}, such as the expression
  2896. \racket{\code{(- 10)}}\python{\code{-10}}
  2897. in the following program. This is accomplished by introducing a new
  2898. temporary variable, assigning the complex operand to the new
  2899. variable, and then using the new variable in place of the complex
  2900. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2901. right.
  2902. {\if\edition\racketEd
  2903. \begin{transformation}
  2904. % var_test_19.rkt
  2905. \begin{lstlisting}
  2906. (let ([x (+ 42 (- 10))])
  2907. (+ x 10))
  2908. \end{lstlisting}
  2909. \compilesto
  2910. \begin{lstlisting}
  2911. (let ([x (let ([tmp.1 (- 10)])
  2912. (+ 42 tmp.1))])
  2913. (+ x 10))
  2914. \end{lstlisting}
  2915. \end{transformation}
  2916. \fi}
  2917. {\if\edition\pythonEd
  2918. \begin{transformation}
  2919. \begin{lstlisting}
  2920. x = 42 + -10
  2921. print(x + 10)
  2922. \end{lstlisting}
  2923. \compilesto
  2924. \begin{lstlisting}
  2925. tmp_0 = -10
  2926. x = 42 + tmp_0
  2927. tmp_1 = x + 10
  2928. print(tmp_1)
  2929. \end{lstlisting}
  2930. \end{transformation}
  2931. \fi}
  2932. \newcommand{\LvarMonadASTRacket}{
  2933. \begin{array}{rcl}
  2934. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2935. \Exp &::=& \Atm \MID \READ{} \\
  2936. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2937. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2938. \end{array}
  2939. }
  2940. \newcommand{\LvarMonadASTPython}{
  2941. \begin{array}{rcl}
  2942. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2943. \Exp{} &::=& \Atm \MID \READ{} \\
  2944. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2945. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2946. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2947. \end{array}
  2948. }
  2949. \begin{figure}[tp]
  2950. \centering
  2951. \begin{tcolorbox}[colback=white]
  2952. {\if\edition\racketEd
  2953. \[
  2954. \begin{array}{l}
  2955. \LvarMonadASTRacket \\
  2956. \begin{array}{rcl}
  2957. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2958. \end{array}
  2959. \end{array}
  2960. \]
  2961. \fi}
  2962. {\if\edition\pythonEd
  2963. \[
  2964. \begin{array}{l}
  2965. \LvarMonadASTPython \\
  2966. \begin{array}{rcl}
  2967. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2968. \end{array}
  2969. \end{array}
  2970. \]
  2971. \fi}
  2972. \end{tcolorbox}
  2973. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2974. atomic expressions.}
  2975. \label{fig:Lvar-anf-syntax}
  2976. \end{figure}
  2977. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2978. of this pass, the language \LangVarANF{}. The only difference is that
  2979. operator arguments are restricted to be atomic expressions that are
  2980. defined by the \Atm{} nonterminal. In particular, integer constants
  2981. and variables are atomic.
  2982. The atomic expressions are pure (they do not cause or depend on side
  2983. effects) whereas complex expressions may have side effects, such as
  2984. \READ{}. A language with this separation between pure expression
  2985. versus expressions with side effects is said to be in monadic normal
  2986. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2987. in the name \LangVarANF{}. An important invariant of the
  2988. \code{remove\_complex\_operands} pass is that the relative ordering
  2989. among complex expressions is not changed, but the relative ordering
  2990. between atomic expressions and complex expressions can change and
  2991. often does. The reason that these changes are behavior preserving is
  2992. that the atomic expressions are pure.
  2993. Another well-known form for intermediate languages is the
  2994. \emph{administrative normal form}
  2995. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2996. \index{subject}{administrative normal form} \index{subject}{ANF}
  2997. %
  2998. The \LangVarANF{} language is not quite in ANF because we allow the
  2999. right-hand side of a \code{let} to be a complex expression.
  3000. {\if\edition\racketEd
  3001. We recommend implementing this pass with two mutually recursive
  3002. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3003. \code{rco\_atom} to subexpressions that need to become atomic and to
  3004. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3005. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3006. returns an expression. The \code{rco\_atom} function returns two
  3007. things: an atomic expression and an alist mapping temporary variables to
  3008. complex subexpressions. You can return multiple things from a function
  3009. using Racket's \key{values} form, and you can receive multiple things
  3010. from a function call using the \key{define-values} form.
  3011. \fi}
  3012. %
  3013. {\if\edition\pythonEd
  3014. %
  3015. We recommend implementing this pass with an auxiliary method named
  3016. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3017. Boolean that specifies whether the expression needs to become atomic
  3018. or not. The \code{rco\_exp} method should return a pair consisting of
  3019. the new expression and a list of pairs, associating new temporary
  3020. variables with their initializing expressions.
  3021. %
  3022. \fi}
  3023. {\if\edition\racketEd
  3024. %
  3025. Returning to the example program with the expression \code{(+ 42 (-
  3026. 10))}, the subexpression \code{(- 10)} should be processed using the
  3027. \code{rco\_atom} function because it is an argument of the \code{+}
  3028. operator and therefore needs to become atomic. The output of
  3029. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3030. \begin{transformation}
  3031. \begin{lstlisting}
  3032. (- 10)
  3033. \end{lstlisting}
  3034. \compilesto
  3035. \begin{lstlisting}
  3036. tmp.1
  3037. ((tmp.1 . (- 10)))
  3038. \end{lstlisting}
  3039. \end{transformation}
  3040. \fi}
  3041. %
  3042. {\if\edition\pythonEd
  3043. %
  3044. Returning to the example program with the expression \code{42 + -10},
  3045. the subexpression \code{-10} should be processed using the
  3046. \code{rco\_exp} function with \code{True} as the second argument
  3047. because \code{-10} is an argument of the \code{+} operator and
  3048. therefore needs to become atomic. The output of \code{rco\_exp}
  3049. applied to \code{-10} is as follows.
  3050. \begin{transformation}
  3051. \begin{lstlisting}
  3052. -10
  3053. \end{lstlisting}
  3054. \compilesto
  3055. \begin{lstlisting}
  3056. tmp_1
  3057. [(tmp_1, -10)]
  3058. \end{lstlisting}
  3059. \end{transformation}
  3060. %
  3061. \fi}
  3062. Take special care of programs, such as the following, that
  3063. %
  3064. \racket{bind a variable to an atomic expression.}
  3065. %
  3066. \python{assign an atomic expression to a variable.}
  3067. %
  3068. You should leave such \racket{variable bindings}\python{assignments}
  3069. unchanged, as shown in the program on the right\\
  3070. %
  3071. {\if\edition\racketEd
  3072. \begin{transformation}
  3073. % var_test_20.rkt
  3074. \begin{lstlisting}
  3075. (let ([a 42])
  3076. (let ([b a])
  3077. b))
  3078. \end{lstlisting}
  3079. \compilesto
  3080. \begin{lstlisting}
  3081. (let ([a 42])
  3082. (let ([b a])
  3083. b))
  3084. \end{lstlisting}
  3085. \end{transformation}
  3086. \fi}
  3087. {\if\edition\pythonEd
  3088. \begin{transformation}
  3089. \begin{lstlisting}
  3090. a = 42
  3091. b = a
  3092. print(b)
  3093. \end{lstlisting}
  3094. \compilesto
  3095. \begin{lstlisting}
  3096. a = 42
  3097. b = a
  3098. print(b)
  3099. \end{lstlisting}
  3100. \end{transformation}
  3101. \fi}
  3102. %
  3103. \noindent A careless implementation might produce the following output with
  3104. unnecessary temporary variables.
  3105. \begin{center}
  3106. \begin{minipage}{0.4\textwidth}
  3107. {\if\edition\racketEd
  3108. \begin{lstlisting}
  3109. (let ([tmp.1 42])
  3110. (let ([a tmp.1])
  3111. (let ([tmp.2 a])
  3112. (let ([b tmp.2])
  3113. b))))
  3114. \end{lstlisting}
  3115. \fi}
  3116. {\if\edition\pythonEd
  3117. \begin{lstlisting}
  3118. tmp_1 = 42
  3119. a = tmp_1
  3120. tmp_2 = a
  3121. b = tmp_2
  3122. print(b)
  3123. \end{lstlisting}
  3124. \fi}
  3125. \end{minipage}
  3126. \end{center}
  3127. \begin{exercise}
  3128. \normalfont\normalsize
  3129. {\if\edition\racketEd
  3130. Implement the \code{remove\_complex\_operands} function in
  3131. \code{compiler.rkt}.
  3132. %
  3133. Create three new \LangVar{} programs that exercise the interesting
  3134. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3135. regarding file names described in exercise~\ref{ex:Lvar}.
  3136. %
  3137. In the \code{run-tests.rkt} script, add the following entry to the
  3138. list of \code{passes}, and then run the script to test your compiler.
  3139. \begin{lstlisting}
  3140. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3141. \end{lstlisting}
  3142. In debugging your compiler, it is often useful to see the intermediate
  3143. programs that are output from each pass. To print the intermediate
  3144. programs, place \lstinline{(debug-level 1)} before the call to
  3145. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3146. %
  3147. {\if\edition\pythonEd
  3148. Implement the \code{remove\_complex\_operands} pass in
  3149. \code{compiler.py}, creating auxiliary functions for each
  3150. nonterminal in the grammar, i.e., \code{rco\_exp}
  3151. and \code{rco\_stmt}. We recommend you use the function
  3152. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3153. \fi}
  3154. \end{exercise}
  3155. {\if\edition\pythonEd
  3156. \begin{exercise}
  3157. \normalfont\normalsize
  3158. \label{ex:Lvar}
  3159. Create five \LangVar{} programs that exercise the most interesting
  3160. parts of the \code{remove\_complex\_operands} pass. The five programs
  3161. should be placed in the subdirectory named \key{tests}, and the file
  3162. names should start with \code{var\_test\_} followed by a unique
  3163. integer and end with the file extension \key{.py}.
  3164. %% The \key{run-tests.rkt} script in the support code checks whether the
  3165. %% output programs produce the same result as the input programs. The
  3166. %% script uses the \key{interp-tests} function
  3167. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3168. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3169. %% parameter of \key{interp-tests} is a list that should have one entry
  3170. %% for each pass in your compiler. For now, define \code{passes} to
  3171. %% contain just one entry for \code{uniquify} as shown below.
  3172. %% \begin{lstlisting}
  3173. %% (define passes
  3174. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3175. %% \end{lstlisting}
  3176. Run the \key{run-tests.py} script in the support code to check
  3177. whether the output programs produce the same result as the input
  3178. programs.
  3179. \end{exercise}
  3180. \fi}
  3181. {\if\edition\racketEd
  3182. \section{Explicate Control}
  3183. \label{sec:explicate-control-Lvar}
  3184. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3185. programs that make the order of execution explicit in their
  3186. syntax. For now this amounts to flattening \key{let} constructs into a
  3187. sequence of assignment statements. For example, consider the following
  3188. \LangVar{} program:\\
  3189. % var_test_11.rkt
  3190. \begin{minipage}{0.96\textwidth}
  3191. \begin{lstlisting}
  3192. (let ([y (let ([x 20])
  3193. (+ x (let ([x 22]) x)))])
  3194. y)
  3195. \end{lstlisting}
  3196. \end{minipage}\\
  3197. %
  3198. The output of the previous pass is shown next, on the left, and the
  3199. output of \code{explicate\_control} is on the right. Recall that the
  3200. right-hand side of a \key{let} executes before its body, so that the order
  3201. of evaluation for this program is to assign \code{20} to \code{x.1},
  3202. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3203. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3204. this ordering explicit.
  3205. \begin{transformation}
  3206. \begin{lstlisting}
  3207. (let ([y (let ([x.1 20])
  3208. (let ([x.2 22])
  3209. (+ x.1 x.2)))])
  3210. y)
  3211. \end{lstlisting}
  3212. \compilesto
  3213. \begin{lstlisting}[language=C]
  3214. start:
  3215. x.1 = 20;
  3216. x.2 = 22;
  3217. y = (+ x.1 x.2);
  3218. return y;
  3219. \end{lstlisting}
  3220. \end{transformation}
  3221. \begin{figure}[tbp]
  3222. \begin{tcolorbox}[colback=white]
  3223. \begin{lstlisting}
  3224. (define (explicate_tail e)
  3225. (match e
  3226. [(Var x) ___]
  3227. [(Int n) (Return (Int n))]
  3228. [(Let x rhs body) ___]
  3229. [(Prim op es) ___]
  3230. [else (error "explicate_tail unhandled case" e)]))
  3231. (define (explicate_assign e x cont)
  3232. (match e
  3233. [(Var x) ___]
  3234. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3235. [(Let y rhs body) ___]
  3236. [(Prim op es) ___]
  3237. [else (error "explicate_assign unhandled case" e)]))
  3238. (define (explicate_control p)
  3239. (match p
  3240. [(Program info body) ___]))
  3241. \end{lstlisting}
  3242. \end{tcolorbox}
  3243. \caption{Skeleton for the \code{explicate\_control} pass.}
  3244. \label{fig:explicate-control-Lvar}
  3245. \end{figure}
  3246. The organization of this pass depends on the notion of tail position
  3247. to which we have alluded. Here is the definition.
  3248. \begin{definition}\normalfont
  3249. The following rules define when an expression is in \emph{tail
  3250. position}\index{subject}{tail position} for the language \LangVar{}.
  3251. \begin{enumerate}
  3252. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3253. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3254. \end{enumerate}
  3255. \end{definition}
  3256. We recommend implementing \code{explicate\_control} using two
  3257. recursive functions, \code{explicate\_tail} and
  3258. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3259. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3260. function should be applied to expressions in tail position, whereas the
  3261. \code{explicate\_assign} should be applied to expressions that occur on
  3262. the right-hand side of a \key{let}.
  3263. %
  3264. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3265. input and produces a \Tail{} in \LangCVar{} (see
  3266. figure~\ref{fig:c0-syntax}).
  3267. %
  3268. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3269. the variable to which it is to be assigned to, and a \Tail{} in
  3270. \LangCVar{} for the code that comes after the assignment. The
  3271. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3272. The \code{explicate\_assign} function is in accumulator-passing style:
  3273. the \code{cont} parameter is used for accumulating the output. This
  3274. accumulator-passing style plays an important role in the way that we
  3275. generate high-quality code for conditional expressions in
  3276. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3277. continuation because it contains the generated code that should come
  3278. after the current assignment. This code organization is also related
  3279. to continuation-passing style, except that \code{cont} is not what
  3280. happens next during compilation but is what happens next in the
  3281. generated code.
  3282. \begin{exercise}\normalfont\normalsize
  3283. %
  3284. Implement the \code{explicate\_control} function in
  3285. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3286. exercise the code in \code{explicate\_control}.
  3287. %
  3288. In the \code{run-tests.rkt} script, add the following entry to the
  3289. list of \code{passes} and then run the script to test your compiler.
  3290. \begin{lstlisting}
  3291. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3292. \end{lstlisting}
  3293. \end{exercise}
  3294. \fi}
  3295. \section{Select Instructions}
  3296. \label{sec:select-Lvar}
  3297. \index{subject}{instruction selection}
  3298. In the \code{select\_instructions} pass we begin the work of
  3299. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3300. language of this pass is a variant of x86 that still uses variables,
  3301. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3302. nonterminal of the \LangXInt{} abstract syntax
  3303. (figure~\ref{fig:x86-int-ast}).
  3304. \racket{We recommend implementing the
  3305. \code{select\_instructions} with three auxiliary functions, one for
  3306. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3307. $\Tail$.}
  3308. \python{We recommend implementing an auxiliary function
  3309. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3310. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3311. same and integer constants change to immediates; that is, $\INT{n}$
  3312. changes to $\IMM{n}$.}
  3313. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3314. arithmetic operations. For example, consider the following addition
  3315. operation, on the left side. There is an \key{addq} instruction in
  3316. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3317. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3318. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3319. $\Atm_2$, respectively.
  3320. \begin{transformation}
  3321. {\if\edition\racketEd
  3322. \begin{lstlisting}
  3323. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3324. \end{lstlisting}
  3325. \fi}
  3326. {\if\edition\pythonEd
  3327. \begin{lstlisting}
  3328. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3329. \end{lstlisting}
  3330. \fi}
  3331. \compilesto
  3332. \begin{lstlisting}
  3333. movq |$\Arg_1$|, |$\itm{var}$|
  3334. addq |$\Arg_2$|, |$\itm{var}$|
  3335. \end{lstlisting}
  3336. \end{transformation}
  3337. There are also cases that require special care to avoid generating
  3338. needlessly complicated code. For example, if one of the arguments of
  3339. the addition is the same variable as the left-hand side of the
  3340. assignment, as shown next, then there is no need for the extra move
  3341. instruction. The assignment statement can be translated into a single
  3342. \key{addq} instruction, as follows.
  3343. \begin{transformation}
  3344. {\if\edition\racketEd
  3345. \begin{lstlisting}
  3346. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3347. \end{lstlisting}
  3348. \fi}
  3349. {\if\edition\pythonEd
  3350. \begin{lstlisting}
  3351. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3352. \end{lstlisting}
  3353. \fi}
  3354. \compilesto
  3355. \begin{lstlisting}
  3356. addq |$\Arg_1$|, |$\itm{var}$|
  3357. \end{lstlisting}
  3358. \end{transformation}
  3359. The \READOP{} operation does not have a direct counterpart in x86
  3360. assembly, so we provide this functionality with the function
  3361. \code{read\_int} in the file \code{runtime.c}, written in
  3362. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3363. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3364. system}, or simply the \emph{runtime} for short. When compiling your
  3365. generated x86 assembly code, you need to compile \code{runtime.c} to
  3366. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3367. \code{-c}) and link it into the executable. For our purposes of code
  3368. generation, all you need to do is translate an assignment of
  3369. \READOP{} into a call to the \code{read\_int} function followed by a
  3370. move from \code{rax} to the left-hand side variable. (Recall that the
  3371. return value of a function goes into \code{rax}.)
  3372. \begin{transformation}
  3373. {\if\edition\racketEd
  3374. \begin{lstlisting}
  3375. |$\itm{var}$| = (read);
  3376. \end{lstlisting}
  3377. \fi}
  3378. {\if\edition\pythonEd
  3379. \begin{lstlisting}
  3380. |$\itm{var}$| = input_int();
  3381. \end{lstlisting}
  3382. \fi}
  3383. \compilesto
  3384. \begin{lstlisting}
  3385. callq read_int
  3386. movq %rax, |$\itm{var}$|
  3387. \end{lstlisting}
  3388. \end{transformation}
  3389. {\if\edition\pythonEd
  3390. %
  3391. Similarly, we translate the \code{print} operation, shown below, into
  3392. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3393. In x86, the first six arguments to functions are passed in registers,
  3394. with the first argument passed in register \code{rdi}. So we move the
  3395. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3396. \code{callq} instruction.
  3397. \begin{transformation}
  3398. \begin{lstlisting}
  3399. print(|$\Atm$|)
  3400. \end{lstlisting}
  3401. \compilesto
  3402. \begin{lstlisting}
  3403. movq |$\Arg$|, %rdi
  3404. callq print_int
  3405. \end{lstlisting}
  3406. \end{transformation}
  3407. %
  3408. \fi}
  3409. {\if\edition\racketEd
  3410. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3411. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3412. assignment to the \key{rax} register followed by a jump to the
  3413. conclusion of the program (so the conclusion needs to be labeled).
  3414. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3415. recursively and then append the resulting instructions.
  3416. \fi}
  3417. {\if\edition\pythonEd
  3418. We recommend that you use the function \code{utils.label\_name()} to
  3419. transform a string into an label argument suitably suitable for, e.g.,
  3420. the target of the \code{callq} instruction. This practice makes your
  3421. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3422. all labels.
  3423. \fi}
  3424. \begin{exercise}
  3425. \normalfont\normalsize
  3426. {\if\edition\racketEd
  3427. Implement the \code{select\_instructions} pass in
  3428. \code{compiler.rkt}. Create three new example programs that are
  3429. designed to exercise all the interesting cases in this pass.
  3430. %
  3431. In the \code{run-tests.rkt} script, add the following entry to the
  3432. list of \code{passes} and then run the script to test your compiler.
  3433. \begin{lstlisting}
  3434. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3435. \end{lstlisting}
  3436. \fi}
  3437. {\if\edition\pythonEd
  3438. Implement the \key{select\_instructions} pass in
  3439. \code{compiler.py}. Create three new example programs that are
  3440. designed to exercise all the interesting cases in this pass.
  3441. Run the \code{run-tests.py} script to to check
  3442. whether the output programs produce the same result as the input
  3443. programs.
  3444. \fi}
  3445. \end{exercise}
  3446. \section{Assign Homes}
  3447. \label{sec:assign-Lvar}
  3448. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3449. \LangXVar{} programs that no longer use program variables. Thus, the
  3450. \code{assign\_homes} pass is responsible for placing all the program
  3451. variables in registers or on the stack. For runtime efficiency, it is
  3452. better to place variables in registers, but because there are only
  3453. sixteen registers, some programs must necessarily resort to placing
  3454. some variables on the stack. In this chapter we focus on the mechanics
  3455. of placing variables on the stack. We study an algorithm for placing
  3456. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3457. Consider again the following \LangVar{} program from
  3458. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3459. % var_test_20.rkt
  3460. \begin{minipage}{0.96\textwidth}
  3461. {\if\edition\racketEd
  3462. \begin{lstlisting}
  3463. (let ([a 42])
  3464. (let ([b a])
  3465. b))
  3466. \end{lstlisting}
  3467. \fi}
  3468. {\if\edition\pythonEd
  3469. \begin{lstlisting}
  3470. a = 42
  3471. b = a
  3472. print(b)
  3473. \end{lstlisting}
  3474. \fi}
  3475. \end{minipage}\\
  3476. %
  3477. The output of \code{select\_instructions} is shown next, on the left,
  3478. and the output of \code{assign\_homes} is on the right. In this
  3479. example, we assign variable \code{a} to stack location
  3480. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3481. \begin{transformation}
  3482. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3483. movq $42, a
  3484. movq a, b
  3485. movq b, %rax
  3486. \end{lstlisting}
  3487. \compilesto
  3488. %stack-space: 16
  3489. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3490. movq $42, -8(%rbp)
  3491. movq -8(%rbp), -16(%rbp)
  3492. movq -16(%rbp), %rax
  3493. \end{lstlisting}
  3494. \end{transformation}
  3495. \racket{
  3496. The \code{assign\_homes} pass should replace all variables
  3497. with stack locations.
  3498. The list of variables can be obtained from
  3499. the \code{locals-types} entry in the $\itm{info}$ of the
  3500. \code{X86Program} node. The \code{locals-types} entry is an alist
  3501. mapping all the variables in the program to their types
  3502. (for now, just \code{Integer}).
  3503. As an aside, the \code{locals-types} entry is
  3504. computed by \code{type-check-Cvar} in the support code, which
  3505. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3506. which you should propagate to the \code{X86Program} node.}
  3507. %
  3508. \python{The \code{assign\_homes} pass should replace all uses of
  3509. variables with stack locations.}
  3510. %
  3511. In the process of assigning variables to stack locations, it is
  3512. convenient for you to compute and store the size of the frame (in
  3513. bytes) in
  3514. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3515. %
  3516. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3517. %
  3518. which is needed later to generate the conclusion of the \code{main}
  3519. procedure. The x86-64 standard requires the frame size to be a
  3520. multiple of 16 bytes.\index{subject}{frame}
  3521. % TODO: store the number of variables instead? -Jeremy
  3522. \begin{exercise}\normalfont\normalsize
  3523. Implement the \code{assign\_homes} pass in
  3524. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3525. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3526. grammar. We recommend that the auxiliary functions take an extra
  3527. parameter that maps variable names to homes (stack locations for now).
  3528. %
  3529. {\if\edition\racketEd
  3530. In the \code{run-tests.rkt} script, add the following entry to the
  3531. list of \code{passes} and then run the script to test your compiler.
  3532. \begin{lstlisting}
  3533. (list "assign homes" assign-homes interp_x86-0)
  3534. \end{lstlisting}
  3535. \fi}
  3536. {\if\edition\pythonEd
  3537. Run the \code{run-tests.py} script to to check
  3538. whether the output programs produce the same result as the input
  3539. programs.
  3540. \fi}
  3541. \end{exercise}
  3542. \section{Patch Instructions}
  3543. \label{sec:patch-s0}
  3544. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3545. \LangXInt{} by making sure that each instruction adheres to the
  3546. restriction that at most one argument of an instruction may be a
  3547. memory reference.
  3548. We return to the following example.\\
  3549. \begin{minipage}{0.5\textwidth}
  3550. % var_test_20.rkt
  3551. {\if\edition\racketEd
  3552. \begin{lstlisting}
  3553. (let ([a 42])
  3554. (let ([b a])
  3555. b))
  3556. \end{lstlisting}
  3557. \fi}
  3558. {\if\edition\pythonEd
  3559. \begin{lstlisting}
  3560. a = 42
  3561. b = a
  3562. print(b)
  3563. \end{lstlisting}
  3564. \fi}
  3565. \end{minipage}\\
  3566. The \code{assign\_homes} pass produces the following translation. \\
  3567. \begin{minipage}{0.5\textwidth}
  3568. {\if\edition\racketEd
  3569. \begin{lstlisting}
  3570. movq $42, -8(%rbp)
  3571. movq -8(%rbp), -16(%rbp)
  3572. movq -16(%rbp), %rax
  3573. \end{lstlisting}
  3574. \fi}
  3575. {\if\edition\pythonEd
  3576. \begin{lstlisting}
  3577. movq 42, -8(%rbp)
  3578. movq -8(%rbp), -16(%rbp)
  3579. movq -16(%rbp), %rdi
  3580. callq print_int
  3581. \end{lstlisting}
  3582. \fi}
  3583. \end{minipage}\\
  3584. The second \key{movq} instruction is problematic because both
  3585. arguments are stack locations. We suggest fixing this problem by
  3586. moving from the source location to the register \key{rax} and then
  3587. from \key{rax} to the destination location, as follows.
  3588. \begin{lstlisting}
  3589. movq -8(%rbp), %rax
  3590. movq %rax, -16(%rbp)
  3591. \end{lstlisting}
  3592. \begin{exercise}
  3593. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3594. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3595. Create three new example programs that are
  3596. designed to exercise all the interesting cases in this pass.
  3597. %
  3598. {\if\edition\racketEd
  3599. In the \code{run-tests.rkt} script, add the following entry to the
  3600. list of \code{passes} and then run the script to test your compiler.
  3601. \begin{lstlisting}
  3602. (list "patch instructions" patch_instructions interp_x86-0)
  3603. \end{lstlisting}
  3604. \fi}
  3605. {\if\edition\pythonEd
  3606. Run the \code{run-tests.py} script to to check
  3607. whether the output programs produce the same result as the input
  3608. programs.
  3609. \fi}
  3610. \end{exercise}
  3611. \section{Generate Prelude and Conclusion}
  3612. \label{sec:print-x86}
  3613. \index{subject}{prelude}\index{subject}{conclusion}
  3614. The last step of the compiler from \LangVar{} to x86 is to generate
  3615. the \code{main} function with a prelude and conclusion wrapped around
  3616. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3617. discussed in section~\ref{sec:x86}.
  3618. When running on Mac OS X, your compiler should prefix an underscore to
  3619. all labels, e.g., changing \key{main} to \key{\_main}.
  3620. %
  3621. \racket{The Racket call \code{(system-type 'os)} is useful for
  3622. determining which operating system the compiler is running on. It
  3623. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3624. %
  3625. \python{The Python \code{platform} library includes a \code{system()}
  3626. function that returns \code{'Linux'}, \code{'Windows'}, or
  3627. \code{'Darwin'} (for Mac).}
  3628. \begin{exercise}\normalfont\normalsize
  3629. %
  3630. Implement the \key{prelude\_and\_conclusion} pass in
  3631. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3632. %
  3633. {\if\edition\racketEd
  3634. In the \code{run-tests.rkt} script, add the following entry to the
  3635. list of \code{passes} and then run the script to test your compiler.
  3636. \begin{lstlisting}
  3637. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3638. \end{lstlisting}
  3639. %
  3640. Uncomment the call to the \key{compiler-tests} function
  3641. (appendix~\ref{appendix:utilities}), which tests your complete
  3642. compiler by executing the generated x86 code. It translates the x86
  3643. AST that you produce into a string by invoking the \code{print-x86}
  3644. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3645. the provided \key{runtime.c} file to \key{runtime.o} using
  3646. \key{gcc}. Run the script to test your compiler.
  3647. %
  3648. \fi}
  3649. {\if\edition\pythonEd
  3650. %
  3651. Run the \code{run-tests.py} script to to check whether the output
  3652. programs produce the same result as the input programs. That script
  3653. translates the x86 AST that you produce into a string by invoking the
  3654. \code{repr} method that is implemented by the x86 AST classes in
  3655. \code{x86\_ast.py}.
  3656. %
  3657. \fi}
  3658. \end{exercise}
  3659. \section{Challenge: Partial Evaluator for \LangVar{}}
  3660. \label{sec:pe-Lvar}
  3661. \index{subject}{partial evaluation}
  3662. This section describes two optional challenge exercises that involve
  3663. adapting and improving the partial evaluator for \LangInt{} that was
  3664. introduced in section~\ref{sec:partial-evaluation}.
  3665. \begin{exercise}\label{ex:pe-Lvar}
  3666. \normalfont\normalsize
  3667. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3668. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3669. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3670. %
  3671. \racket{\key{let} binding}\python{assignment}
  3672. %
  3673. to the \LangInt{} language, so you will need to add cases for them in
  3674. the \code{pe\_exp}
  3675. %
  3676. \racket{function.}
  3677. %
  3678. \python{and \code{pe\_stmt} functions.}
  3679. %
  3680. Once complete, add the partial evaluation pass to the front of your
  3681. compiler, and make sure that your compiler still passes all the
  3682. tests.
  3683. \end{exercise}
  3684. \begin{exercise}
  3685. \normalfont\normalsize
  3686. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3687. \code{pe\_add} auxiliary functions with functions that know more about
  3688. arithmetic. For example, your partial evaluator should translate
  3689. {\if\edition\racketEd
  3690. \[
  3691. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3692. \code{(+ 2 (read))}
  3693. \]
  3694. \fi}
  3695. {\if\edition\pythonEd
  3696. \[
  3697. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3698. \code{2 + input\_int()}
  3699. \]
  3700. \fi}
  3701. %
  3702. To accomplish this, the \code{pe\_exp} function should produce output
  3703. in the form of the $\itm{residual}$ nonterminal of the following
  3704. grammar. The idea is that when processing an addition expression, we
  3705. can always produce one of the following: (1) an integer constant, (2)
  3706. an addition expression with an integer constant on the left-hand side
  3707. but not the right-hand side, or (3) an addition expression in which
  3708. neither subexpression is a constant.
  3709. %
  3710. {\if\edition\racketEd
  3711. \[
  3712. \begin{array}{lcl}
  3713. \itm{inert} &::=& \Var
  3714. \MID \LP\key{read}\RP
  3715. \MID \LP\key{-} ~\Var\RP
  3716. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3717. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3718. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3719. \itm{residual} &::=& \Int
  3720. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3721. \MID \itm{inert}
  3722. \end{array}
  3723. \]
  3724. \fi}
  3725. {\if\edition\pythonEd
  3726. \[
  3727. \begin{array}{lcl}
  3728. \itm{inert} &::=& \Var
  3729. \MID \key{input\_int}\LP\RP
  3730. \MID \key{-} \Var
  3731. \MID \key{-} \key{input\_int}\LP\RP
  3732. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3733. \itm{residual} &::=& \Int
  3734. \MID \Int ~ \key{+} ~ \itm{inert}
  3735. \MID \itm{inert}
  3736. \end{array}
  3737. \]
  3738. \fi}
  3739. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3740. inputs are $\itm{residual}$ expressions and they should return
  3741. $\itm{residual}$ expressions. Once the improvements are complete,
  3742. make sure that your compiler still passes all the tests. After
  3743. all, fast code is useless if it produces incorrect results!
  3744. \end{exercise}
  3745. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3746. {\if\edition\pythonEd
  3747. \chapter{Parsing}
  3748. \label{ch:parsing}
  3749. \setcounter{footnote}{0}
  3750. \index{subject}{parsing}
  3751. In this chapter we learn how to use the Lark parser
  3752. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3753. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3754. You will then be asked to use Lark to create a parser for \LangVar{}.
  3755. We also describe the parsing algorithms used inside Lark, studying the
  3756. \citet{Earley:1970ly} and LALR(1) algorithms.
  3757. A parser framework such as Lark takes in a specification of the
  3758. concrete syntax and the input program and produces a parse tree. Even
  3759. though a parser framework does most of the work for us, using one
  3760. properly requires some knowledge. In particular, we must learn about
  3761. its specification languages and we must learn how to deal with
  3762. ambiguity in our language specifications.
  3763. The process of parsing is traditionally subdivided into two phases:
  3764. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3765. analysis} (also called parsing). The lexical analysis phase
  3766. translates the sequence of characters into a sequence of
  3767. \emph{tokens}, that is, words consisting of several characters. The
  3768. parsing phase organizes the tokens into a \emph{parse tree} that
  3769. captures how the tokens were matched by rules in the grammar of the
  3770. language. The reason for the subdivision into two phases is to enable
  3771. the use of a faster but less powerful algorithm for lexical analysis
  3772. and the use of a slower but more powerful algorithm for parsing.
  3773. %
  3774. %% Likewise, parser generators typical come in pairs, with separate
  3775. %% generators for the lexical analyzer (or lexer for short) and for the
  3776. %% parser. A paricularly influential pair of generators were
  3777. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3778. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3779. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3780. %% Compiler Compiler.
  3781. %
  3782. The Lark parse framwork that we use in this chapter includes both
  3783. lexical analyzers and parsers. The next section discusses lexical
  3784. analysis and the remainder of the chapter discusses parsing.
  3785. \section{Lexical Analysis and Regular Expressions}
  3786. \label{sec:lex}
  3787. The lexical analyzers produced by Lark turn a sequence of characters
  3788. (a string) into a sequence of token objects. For example, a Lark
  3789. generated lexer for \LangInt{} converts the string
  3790. \begin{lstlisting}
  3791. 'print(1 + 3)'
  3792. \end{lstlisting}
  3793. \noindent into the following sequence of token objects
  3794. \begin{center}
  3795. \begin{minipage}{0.95\textwidth}
  3796. \begin{lstlisting}
  3797. Token('PRINT', 'print')
  3798. Token('LPAR', '(')
  3799. Token('INT', '1')
  3800. Token('PLUS', '+')
  3801. Token('INT', '3')
  3802. Token('RPAR', ')')
  3803. Token('NEWLINE', '\n')
  3804. \end{lstlisting}
  3805. \end{minipage}
  3806. \end{center}
  3807. Each token includes a field for its \code{type}, such as \code{'INT'},
  3808. and a field for its \code{value}, such as \code{'1'}.
  3809. Following in the tradition of \code{lex}, the specification language
  3810. for Lark's lexical analysis generator is one regular expression for
  3811. each type of token. The term \emph{regular} comes from the term
  3812. \emph{regular languages}, which are the languages that can be
  3813. recognized by a finite automata. A \emph{regular expression} is a
  3814. pattern formed of the following core elements:\index{subject}{regular
  3815. expression}\footnote{Regular expressions traditionally include the
  3816. empty regular expression that matches any zero-length part of a
  3817. string, but Lark does not support the empty regular expression.}
  3818. \begin{itemize}
  3819. \item A single character $c$ is a regular expression and it only
  3820. matches itself. For example, the regular expression \code{a} only
  3821. matches with the string \code{'a'}.
  3822. \item Two regular expressions separated by a vertical bar $R_1 \mid
  3823. R_2$ form a regular expression that matches any string that matches
  3824. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3825. matches the string \code{'a'} and the string \code{'c'}.
  3826. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3827. expression that matches any string that can be formed by
  3828. concatenating two strings, where the first matches $R_1$
  3829. and the second matches $R_2$. For example, the regular expression
  3830. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3831. (Parentheses can be used to control the grouping of operators within
  3832. a regular expression.)
  3833. \item A regular expression followed by an asterisks $R*$ (called
  3834. Kleene closure) is a regular expression that matches any string that
  3835. can be formed by concatenating zero or more strings that each match
  3836. the regular expression $R$. For example, the regular expression
  3837. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} and
  3838. \code{''}, but not \code{'abc'}.
  3839. \end{itemize}
  3840. For our convenience, Lark also accepts an extended set of regular
  3841. expressions that are automatically translated into the core regular
  3842. expressions.
  3843. \begin{itemize}
  3844. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3845. c_n]$ is a regular expression that matches any one of the
  3846. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3847. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3848. \item A range of characters enclosed in square brackets $[c_1-c_2]$ is
  3849. a regular expression that matches any character between $c_1$ and
  3850. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3851. letter in the alphabet.
  3852. \item A regular expression followed by the plus symbol $R+$
  3853. is a regular expression that matches any string that can
  3854. be formed by concatenating one or more strings that each match $R$.
  3855. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3856. matches \code{'b'} and \code{'bzca'}.
  3857. \item A regular expression followed by a question mark $R?$
  3858. is a regular expression that matches any string that either
  3859. matches $R$ or that is the empty string.
  3860. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3861. \item A string, such as \code{"hello"}, which matches itself,
  3862. that is, \code{'hello'}.
  3863. \end{itemize}
  3864. In a Lark grammar file, specify a name for each type of token followed
  3865. by a colon and then a regular expression surrounded by \code{/}
  3866. characters. For example, the \code{DIGIT}, \code{INT}, and
  3867. \code{NEWLINE} types of tokens are specified in the following way.
  3868. \begin{center}
  3869. \begin{minipage}{0.95\textwidth}
  3870. \begin{lstlisting}
  3871. DIGIT: /[0-9]/
  3872. INT: "-"? DIGIT+
  3873. NEWLINE: (/\r/? /\n/)+
  3874. \end{lstlisting}
  3875. \end{minipage}
  3876. \end{center}
  3877. \noindent In Lark, the regular expression operators can be used both
  3878. inside a regular expression, that is, between the \code{/} characters,
  3879. and they can be used to combine regular expressions, outside the
  3880. \code{/} characters.
  3881. \section{Grammars and Parse Trees}
  3882. \label{sec:CFG}
  3883. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3884. specify the abstract syntax of a language. We now take a closer look
  3885. at using grammar rules to specify the concrete syntax. Recall that
  3886. each rule has a left-hand side and a right-hand side. However, for
  3887. concrete syntax, each right-hand side expresses a pattern to match
  3888. against a string, instead of matching against an abstract syntax
  3889. tree. In particular, each right-hand side is a sequence of
  3890. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3891. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3892. a string. The nonterminals play the same role as in the abstract
  3893. syntax, defining categories of syntax. The nonterminals of a grammar
  3894. include the tokens defined in the lexer and all the nonterminals
  3895. defined in the grammar rules.
  3896. As an example, let us take a closer look at the concrete syntax of the
  3897. \LangInt{} language, repeated here.
  3898. \[
  3899. \begin{array}{l}
  3900. \LintGrammarPython \\
  3901. \begin{array}{rcl}
  3902. \LangInt{} &::=& \Stmt^{*}
  3903. \end{array}
  3904. \end{array}
  3905. \]
  3906. The Lark syntax for grammar rules differs slightly from the variant of
  3907. BNF that we use in this book. In particular, the notation $::=$ is
  3908. replaced by a single colon and the use of typewriter font for string
  3909. literals is replaced by quotation marks. The following grammar serves
  3910. as a first draft of a Lark grammar for \LangInt{}.
  3911. \begin{center}
  3912. \begin{minipage}{0.95\textwidth}
  3913. \begin{lstlisting}[escapechar=$]
  3914. exp: INT
  3915. | "input_int" "(" ")"
  3916. | "-" exp
  3917. | exp "+" exp
  3918. | exp "-" exp
  3919. | "(" exp ")"
  3920. stmt_list:
  3921. | stmt NEWLINE stmt_list
  3922. lang_int: stmt_list
  3923. \end{lstlisting}
  3924. \end{minipage}
  3925. \end{center}
  3926. Let us begin by discussing the rule \code{exp: INT}. In
  3927. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  3928. nonterminal with an English sentence. Here we specify \code{INT} more
  3929. formally using a type of token \code{INT} and its regular expression
  3930. \code{"-"? DIGIT+}. Thus, the rule \code{exp: INT} says that if the
  3931. lexer matches a string to \code{INT}, then the parser also categorizes
  3932. the string as an \code{exp}.
  3933. The rule \code{exp: exp "+" exp} says that any string that matches
  3934. \code{exp}, followed by the \code{+} character, followed by another
  3935. string that matches \code{exp}, is itself an \code{exp}. For example,
  3936. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  3937. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then the
  3938. rule for addition applies to categorize \code{'1+3'} as an \Exp{}. We
  3939. can visualize the application of grammar rules to categorize a string
  3940. using a \emph{parse tree}\index{subject}{parse tree}. Each internal
  3941. node in the tree is an application of a grammar rule and is labeled
  3942. with the nonterminal of its left-hand side. Each leaf node is a
  3943. substring of the input program. The parse tree for \code{'1+3'} is
  3944. shown in figure~\ref{fig:simple-parse-tree}.
  3945. \begin{figure}[tbp]
  3946. \begin{tcolorbox}[colback=white]
  3947. \centering
  3948. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  3949. \end{tcolorbox}
  3950. \caption{The parse tree for \code{'1+3'}.}
  3951. \label{fig:simple-parse-tree}
  3952. \end{figure}
  3953. The result of parsing \code{'1+3'} with this Lark grammar is the
  3954. following parse tree as represented by \code{Tree} and \code{Token}
  3955. objects.
  3956. \begin{lstlisting}
  3957. Tree('lang_int',
  3958. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  3959. Tree('exp', [Token('INT', '3')])])]),
  3960. Token('NEWLINE', '\n')])
  3961. \end{lstlisting}
  3962. The nodes that come from the lexer are \code{Token} objects whereas
  3963. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  3964. object has a \code{data} field containing the name of the nonterminal
  3965. for the grammar rule that was applied. Each \code{Tree} object also
  3966. has a \code{children} field that is a list containing trees and/or
  3967. tokens. Note that Lark does not produce nodes for string literals in
  3968. the grammar. For example, the \code{Tree} node for the addition
  3969. expression has only two children for the two integers but is missing
  3970. its middle child for the \code{"+"} terminal. This would be
  3971. problematic except that Lark provides a mechanism for customizing the
  3972. \code{data} field of each \code{Tree} node based on which rule was
  3973. applied. Next to each alternative in a grammar rule, write \code{->}
  3974. followed by a string that you would like to appear in the \code{data}
  3975. field. The following is a second draft of a Lark grammar for
  3976. \LangInt{}, this time with more specific labels on the \code{Tree}
  3977. nodes.
  3978. \begin{center}
  3979. \begin{minipage}{0.95\textwidth}
  3980. \begin{lstlisting}[escapechar=$]
  3981. exp: INT -> int
  3982. | "input_int" "(" ")" -> input_int
  3983. | "-" exp -> usub
  3984. | exp "+" exp -> add
  3985. | exp "-" exp -> sub
  3986. | "(" exp ")" -> paren
  3987. stmt: "print" "(" exp ")" -> print
  3988. | exp -> expr
  3989. stmt_list: -> empty_stmt
  3990. | stmt NEWLINE stmt_list -> add_stmt
  3991. lang_int: stmt_list -> module
  3992. \end{lstlisting}
  3993. \end{minipage}
  3994. \end{center}
  3995. Here is the resulting parse tree.
  3996. \begin{lstlisting}
  3997. Tree('module',
  3998. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  3999. Tree('int', [Token('INT', '3')])])]),
  4000. Token('NEWLINE', '\n')])
  4001. \end{lstlisting}
  4002. \section{Ambiguous Grammars}
  4003. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4004. can be parsed in more than one way. For example, consider the string
  4005. \code{'1-2+3'}. This string can parsed in two different ways using
  4006. our draft grammar, resulting in the two parse trees shown in
  4007. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4008. interpreting the second parse tree would yield \code{-4} even through
  4009. the correct answer is \code{2}.
  4010. \begin{figure}[tbp]
  4011. \begin{tcolorbox}[colback=white]
  4012. \centering
  4013. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4014. \end{tcolorbox}
  4015. \caption{The two parse trees for \code{'1-2+3'}.}
  4016. \label{fig:ambig-parse-tree}
  4017. \end{figure}
  4018. To deal with this problem we can change the grammar by categorizing
  4019. the syntax in a more fine grained fashion. In this case we want to
  4020. disallow the application of the rule \code{exp: exp "-" exp} when the
  4021. child on the right is an addition. To do this we can replace the
  4022. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4023. the expressions except for addition, as in the following.
  4024. \begin{center}
  4025. \begin{minipage}{0.95\textwidth}
  4026. \begin{lstlisting}[escapechar=$]
  4027. exp: exp "-" exp_no_add -> sub
  4028. | exp "+" exp -> add
  4029. | exp_no_add
  4030. exp_no_add: INT -> int
  4031. | "input_int" "(" ")" -> input_int
  4032. | "-" exp -> usub
  4033. | exp "-" exp_no_add -> sub
  4034. | "(" exp ")" -> paren
  4035. \end{lstlisting}
  4036. \end{minipage}
  4037. \end{center}
  4038. However, there remains some ambiguity in the grammar. For example, the
  4039. string \code{'1-2-3'} can still be parsed in two different ways, as
  4040. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4041. to say, subtraction is left associative. Likewise, addition in Python
  4042. is left associative. We also need to consider the interaction of unary
  4043. subtraction with both addition and subtraction. How should we parse
  4044. \code{'-1+2'}? Unary subtraction has higher
  4045. \emph{precendence}\index{subject}{precedence} than addition and
  4046. subtraction, so \code{'-1+2'} should parse as \code{'(-1)+2'} and not
  4047. \code{'-(1+2)'}. The grammar in figure~\ref{fig:Lint-lark-grammar}
  4048. handles the associativity of addition and subtraction by using the
  4049. nonterminal \code{exp\_hi} for all the other expressions, and uses
  4050. \code{exp\_hi} for the second child in the rules for addition and
  4051. subtraction. Furthermore, unary subtraction uses \code{exp\_hi} for
  4052. its child.
  4053. For languages with more operators and more precedence levels, one
  4054. would need to refine the \code{exp} nonterminal into several
  4055. nonterminals, one for each precedence level.
  4056. \begin{figure}[tbp]
  4057. \begin{tcolorbox}[colback=white]
  4058. \centering
  4059. \begin{lstlisting}[escapechar=$]
  4060. exp: exp "+" exp_hi -> add
  4061. | exp "-" exp_hi -> sub
  4062. | exp_hi
  4063. exp_hi: INT -> int
  4064. | "input_int" "(" ")" -> input_int
  4065. | "-" exp_hi -> usub
  4066. | "(" exp ")" -> paren
  4067. stmt: "print" "(" exp ")" -> print
  4068. | exp -> expr
  4069. stmt_list: -> empty_stmt
  4070. | stmt NEWLINE stmt_list -> add_stmt
  4071. lang_int: stmt_list -> module
  4072. \end{lstlisting}
  4073. \end{tcolorbox}
  4074. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4075. \label{fig:Lint-lark-grammar}
  4076. \end{figure}
  4077. \section{From Parse Trees to Abstract Syntax Trees}
  4078. As we have seen, the output of a Lark parser is a parse tree, that is,
  4079. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4080. step is to convert the parse tree to an abstract syntax tree. This can
  4081. be accomplished with a recursive function that inspects the
  4082. \code{data} field of each node and then constructs the corresponding
  4083. AST node, using recursion to handle its children. The following is an
  4084. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4085. \begin{center}
  4086. \begin{minipage}{0.95\textwidth}
  4087. \begin{lstlisting}
  4088. def parse_tree_to_ast(e):
  4089. if e.data == 'int':
  4090. return Constant(int(e.children[0].value))
  4091. elif e.data == 'input_int':
  4092. return Call(Name('input_int'), [])
  4093. elif e.data == 'add':
  4094. e1, e2 = e.children
  4095. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4096. ...
  4097. else:
  4098. raise Exception('unhandled parse tree', e)
  4099. \end{lstlisting}
  4100. \end{minipage}
  4101. \end{center}
  4102. \begin{exercise}
  4103. \normalfont\normalsize
  4104. %
  4105. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4106. default parsing algorithm (Earley) with the \code{ambiguity} option
  4107. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4108. output will include multiple parse trees which will indicate to you
  4109. that there is a problem with your grammar. Your parser should ignore
  4110. white space so we recommend using Lark's \code{\%ignore} directive
  4111. as follows.
  4112. \begin{lstlisting}
  4113. WS: /[ \t\f\r\n]/+
  4114. %ignore WS
  4115. \end{lstlisting}
  4116. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4117. Lark-generated parser instead of using the \code{parse} function from
  4118. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4119. programs that you have created and create four additional programs
  4120. that would reveal ambiguities in your grammar.
  4121. \end{exercise}
  4122. \section{The Earley Algorithm}
  4123. \label{sec:earley}
  4124. In this section we discuss the parsing algorithm of
  4125. \citet{Earley:1970ly}, which is the default algorithm used by Lark.
  4126. The algorithm is powerful in that it can handle any context-free
  4127. grammar, which makes it easy to use. However, it is not the most
  4128. efficient parsing algorithm: it is $O(n^3)$ for ambiguous grammars and
  4129. $O(n^2)$ for unambiguous grammars~\citep{Hopcroft06:_automata}, where
  4130. $n$ is the number of tokens in the input string. In
  4131. section~\ref{sec:lalr} we learn about the LALR algorithm, which is
  4132. more efficient but can only handle a subset of the context-free
  4133. grammars.
  4134. The Earley algorithm can be viewed as an interpreter; it treats the
  4135. grammar as the program being interpreted and it treats the concrete
  4136. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4137. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4138. keep track of its progress and to memoize its results. The chart is an
  4139. array with one slot for each position in the input string, where
  4140. position $0$ is before the first character and position $n$ is
  4141. immediately after the last character. So the array has length $n+1$
  4142. for an input string of length $n$. Each slot in the chart contains a
  4143. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4144. with a period indicating how much of its right-hand side has already
  4145. been parsed. For example, the dotted rule
  4146. \begin{lstlisting}
  4147. exp: exp "+" . exp_hi
  4148. \end{lstlisting}
  4149. represents a partial parse that has matched an \code{exp} followed by
  4150. \code{+}, but has not yet parsed an \code{exp} to the right of
  4151. \code{+}.
  4152. %
  4153. The Earley algorithm starts with an initialization phase, and then
  4154. repeats three actions (prediction, scanning, and completion) for as
  4155. long as opportunities arise for those actions. We demonstrate the
  4156. Earley algorithm on a running example, parsing the following program:
  4157. \begin{lstlisting}
  4158. print(1 + 3)
  4159. \end{lstlisting}
  4160. The algorithm's initialization phase creates dotted rules for all the
  4161. grammar rules whose left-hand side is the start symbol and places them
  4162. in slot $0$ of the chart. It also records the starting position of the
  4163. dotted rule, in parentheses on the right. For example, given the
  4164. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4165. \begin{lstlisting}
  4166. lang_int: . stmt_list (0)
  4167. \end{lstlisting}
  4168. in slot $0$ of the chart. The algorithm then proceeds to with
  4169. \emph{prediction} actions in which it adds more dotted rules to the
  4170. chart based on which nonterminal come after a period. In the above,
  4171. the nonterminal \code{stmt\_list} appears after a period, so we add all
  4172. the rules for \code{stmt\_list} to slot $0$, with a period at the
  4173. beginning of their right-hand sides, as follows:
  4174. \begin{lstlisting}
  4175. stmt_list: . (0)
  4176. stmt_list: . stmt NEWLINE stmt_list (0)
  4177. \end{lstlisting}
  4178. We continue to perform prediction actions as more opportunities
  4179. arise. For example, the \code{stmt} nonterminal now appears after a
  4180. period, so we add all the rules for \code{stmt}.
  4181. \begin{lstlisting}
  4182. stmt: . "print" "(" exp ")" (0)
  4183. stmt: . exp (0)
  4184. \end{lstlisting}
  4185. This reveals more opportunities for prediction, so we add the grammar
  4186. rules for \code{exp} and \code{exp\_hi}.
  4187. \begin{lstlisting}[escapechar=$]
  4188. exp: . exp "+" exp_hi (0)
  4189. exp: . exp "-" exp_hi (0)
  4190. exp: . exp_hi (0)
  4191. exp_hi: . INT (0)
  4192. exp_hi: . "input_int" "(" ")" (0)
  4193. exp_hi: . "-" exp_hi (0)
  4194. exp_hi: . "(" exp ")" (0)
  4195. \end{lstlisting}
  4196. We have exhausted the opportunities for prediction, so the algorithm
  4197. proceeds to \emph{scanning}, in which we inspect the next input token
  4198. and look for a dotted rule at the current position that has a matching
  4199. terminal following the period. In our running example, the first input
  4200. token is \code{"print"} so we identify the dotted rule in slot $0$ of
  4201. the chart:
  4202. \begin{lstlisting}
  4203. stmt: . "print" "(" exp ")" (0)
  4204. \end{lstlisting}
  4205. and add the following rule to slot $1$ of the chart, with the period
  4206. moved forward past \code{"print"}.
  4207. \begin{lstlisting}
  4208. stmt: "print" . "(" exp ")" (0)
  4209. \end{lstlisting}
  4210. If the new dotted rule had a nonterminal after the period, we would
  4211. need to carry out a prediction action, adding more dotted rules into
  4212. slot $1$. That is not the case, so we continue scanning. The next
  4213. input token is \code{"("}, so we add the following to slot $2$ of the
  4214. chart.
  4215. \begin{lstlisting}
  4216. stmt: "print" "(" . exp ")" (0)
  4217. \end{lstlisting}
  4218. Now we have a nonterminal after the period, so we carry out several
  4219. prediction actions, adding dotted rules for \code{exp} and
  4220. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4221. starting position $2$.
  4222. \begin{lstlisting}[escapechar=$]
  4223. exp: . exp "+" exp_hi (2)
  4224. exp: . exp "-" exp_hi (2)
  4225. exp: . exp_hi (2)
  4226. exp_hi: . INT (2)
  4227. exp_hi: . "input_int" "(" ")" (2)
  4228. exp_hi: . "-" exp_hi (2)
  4229. exp_hi: . "(" exp ")" (2)
  4230. \end{lstlisting}
  4231. With that prediction complete, we return to scanning, noting that the
  4232. next input token is \code{"1"} which the lexer categorized as an
  4233. \code{INT}. There is a matching rule is slot $2$:
  4234. \begin{lstlisting}
  4235. exp_hi: . INT (2)
  4236. \end{lstlisting}
  4237. so we advance the period and put the following rule is slot $3$.
  4238. \begin{lstlisting}
  4239. exp_hi: INT . (2)
  4240. \end{lstlisting}
  4241. This brings us to \emph{completion} actions. When the period reaches
  4242. the end of a dotted rule, we have finished parsing a substring
  4243. according to the left-hand side of the rule, in this case
  4244. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4245. rules in slot $2$ (the starting position for the finished rule) the
  4246. period is immediately followed by \code{exp\_hi}. So we identify
  4247. \begin{lstlisting}
  4248. exp: . exp_hi (2)
  4249. \end{lstlisting}
  4250. and add the following dotted rule to slot $3$
  4251. \begin{lstlisting}
  4252. exp: exp_hi . (2)
  4253. \end{lstlisting}
  4254. This triggers another completion step for the nonterminal \code{exp},
  4255. adding two more dotted rules to slot $3$.
  4256. \begin{lstlisting}[escapechar=$]
  4257. exp: exp . "+" exp_hi (2)
  4258. exp: exp . "-" exp_hi (2)
  4259. \end{lstlisting}
  4260. Returning to scanning, the next input token is \code{"+"}, so
  4261. we add the following to slot $4$.
  4262. \begin{lstlisting}[escapechar=$]
  4263. exp: exp "+" . exp_hi (2)
  4264. \end{lstlisting}
  4265. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4266. the following dotted rules to slot $4$ of the chart.
  4267. \begin{lstlisting}[escapechar=$]
  4268. exp_hi: . INT (4)
  4269. exp_hi: . "input_int" "(" ")" (4)
  4270. exp_hi: . "-" exp_hi (4)
  4271. exp_hi: . "(" exp ")" (4)
  4272. \end{lstlisting}
  4273. The next input token is \code{"3"} which the lexer categorized as an
  4274. \code{INT}, so we advance the period past \code{INT} for the rules in
  4275. slot $4$, of which there is just one, and put the following in slot $5$.
  4276. \begin{lstlisting}[escapechar=$]
  4277. exp_hi: INT . (4)
  4278. \end{lstlisting}
  4279. The period at the end of the rule triggers a completion action for the
  4280. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4281. So we advance the period and put the following in slot $5$.
  4282. \begin{lstlisting}[escapechar=$]
  4283. exp: exp "+" exp_hi . (2)
  4284. \end{lstlisting}
  4285. This triggers another completion action for the rules in slot $2$ that
  4286. have a period before \code{exp}.
  4287. \begin{lstlisting}[escapechar=$]
  4288. stmt: "print" "(" exp . ")" (0)
  4289. exp: exp . "+" exp_hi (2)
  4290. exp: exp . "-" exp_hi (2)
  4291. \end{lstlisting}
  4292. We scan the next input token \code{")"}, placing the following dotted
  4293. rule in slot $6$.
  4294. \begin{lstlisting}[escapechar=$]
  4295. stmt: "print" "(" exp ")" . (0)
  4296. \end{lstlisting}
  4297. This triggers the completion of \code{stmt} in slot $0$
  4298. \begin{lstlisting}
  4299. stmt_list: stmt . NEWLINE stmt_list (0)
  4300. \end{lstlisting}
  4301. The last input token is a \code{NEWLINE}, so we advance the period
  4302. and place the new dotted rule in slot $7$.
  4303. \begin{lstlisting}
  4304. stmt_list: stmt NEWLINE . stmt_list (0)
  4305. \end{lstlisting}
  4306. We are close to the end of parsing the input!
  4307. The period is before the \code{stmt\_list} nonterminal, so we
  4308. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4309. \begin{lstlisting}
  4310. stmt_list: . (7)
  4311. stmt_list: . stmt NEWLINE stmt_list (7)
  4312. stmt: . "print" "(" exp ")" (7)
  4313. stmt: . exp (7)
  4314. \end{lstlisting}
  4315. There is immediately an opportunity for completion of \code{stmt\_list},
  4316. so we add the following to slot $7$.
  4317. \begin{lstlisting}
  4318. stmt_list: stmt NEWLINE stmt_list . (0)
  4319. \end{lstlisting}
  4320. This triggers another completion action for \code{stmt\_list} in slot $0$
  4321. \begin{lstlisting}
  4322. lang_int: stmt_list . (0)
  4323. \end{lstlisting}
  4324. which in turn completes \code{lang\_int}, the start symbol of the
  4325. grammar, so the parsing of the input is complete.
  4326. For reference, we now give a general description of the Earley
  4327. algorithm.
  4328. \begin{enumerate}
  4329. \item The algorithm begins by initializing slot $0$ of the chart with the
  4330. grammar rule for the start symbol, placing a period at the beginning
  4331. of the right-hand side, and recording its starting position as $0$.
  4332. \item The algorithm repeatedly applies the following three kinds of
  4333. actions for as long as there are opportunities to do so.
  4334. \begin{itemize}
  4335. \item Prediction: if there is a dotted rule in slot $k$ whose period
  4336. comes before a nonterminal, add all the rules for that nonterminal
  4337. into slot $k$, placing a period at the beginning of their
  4338. right-hand sides, and recording their starting position as
  4339. $k$.
  4340. \item Scanning: If the token at position $k$ of the input string
  4341. matches the symbol after the period in a dotted rule in slot $k$
  4342. of the chart, advance the prior in the dotted rule, adding
  4343. the result to slot $k+1$.
  4344. \item Completion: If a dotted rule in slot $k$ has a period at the
  4345. end, consider the rules in the slot corresponding to the starting
  4346. position of the completed rule. If any of those rules have a
  4347. nonterminal following their period that matches the left-hand side
  4348. of the completed rule, then advance their period, placing the new
  4349. dotted rule in slot $k$.
  4350. \end{itemize}
  4351. While repeating these three actions, take care to never add
  4352. duplicate dotted rules to the chart.
  4353. \end{enumerate}
  4354. We have described how the Earley algorithm recognizes that an input
  4355. string matches a grammar, but we have not described how it builds a
  4356. parse tree. The basic idea is simple, but it turns out that building
  4357. parse trees in an efficient way is more complex, requiring a data
  4358. structure called a shared packed parse forest~\citep{Tomita:1985qr}.
  4359. The simple idea is to attach a partial parse tree to every dotted
  4360. rule. Initially, the tree node associated with a dotted rule has no
  4361. children. As the period moves to the right, the nodes from the
  4362. subparses are added as children to this tree node.
  4363. As mentioned at the beginning of this section, the Earley algorithm is
  4364. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4365. files that contain thousands of tokens in a reasonable amount of time,
  4366. but not millions. In the next section we discuss the LALR(1) parsing
  4367. algorithm, which has time complexity $O(n)$, making it practical to
  4368. use with even the largest of input files.
  4369. \section{The LALR(1) Algorithm}
  4370. \label{sec:lalr}
  4371. The LALR(1) algorithm can be viewed as a two phase approach in which
  4372. it first compiles the grammar into a state machine and then runs the
  4373. state machine to parse the input string. The state machine also uses
  4374. a stack to record its progress in parsing the input string. Each
  4375. element of the stack is a pair: a state number and a grammar symbol (a
  4376. terminal or nonterminal). The symbol characterizes the input that has
  4377. been parsed so-far and the state number is used to remember how to
  4378. proceed once the next symbol-worth of input has been parsed. Each
  4379. state in the machine represents where the parser stands in the parsing
  4380. process with respect to certain grammar rules. In particular, each
  4381. state is associated with a set of dotted rules.
  4382. Figure~\ref{fig:shift-reduce} shows an example LALR(1) parse table
  4383. generated by Lark for the following simple but amiguous grammar:
  4384. \begin{lstlisting}[escapechar=$]
  4385. exp: INT
  4386. | exp "+" exp
  4387. stmt: "print" exp
  4388. start: stmt
  4389. \end{lstlisting}
  4390. %% When PLY generates a parse table, it also
  4391. %% outputs a textual representation of the parse table to the file
  4392. %% \texttt{parser.out} which is useful for debugging purposes.
  4393. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4394. read in a \lstinline{PRINT} token, so the top of the stack is
  4395. \lstinline{(1,PRINT)}. The parser is part of the way through parsing
  4396. the input according to grammar rule 1, which is signified by showing
  4397. rule 1 with a period after the \code{PRINT} token and before the
  4398. \code{exp} nonterminal. A rule with a period in it is called an
  4399. \emph{item}. There are several rules that could apply next, both rule
  4400. 2 and 3, so state 1 also shows those rules with a period at the
  4401. beginning of their right-hand sides. The edges between states indicate
  4402. which transitions the machine should make depending on the next input
  4403. token. So, for example, if the next input token is \code{INT} then the
  4404. parser will push \code{INT} and the target state 4 on the stack and
  4405. transition to state 4. Suppose we are now at the end of the input. In
  4406. state 4 it says we should reduce by rule 3, so we pop from the stack
  4407. the same number of items as the number of symbols in the right-hand
  4408. side of the rule, in this case just one. We then momentarily jump to
  4409. the state at the top of the stack (state 1) and then follow the goto
  4410. edge that corresponds to the left-hand side of the rule we just
  4411. reduced by, in this case \code{exp}, so we arrive at state 3. (A
  4412. slightly longer example parse is shown in
  4413. Figure~\ref{fig:shift-reduce}.)
  4414. \begin{figure}[htbp]
  4415. \centering
  4416. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4417. \caption{An LALR(1) parse table and a trace of an example run.}
  4418. \label{fig:shift-reduce}
  4419. \end{figure}
  4420. In general, the shift-reduce algorithm works as follows. Look at the
  4421. next input token.
  4422. \begin{itemize}
  4423. \item If there there is a shift edge for the input token, push the
  4424. edge's target state and the input token on the stack and proceed to
  4425. the edge's target state.
  4426. \item If there is a reduce action for the input token, pop $k$
  4427. elements from the stack, where $k$ is the number of symbols in the
  4428. right-hand side of the rule being reduced. Jump to the state at the
  4429. top of the stack and then follow the goto edge for the nonterminal
  4430. that matches the left-hand side of the rule we're reducing by. Push
  4431. the edge's target state and the nonterminal on the stack.
  4432. \end{itemize}
  4433. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4434. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4435. algorithm does not know which action to take in this case. When a
  4436. state has both a shift and a reduce action for the same token, we say
  4437. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4438. will arise, for example, when trying to parse the input
  4439. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4440. the parser will be in state 6, and it will not know whether to
  4441. reduce to form an \emph{exp} of \lstinline{1 + 2}, or whether it
  4442. should proceed by shifting the next \lstinline{+} from the input.
  4443. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4444. arises when there are two reduce actions in a state for the same
  4445. token. To understand which grammars gives rise to shift/reduce and
  4446. reduce/reduce conflicts, it helps to know how the parse table is
  4447. generated from the grammar, which we discuss next.
  4448. The parse table is generated one state at a time. State 0 represents
  4449. the start of the parser. We add the grammar rule for the start symbol
  4450. to this state with a period at the beginning of the right-hand side,
  4451. similar to the initialization phase of the Earley parser. If the
  4452. period appears immediately before another nonterminal, we add all the
  4453. rules with that nonterminal on the left-hand side. Again, we place a
  4454. period at the beginning of the right-hand side of each the new
  4455. rules. This process called \emph{state closure} is continued
  4456. until there are no more rules to add (similar to the prediction
  4457. actions of an Earley parser). We then examine each dotted rule in the
  4458. current state $I$. Suppose a dotted rule has the form $A ::=
  4459. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4460. are sequences of symbols. We create a new state, call it $J$. If $X$
  4461. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4462. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4463. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4464. state $J$. We start by adding all dotted rules from state $I$ that
  4465. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4466. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4467. the period moved past the $X$. (This is analogous to completion in
  4468. the Earley algorithm.) We then perform state closure on $J$. This
  4469. process repeats until there are no more states or edges to add.
  4470. We then mark states as accepting states if they have a dotted rule
  4471. that is the start rule with a period at the end. Also, to add
  4472. in the reduce actions, we look for any state containing a dotted rule
  4473. with a period at the end. Let $n$ be the rule number for this dotted
  4474. rule. We then put a reduce $n$ action into that state for every token
  4475. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4476. dotted rule with a period at the end. We therefore put a reduce by
  4477. rule 3 action into state 4 for every
  4478. token.
  4479. %% (Figure~\ref{fig:shift-reduce} does not show a reduce rule for
  4480. %% \code{INT} in state 4 because this grammar does not allow two
  4481. %% consecutive \code{INT} tokens in the input. We will not go into how
  4482. %% this can be figured out, but in any event it does no harm to have a
  4483. %% reduce rule for \code{INT} in state 4; it just means the input will be
  4484. %% rejected at a later point in the parsing process.)
  4485. When inserting reduce actions, take care to spot any shift/reduce or
  4486. reduce/reduce conflicts. If there are any, abort the construction of
  4487. the parse table.
  4488. \begin{exercise}
  4489. \normalfont\normalsize
  4490. %
  4491. On a piece of paper, walk through the parse table generation process
  4492. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4493. your results against parse table in figure~\ref{fig:shift-reduce}.
  4494. \end{exercise}
  4495. \begin{exercise}
  4496. \normalfont\normalsize
  4497. %
  4498. Change the parser in your compiler for \LangVar{} to set the
  4499. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4500. all the \LangVar{} programs that you have created. In doing so, Lark
  4501. may signal an error due to shift/reduce or reduce/reduce conflicts
  4502. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4503. remove those conflicts.
  4504. \end{exercise}
  4505. \section{Further Reading}
  4506. In this chapter we have just scratched the surface of the field of
  4507. parsing, with the study of a very general put less efficient algorithm
  4508. (Earley) and with a more limited but highly efficient algorithm
  4509. (LALR). There are many more algorithms, and classes of grammars, that
  4510. fall between these two. We recommend the reader to \citet{Aho:2006wb}
  4511. for a thorough treatment of parsing.
  4512. Regarding lexical analysis, we described the specification language,
  4513. the regular expressions, but not the algorithms for recognizing them.
  4514. In short, regular expressions can be translated to nondeterministic
  4515. finite automata, which in turn are translated to finite automata. We
  4516. refer the reader again to \citet{Aho:2006wb} for all the details of
  4517. lexical analysis.
  4518. \fi}
  4519. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4520. \chapter{Register Allocation}
  4521. \label{ch:register-allocation-Lvar}
  4522. \setcounter{footnote}{0}
  4523. \index{subject}{register allocation}
  4524. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4525. storing variables on the procedure call stack. The CPU may require tens
  4526. to hundreds of cycles to access a location on the stack, whereas
  4527. accessing a register takes only a single cycle. In this chapter we
  4528. improve the efficiency of our generated code by storing some variables
  4529. in registers. The goal of register allocation is to fit as many
  4530. variables into registers as possible. Some programs have more
  4531. variables than registers, so we cannot always map each variable to a
  4532. different register. Fortunately, it is common for different variables
  4533. to be in use during different periods of time during program
  4534. execution, and in those cases we can map multiple variables to the
  4535. same register.
  4536. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4537. example. The source program is on the left and the output of
  4538. instruction selection is on the right. The program is almost
  4539. completely in the x86 assembly language, but it still uses variables.
  4540. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4541. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4542. the other hand, is used only after this point, so \code{x} and
  4543. \code{z} could share the same register.
  4544. \begin{figure}
  4545. \begin{tcolorbox}[colback=white]
  4546. \begin{minipage}{0.45\textwidth}
  4547. Example \LangVar{} program:
  4548. % var_test_28.rkt
  4549. {\if\edition\racketEd
  4550. \begin{lstlisting}
  4551. (let ([v 1])
  4552. (let ([w 42])
  4553. (let ([x (+ v 7)])
  4554. (let ([y x])
  4555. (let ([z (+ x w)])
  4556. (+ z (- y)))))))
  4557. \end{lstlisting}
  4558. \fi}
  4559. {\if\edition\pythonEd
  4560. \begin{lstlisting}
  4561. v = 1
  4562. w = 42
  4563. x = v + 7
  4564. y = x
  4565. z = x + w
  4566. print(z + (- y))
  4567. \end{lstlisting}
  4568. \fi}
  4569. \end{minipage}
  4570. \begin{minipage}{0.45\textwidth}
  4571. After instruction selection:
  4572. {\if\edition\racketEd
  4573. \begin{lstlisting}
  4574. locals-types:
  4575. x : Integer, y : Integer,
  4576. z : Integer, t : Integer,
  4577. v : Integer, w : Integer
  4578. start:
  4579. movq $1, v
  4580. movq $42, w
  4581. movq v, x
  4582. addq $7, x
  4583. movq x, y
  4584. movq x, z
  4585. addq w, z
  4586. movq y, t
  4587. negq t
  4588. movq z, %rax
  4589. addq t, %rax
  4590. jmp conclusion
  4591. \end{lstlisting}
  4592. \fi}
  4593. {\if\edition\pythonEd
  4594. \begin{lstlisting}
  4595. movq $1, v
  4596. movq $42, w
  4597. movq v, x
  4598. addq $7, x
  4599. movq x, y
  4600. movq x, z
  4601. addq w, z
  4602. movq y, tmp_0
  4603. negq tmp_0
  4604. movq z, tmp_1
  4605. addq tmp_0, tmp_1
  4606. movq tmp_1, %rdi
  4607. callq print_int
  4608. \end{lstlisting}
  4609. \fi}
  4610. \end{minipage}
  4611. \end{tcolorbox}
  4612. \caption{A running example for register allocation.}
  4613. \label{fig:reg-eg}
  4614. \end{figure}
  4615. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4616. compute where a variable is in use. Once we have that information, we
  4617. compute which variables are in use at the same time, i.e., which ones
  4618. \emph{interfere}\index{subject}{interfere} with each other, and
  4619. represent this relation as an undirected graph whose vertices are
  4620. variables and edges indicate when two variables interfere
  4621. (section~\ref{sec:build-interference}). We then model register
  4622. allocation as a graph coloring problem
  4623. (section~\ref{sec:graph-coloring}).
  4624. If we run out of registers despite these efforts, we place the
  4625. remaining variables on the stack, similarly to how we handled
  4626. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4627. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4628. location. The decision to spill a variable is handled as part of the
  4629. graph coloring process.
  4630. We make the simplifying assumption that each variable is assigned to
  4631. one location (a register or stack address). A more sophisticated
  4632. approach is to assign a variable to one or more locations in different
  4633. regions of the program. For example, if a variable is used many times
  4634. in short sequence and then used again only after many other
  4635. instructions, it could be more efficient to assign the variable to a
  4636. register during the initial sequence and then move it to the stack for
  4637. the rest of its lifetime. We refer the interested reader to
  4638. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4639. approach.
  4640. % discuss prioritizing variables based on how much they are used.
  4641. \section{Registers and Calling Conventions}
  4642. \label{sec:calling-conventions}
  4643. \index{subject}{calling conventions}
  4644. As we perform register allocation, we must be aware of the
  4645. \emph{calling conventions} \index{subject}{calling conventions} that
  4646. govern how functions calls are performed in x86.
  4647. %
  4648. Even though \LangVar{} does not include programmer-defined functions,
  4649. our generated code includes a \code{main} function that is called by
  4650. the operating system and our generated code contains calls to the
  4651. \code{read\_int} function.
  4652. Function calls require coordination between two pieces of code that
  4653. may be written by different programmers or generated by different
  4654. compilers. Here we follow the System V calling conventions that are
  4655. used by the GNU C compiler on Linux and
  4656. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4657. %
  4658. The calling conventions include rules about how functions share the
  4659. use of registers. In particular, the caller is responsible for freeing
  4660. some registers prior to the function call for use by the callee.
  4661. These are called the \emph{caller-saved registers}
  4662. \index{subject}{caller-saved registers}
  4663. and they are
  4664. \begin{lstlisting}
  4665. rax rcx rdx rsi rdi r8 r9 r10 r11
  4666. \end{lstlisting}
  4667. On the other hand, the callee is responsible for preserving the values
  4668. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4669. which are
  4670. \begin{lstlisting}
  4671. rsp rbp rbx r12 r13 r14 r15
  4672. \end{lstlisting}
  4673. We can think about this caller/callee convention from two points of
  4674. view, the caller view and the callee view, as follows:
  4675. \begin{itemize}
  4676. \item The caller should assume that all the caller-saved registers get
  4677. overwritten with arbitrary values by the callee. On the other hand,
  4678. the caller can safely assume that all the callee-saved registers
  4679. retain their original values.
  4680. \item The callee can freely use any of the caller-saved registers.
  4681. However, if the callee wants to use a callee-saved register, the
  4682. callee must arrange to put the original value back in the register
  4683. prior to returning to the caller. This can be accomplished by saving
  4684. the value to the stack in the prelude of the function and restoring
  4685. the value in the conclusion of the function.
  4686. \end{itemize}
  4687. In x86, registers are also used for passing arguments to a function
  4688. and for the return value. In particular, the first six arguments of a
  4689. function are passed in the following six registers, in this order.
  4690. \index{subject}{argument-passing registers}
  4691. \index{subject}{parameter-passing registers}
  4692. \begin{lstlisting}
  4693. rdi rsi rdx rcx r8 r9
  4694. \end{lstlisting}
  4695. If there are more than six arguments, the convention is to use
  4696. space on the frame of the caller for the rest of the
  4697. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4698. need more than six arguments.
  4699. %
  4700. \racket{For now, the only function we care about is \code{read\_int},
  4701. which takes zero arguments.}
  4702. %
  4703. \python{For now, the only functions we care about are \code{read\_int}
  4704. and \code{print\_int}, which take zero and one argument, respectively.}
  4705. %
  4706. The register \code{rax} is used for the return value of a function.
  4707. The next question is how these calling conventions impact register
  4708. allocation. Consider the \LangVar{} program presented in
  4709. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4710. example from the caller point of view and then from the callee point
  4711. of view. We refer to a variable that is in use during a function call
  4712. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4713. The program makes two calls to \READOP{}. The variable \code{x} is
  4714. call-live because it is in use during the second call to \READOP{}; we
  4715. must ensure that the value in \code{x} does not get overwritten during
  4716. the call to \READOP{}. One obvious approach is to save all the values
  4717. that reside in caller-saved registers to the stack prior to each
  4718. function call and to restore them after each call. That way, if the
  4719. register allocator chooses to assign \code{x} to a caller-saved
  4720. register, its value will be preserved across the call to \READOP{}.
  4721. However, saving and restoring to the stack is relatively slow. If
  4722. \code{x} is not used many times, it may be better to assign \code{x}
  4723. to a stack location in the first place. Or better yet, if we can
  4724. arrange for \code{x} to be placed in a callee-saved register, then it
  4725. won't need to be saved and restored during function calls.
  4726. The approach that we recommend for call-live variables is either to
  4727. assign them to callee-saved registers or to spill them to the
  4728. stack. On the other hand, for variables that are not call-live, we try
  4729. the following alternatives in order: (1) look for an available
  4730. caller-saved register (to leave room for other variables in the
  4731. callee-saved register), (2) look for a callee-saved register, and (3)
  4732. spill the variable to the stack.
  4733. It is straightforward to implement this approach in a graph coloring
  4734. register allocator. First, we know which variables are call-live
  4735. because we already need to compute which variables are in use at every
  4736. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  4737. we build the interference graph
  4738. (section~\ref{sec:build-interference}), we can place an edge between
  4739. each of the call-live variables and the caller-saved registers in the
  4740. interference graph. This will prevent the graph coloring algorithm
  4741. from assigning them to caller-saved registers.
  4742. Returning to the example in
  4743. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4744. generated x86 code on the right-hand side. Notice that variable
  4745. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  4746. is already in a safe place during the second call to
  4747. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  4748. \code{rcx}, a caller-saved register, because \code{y} is not a
  4749. call-live variable.
  4750. Next we analyze the example from the callee point of view, focusing on
  4751. the prelude and conclusion of the \code{main} function. As usual, the
  4752. prelude begins with saving the \code{rbp} register to the stack and
  4753. setting the \code{rbp} to the current stack pointer. We now know why
  4754. it is necessary to save the \code{rbp}: it is a callee-saved register.
  4755. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  4756. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  4757. (\code{x}). The other callee-saved registers are not saved in the
  4758. prelude because they are not used. The prelude subtracts 8 bytes from
  4759. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4760. conclusion, we see that \code{rbx} is restored from the stack with a
  4761. \code{popq} instruction.
  4762. \index{subject}{prelude}\index{subject}{conclusion}
  4763. \begin{figure}[tp]
  4764. \begin{tcolorbox}[colback=white]
  4765. \begin{minipage}{0.45\textwidth}
  4766. Example \LangVar{} program:
  4767. %var_test_14.rkt
  4768. {\if\edition\racketEd
  4769. \begin{lstlisting}
  4770. (let ([x (read)])
  4771. (let ([y (read)])
  4772. (+ (+ x y) 42)))
  4773. \end{lstlisting}
  4774. \fi}
  4775. {\if\edition\pythonEd
  4776. \begin{lstlisting}
  4777. x = input_int()
  4778. y = input_int()
  4779. print((x + y) + 42)
  4780. \end{lstlisting}
  4781. \fi}
  4782. \end{minipage}
  4783. \begin{minipage}{0.45\textwidth}
  4784. Generated x86 assembly:
  4785. {\if\edition\racketEd
  4786. \begin{lstlisting}
  4787. start:
  4788. callq read_int
  4789. movq %rax, %rbx
  4790. callq read_int
  4791. movq %rax, %rcx
  4792. addq %rcx, %rbx
  4793. movq %rbx, %rax
  4794. addq $42, %rax
  4795. jmp _conclusion
  4796. .globl main
  4797. main:
  4798. pushq %rbp
  4799. movq %rsp, %rbp
  4800. pushq %rbx
  4801. subq $8, %rsp
  4802. jmp start
  4803. conclusion:
  4804. addq $8, %rsp
  4805. popq %rbx
  4806. popq %rbp
  4807. retq
  4808. \end{lstlisting}
  4809. \fi}
  4810. {\if\edition\pythonEd
  4811. \begin{lstlisting}
  4812. .globl main
  4813. main:
  4814. pushq %rbp
  4815. movq %rsp, %rbp
  4816. pushq %rbx
  4817. subq $8, %rsp
  4818. callq read_int
  4819. movq %rax, %rbx
  4820. callq read_int
  4821. movq %rax, %rcx
  4822. movq %rbx, %rdx
  4823. addq %rcx, %rdx
  4824. movq %rdx, %rcx
  4825. addq $42, %rcx
  4826. movq %rcx, %rdi
  4827. callq print_int
  4828. addq $8, %rsp
  4829. popq %rbx
  4830. popq %rbp
  4831. retq
  4832. \end{lstlisting}
  4833. \fi}
  4834. \end{minipage}
  4835. \end{tcolorbox}
  4836. \caption{An example with function calls.}
  4837. \label{fig:example-calling-conventions}
  4838. \end{figure}
  4839. %\clearpage
  4840. \section{Liveness Analysis}
  4841. \label{sec:liveness-analysis-Lvar}
  4842. \index{subject}{liveness analysis}
  4843. The \code{uncover\_live} \racket{pass}\python{function} performs
  4844. \emph{liveness analysis}; that is, it discovers which variables are
  4845. in use in different regions of a program.
  4846. %
  4847. A variable or register is \emph{live} at a program point if its
  4848. current value is used at some later point in the program. We refer to
  4849. variables, stack locations, and registers collectively as
  4850. \emph{locations}.
  4851. %
  4852. Consider the following code fragment in which there are two writes to
  4853. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4854. time?
  4855. \begin{center}
  4856. \begin{minipage}{0.96\textwidth}
  4857. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4858. movq $5, a
  4859. movq $30, b
  4860. movq a, c
  4861. movq $10, b
  4862. addq b, c
  4863. \end{lstlisting}
  4864. \end{minipage}
  4865. \end{center}
  4866. The answer is no, because \code{a} is live from line 1 to 3 and
  4867. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4868. line 2 is never used because it is overwritten (line 4) before the
  4869. next read (line 5).
  4870. The live locations for each instruction can be computed by traversing
  4871. the instruction sequence back to front (i.e., backward in execution
  4872. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4873. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4874. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4875. locations before instruction $I_k$. \racket{We recommend representing
  4876. these sets with the Racket \code{set} data structure described in
  4877. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4878. with the Python
  4879. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4880. data structure.}
  4881. {\if\edition\racketEd
  4882. \begin{figure}[tp]
  4883. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4884. \small
  4885. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4886. A \emph{set} is an unordered collection of elements without duplicates.
  4887. Here are some of the operations defined on sets.
  4888. \index{subject}{set}
  4889. \begin{description}
  4890. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4891. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4892. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4893. difference of the two sets.
  4894. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4895. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4896. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4897. \end{description}
  4898. \end{tcolorbox}
  4899. %\end{wrapfigure}
  4900. \caption{The \code{set} data structure.}
  4901. \label{fig:set}
  4902. \end{figure}
  4903. \fi}
  4904. The live locations after an instruction are always the same as the
  4905. live locations before the next instruction.
  4906. \index{subject}{live-after} \index{subject}{live-before}
  4907. \begin{equation} \label{eq:live-after-before-next}
  4908. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4909. \end{equation}
  4910. To start things off, there are no live locations after the last
  4911. instruction, so
  4912. \begin{equation}\label{eq:live-last-empty}
  4913. L_{\mathsf{after}}(n) = \emptyset
  4914. \end{equation}
  4915. We then apply the following rule repeatedly, traversing the
  4916. instruction sequence back to front.
  4917. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4918. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4919. \end{equation}
  4920. where $W(k)$ are the locations written to by instruction $I_k$, and
  4921. $R(k)$ are the locations read by instruction $I_k$.
  4922. {\if\edition\racketEd
  4923. %
  4924. There is a special case for \code{jmp} instructions. The locations
  4925. that are live before a \code{jmp} should be the locations in
  4926. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4927. maintaining an alist named \code{label->live} that maps each label to
  4928. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4929. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4930. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4931. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4932. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4933. %
  4934. \fi}
  4935. Let us walk through the previous example, applying these formulas
  4936. starting with the instruction on line 5 of the code fragment. We
  4937. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4938. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4939. $\emptyset$ because it is the last instruction
  4940. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4941. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4942. variables \code{b} and \code{c}
  4943. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4944. \[
  4945. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4946. \]
  4947. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4948. the live-before set from line 5 to be the live-after set for this
  4949. instruction (formula~\eqref{eq:live-after-before-next}).
  4950. \[
  4951. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4952. \]
  4953. This move instruction writes to \code{b} and does not read from any
  4954. variables, so we have the following live-before set
  4955. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4956. \[
  4957. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4958. \]
  4959. The live-before for instruction \code{movq a, c}
  4960. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4961. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4962. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4963. variable that is not live and does not read from a variable.
  4964. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4965. because it writes to variable \code{a}.
  4966. \begin{figure}[tbp]
  4967. \centering
  4968. \begin{tcolorbox}[colback=white]
  4969. \hspace{10pt}
  4970. \begin{minipage}{0.4\textwidth}
  4971. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4972. movq $5, a
  4973. movq $30, b
  4974. movq a, c
  4975. movq $10, b
  4976. addq b, c
  4977. \end{lstlisting}
  4978. \end{minipage}
  4979. \vrule\hspace{10pt}
  4980. \begin{minipage}{0.45\textwidth}
  4981. \begin{align*}
  4982. L_{\mathsf{before}}(1)= \emptyset,
  4983. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4984. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4985. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4986. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4987. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4988. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4989. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4990. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4991. L_{\mathsf{after}}(5)= \emptyset
  4992. \end{align*}
  4993. \end{minipage}
  4994. \end{tcolorbox}
  4995. \caption{Example output of liveness analysis on a short example.}
  4996. \label{fig:liveness-example-0}
  4997. \end{figure}
  4998. \begin{exercise}\normalfont\normalsize
  4999. Perform liveness analysis by hand on the running example in
  5000. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5001. sets for each instruction. Compare your answers to the solution
  5002. shown in figure~\ref{fig:live-eg}.
  5003. \end{exercise}
  5004. \begin{figure}[tp]
  5005. \hspace{20pt}
  5006. \begin{minipage}{0.55\textwidth}
  5007. \begin{tcolorbox}[colback=white]
  5008. {\if\edition\racketEd
  5009. \begin{lstlisting}
  5010. |$\{\ttm{rsp}\}$|
  5011. movq $1, v
  5012. |$\{\ttm{v},\ttm{rsp}\}$|
  5013. movq $42, w
  5014. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5015. movq v, x
  5016. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5017. addq $7, x
  5018. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5019. movq x, y
  5020. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5021. movq x, z
  5022. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5023. addq w, z
  5024. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5025. movq y, t
  5026. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5027. negq t
  5028. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5029. movq z, %rax
  5030. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5031. addq t, %rax
  5032. |$\{\ttm{rax},\ttm{rsp}\}$|
  5033. jmp conclusion
  5034. \end{lstlisting}
  5035. \fi}
  5036. {\if\edition\pythonEd
  5037. \begin{lstlisting}
  5038. movq $1, v
  5039. |$\{\ttm{v}\}$|
  5040. movq $42, w
  5041. |$\{\ttm{w}, \ttm{v}\}$|
  5042. movq v, x
  5043. |$\{\ttm{w}, \ttm{x}\}$|
  5044. addq $7, x
  5045. |$\{\ttm{w}, \ttm{x}\}$|
  5046. movq x, y
  5047. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5048. movq x, z
  5049. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5050. addq w, z
  5051. |$\{\ttm{y}, \ttm{z}\}$|
  5052. movq y, tmp_0
  5053. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5054. negq tmp_0
  5055. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5056. movq z, tmp_1
  5057. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5058. addq tmp_0, tmp_1
  5059. |$\{\ttm{tmp\_1}\}$|
  5060. movq tmp_1, %rdi
  5061. |$\{\ttm{rdi}\}$|
  5062. callq print_int
  5063. |$\{\}$|
  5064. \end{lstlisting}
  5065. \fi}
  5066. \end{tcolorbox}
  5067. \end{minipage}
  5068. \caption{The running example annotated with live-after sets.}
  5069. \label{fig:live-eg}
  5070. \end{figure}
  5071. \begin{exercise}\normalfont\normalsize
  5072. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5073. %
  5074. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5075. field of the \code{Block} structure.}
  5076. %
  5077. \python{Return a dictionary that maps each instruction to its
  5078. live-after set.}
  5079. %
  5080. \racket{We recommend creating an auxiliary function that takes a list
  5081. of instructions and an initial live-after set (typically empty) and
  5082. returns the list of live-after sets.}
  5083. %
  5084. We recommend creating auxiliary functions to (1) compute the set
  5085. of locations that appear in an \Arg{}, (2) compute the locations read
  5086. by an instruction (the $R$ function), and (3) the locations written by
  5087. an instruction (the $W$ function). The \code{callq} instruction should
  5088. include all the caller-saved registers in its write set $W$ because
  5089. the calling convention says that those registers may be written to
  5090. during the function call. Likewise, the \code{callq} instruction
  5091. should include the appropriate argument-passing registers in its
  5092. read set $R$, depending on the arity of the function being
  5093. called. (This is why the abstract syntax for \code{callq} includes the
  5094. arity.)
  5095. \end{exercise}
  5096. %\clearpage
  5097. \section{Build the Interference Graph}
  5098. \label{sec:build-interference}
  5099. {\if\edition\racketEd
  5100. \begin{figure}[tp]
  5101. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5102. \small
  5103. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5104. A \emph{graph} is a collection of vertices and edges where each
  5105. edge connects two vertices. A graph is \emph{directed} if each
  5106. edge points from a source to a target. Otherwise the graph is
  5107. \emph{undirected}.
  5108. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5109. \begin{description}
  5110. %% We currently don't use directed graphs. We instead use
  5111. %% directed multi-graphs. -Jeremy
  5112. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5113. directed graph from a list of edges. Each edge is a list
  5114. containing the source and target vertex.
  5115. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5116. undirected graph from a list of edges. Each edge is represented by
  5117. a list containing two vertices.
  5118. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5119. inserts a vertex into the graph.
  5120. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5121. inserts an edge between the two vertices.
  5122. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5123. returns a sequence of vertices adjacent to the vertex.
  5124. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5125. returns a sequence of all vertices in the graph.
  5126. \end{description}
  5127. \end{tcolorbox}
  5128. %\end{wrapfigure}
  5129. \caption{The Racket \code{graph} package.}
  5130. \label{fig:graph}
  5131. \end{figure}
  5132. \fi}
  5133. On the basis of the liveness analysis, we know where each location is
  5134. live. However, during register allocation, we need to answer
  5135. questions of the specific form: are locations $u$ and $v$ live at the
  5136. same time? (If so, they cannot be assigned to the same register.) To
  5137. make this question more efficient to answer, we create an explicit
  5138. data structure, an \emph{interference
  5139. graph}\index{subject}{interference graph}. An interference graph is
  5140. an undirected graph that has an edge between two locations if they are
  5141. live at the same time, that is, if they interfere with each other.
  5142. %
  5143. \racket{We recommend using the Racket \code{graph} package
  5144. (figure~\ref{fig:graph}) to represent the interference graph.}
  5145. %
  5146. \python{We provide implementations of directed and undirected graph
  5147. data structures in the file \code{graph.py} of the support code.}
  5148. A straightforward way to compute the interference graph is to look at
  5149. the set of live locations between each instruction and add an edge to
  5150. the graph for every pair of variables in the same set. This approach
  5151. is less than ideal for two reasons. First, it can be expensive because
  5152. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5153. locations. Second, in the special case in which two locations hold the
  5154. same value (because one was assigned to the other), they can be live
  5155. at the same time without interfering with each other.
  5156. A better way to compute the interference graph is to focus on
  5157. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5158. must not overwrite something in a live location. So for each
  5159. instruction, we create an edge between the locations being written to
  5160. and the live locations. (However, a location never interferes with
  5161. itself.) For the \key{callq} instruction, we consider all the
  5162. caller-saved registers to have been written to, so an edge is added
  5163. between every live variable and every caller-saved register. Also, for
  5164. \key{movq} there is the special case of two variables holding the same
  5165. value. If a live variable $v$ is the same as the source of the
  5166. \key{movq}, then there is no need to add an edge between $v$ and the
  5167. destination, because they both hold the same value.
  5168. %
  5169. Hence we have the following two rules:
  5170. \begin{enumerate}
  5171. \item If instruction $I_k$ is a move instruction of the form
  5172. \key{movq} $s$\key{,} $d$, then for every $v \in
  5173. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5174. $(d,v)$.
  5175. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5176. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5177. $(d,v)$.
  5178. \end{enumerate}
  5179. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5180. these rules to each instruction. We highlight a few of the
  5181. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5182. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5183. so \code{v} interferes with \code{rsp}.}
  5184. %
  5185. \python{The first instruction is \lstinline{movq $1, v}, and the
  5186. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5187. no interference because $\ttm{v}$ is the destination of the move.}
  5188. %
  5189. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5190. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5191. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5192. %
  5193. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5194. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5195. $\ttm{x}$ interferes with \ttm{w}.}
  5196. %
  5197. \racket{The next instruction is \lstinline{movq x, y}, and the
  5198. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5199. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5200. \ttm{x} because \ttm{x} is the source of the move and therefore
  5201. \ttm{x} and \ttm{y} hold the same value.}
  5202. %
  5203. \python{The next instruction is \lstinline{movq x, y}, and the
  5204. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5205. applies, so \ttm{y} interferes with \ttm{w} but not
  5206. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5207. \ttm{x} and \ttm{y} hold the same value.}
  5208. %
  5209. Figure~\ref{fig:interference-results} lists the interference results
  5210. for all the instructions, and the resulting interference graph is
  5211. shown in figure~\ref{fig:interfere}.
  5212. \begin{figure}[tbp]
  5213. \begin{tcolorbox}[colback=white]
  5214. \begin{quote}
  5215. {\if\edition\racketEd
  5216. \begin{tabular}{ll}
  5217. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5218. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5219. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5220. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5221. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5222. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5223. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5224. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5225. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5226. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5227. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5228. \lstinline!jmp conclusion!& no interference.
  5229. \end{tabular}
  5230. \fi}
  5231. {\if\edition\pythonEd
  5232. \begin{tabular}{ll}
  5233. \lstinline!movq $1, v!& no interference\\
  5234. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5235. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5236. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5237. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5238. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5239. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5240. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5241. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5242. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5243. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5244. \lstinline!movq tmp_1, %rdi! & no interference \\
  5245. \lstinline!callq print_int!& no interference.
  5246. \end{tabular}
  5247. \fi}
  5248. \end{quote}
  5249. \end{tcolorbox}
  5250. \caption{Interference results for the running example.}
  5251. \label{fig:interference-results}
  5252. \end{figure}
  5253. \begin{figure}[tbp]
  5254. \begin{tcolorbox}[colback=white]
  5255. \large
  5256. {\if\edition\racketEd
  5257. \[
  5258. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5259. \node (rax) at (0,0) {$\ttm{rax}$};
  5260. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5261. \node (t1) at (0,2) {$\ttm{t}$};
  5262. \node (z) at (3,2) {$\ttm{z}$};
  5263. \node (x) at (6,2) {$\ttm{x}$};
  5264. \node (y) at (3,0) {$\ttm{y}$};
  5265. \node (w) at (6,0) {$\ttm{w}$};
  5266. \node (v) at (9,0) {$\ttm{v}$};
  5267. \draw (t1) to (rax);
  5268. \draw (t1) to (z);
  5269. \draw (z) to (y);
  5270. \draw (z) to (w);
  5271. \draw (x) to (w);
  5272. \draw (y) to (w);
  5273. \draw (v) to (w);
  5274. \draw (v) to (rsp);
  5275. \draw (w) to (rsp);
  5276. \draw (x) to (rsp);
  5277. \draw (y) to (rsp);
  5278. \path[-.,bend left=15] (z) edge node {} (rsp);
  5279. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5280. \draw (rax) to (rsp);
  5281. \end{tikzpicture}
  5282. \]
  5283. \fi}
  5284. {\if\edition\pythonEd
  5285. \[
  5286. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5287. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5288. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5289. \node (z) at (3,2) {$\ttm{z}$};
  5290. \node (x) at (6,2) {$\ttm{x}$};
  5291. \node (y) at (3,0) {$\ttm{y}$};
  5292. \node (w) at (6,0) {$\ttm{w}$};
  5293. \node (v) at (9,0) {$\ttm{v}$};
  5294. \draw (t0) to (t1);
  5295. \draw (t0) to (z);
  5296. \draw (z) to (y);
  5297. \draw (z) to (w);
  5298. \draw (x) to (w);
  5299. \draw (y) to (w);
  5300. \draw (v) to (w);
  5301. \end{tikzpicture}
  5302. \]
  5303. \fi}
  5304. \end{tcolorbox}
  5305. \caption{The interference graph of the example program.}
  5306. \label{fig:interfere}
  5307. \end{figure}
  5308. %% Our next concern is to choose a data structure for representing the
  5309. %% interference graph. There are many choices for how to represent a
  5310. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  5311. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  5312. %% data structure is to study the algorithm that uses the data structure,
  5313. %% determine what operations need to be performed, and then choose the
  5314. %% data structure that provide the most efficient implementations of
  5315. %% those operations. Often times the choice of data structure can have an
  5316. %% effect on the time complexity of the algorithm, as it does here. If
  5317. %% you skim the next section, you will see that the register allocation
  5318. %% algorithm needs to ask the graph for all its vertices and, given a
  5319. %% vertex, it needs to known all the adjacent vertices. Thus, the
  5320. %% correct choice of graph representation is that of an adjacency
  5321. %% list. There are helper functions in \code{utilities.rkt} for
  5322. %% representing graphs using the adjacency list representation:
  5323. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  5324. %% (Appendix~\ref{appendix:utilities}).
  5325. %% %
  5326. %% \margincomment{\footnotesize To do: change to use the
  5327. %% Racket graph library. \\ --Jeremy}
  5328. %% %
  5329. %% In particular, those functions use a hash table to map each vertex to
  5330. %% the set of adjacent vertices, and the sets are represented using
  5331. %% Racket's \key{set}, which is also a hash table.
  5332. \begin{exercise}\normalfont\normalsize
  5333. \racket{Implement the compiler pass named \code{build\_interference} according
  5334. to the algorithm suggested here. We recommend using the Racket
  5335. \code{graph} package to create and inspect the interference graph.
  5336. The output graph of this pass should be stored in the $\itm{info}$ field of
  5337. the program, under the key \code{conflicts}.}
  5338. %
  5339. \python{Implement a function named \code{build\_interference}
  5340. according to the algorithm suggested above that
  5341. returns the interference graph.}
  5342. \end{exercise}
  5343. \section{Graph Coloring via Sudoku}
  5344. \label{sec:graph-coloring}
  5345. \index{subject}{graph coloring}
  5346. \index{subject}{sudoku}
  5347. \index{subject}{color}
  5348. We come to the main event discussed in this chapter, mapping variables
  5349. to registers and stack locations. Variables that interfere with each
  5350. other must be mapped to different locations. In terms of the
  5351. interference graph, this means that adjacent vertices must be mapped
  5352. to different locations. If we think of locations as colors, the
  5353. register allocation problem becomes the graph coloring
  5354. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5355. The reader may be more familiar with the graph coloring problem than he
  5356. or she realizes; the popular game of sudoku is an instance of the
  5357. graph coloring problem. The following describes how to build a graph
  5358. out of an initial sudoku board.
  5359. \begin{itemize}
  5360. \item There is one vertex in the graph for each sudoku square.
  5361. \item There is an edge between two vertices if the corresponding squares
  5362. are in the same row, in the same column, or in the same $3\times 3$ region.
  5363. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5364. \item On the basis of the initial assignment of numbers to squares on the
  5365. sudoku board, assign the corresponding colors to the corresponding
  5366. vertices in the graph.
  5367. \end{itemize}
  5368. If you can color the remaining vertices in the graph with the nine
  5369. colors, then you have also solved the corresponding game of sudoku.
  5370. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5371. the corresponding graph with colored vertices. Here we use a
  5372. monochrome representation of colors, mapping the sudoku number 1 to
  5373. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5374. of the vertices (the colored ones) because showing edges for all the
  5375. vertices would make the graph unreadable.
  5376. \begin{figure}[tbp]
  5377. \begin{tcolorbox}[colback=white]
  5378. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5379. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5380. \end{tcolorbox}
  5381. \caption{A sudoku game board and the corresponding colored graph.}
  5382. \label{fig:sudoku-graph}
  5383. \end{figure}
  5384. Some techniques for playing sudoku correspond to heuristics used in
  5385. graph coloring algorithms. For example, one of the basic techniques
  5386. for sudoku is called Pencil Marks. The idea is to use a process of
  5387. elimination to determine what numbers are no longer available for a
  5388. square and to write those numbers in the square (writing very
  5389. small). For example, if the number $1$ is assigned to a square, then
  5390. write the pencil mark $1$ in all the squares in the same row, column,
  5391. and region to indicate that $1$ is no longer an option for those other
  5392. squares.
  5393. %
  5394. The Pencil Marks technique corresponds to the notion of
  5395. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5396. saturation of a vertex, in sudoku terms, is the set of numbers that
  5397. are no longer available. In graph terminology, we have the following
  5398. definition:
  5399. \begin{equation*}
  5400. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5401. \text{ and } \mathrm{color}(v) = c \}
  5402. \end{equation*}
  5403. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5404. edge with $u$.
  5405. The Pencil Marks technique leads to a simple strategy for filling in
  5406. numbers: if there is a square with only one possible number left, then
  5407. choose that number! But what if there are no squares with only one
  5408. possibility left? One brute-force approach is to try them all: choose
  5409. the first one, and if that ultimately leads to a solution, great. If
  5410. not, backtrack and choose the next possibility. One good thing about
  5411. Pencil Marks is that it reduces the degree of branching in the search
  5412. tree. Nevertheless, backtracking can be terribly time consuming. One
  5413. way to reduce the amount of backtracking is to use the
  5414. most-constrained-first heuristic (aka minimum remaining
  5415. values)~\citep{Russell2003}. That is, in choosing a square, always
  5416. choose one with the fewest possibilities left (the vertex with the
  5417. highest saturation). The idea is that choosing highly constrained
  5418. squares earlier rather than later is better, because later on there may
  5419. not be any possibilities left in the highly saturated squares.
  5420. However, register allocation is easier than sudoku, because the
  5421. register allocator can fall back to assigning variables to stack
  5422. locations when the registers run out. Thus, it makes sense to replace
  5423. backtracking with greedy search: make the best choice at the time and
  5424. keep going. We still wish to minimize the number of colors needed, so
  5425. we use the most-constrained-first heuristic in the greedy search.
  5426. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5427. algorithm for register allocation based on saturation and the
  5428. most-constrained-first heuristic. It is roughly equivalent to the
  5429. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  5430. Just as in sudoku, the algorithm represents colors with integers. The
  5431. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  5432. for register allocation. The integers $k$ and larger correspond to
  5433. stack locations. The registers that are not used for register
  5434. allocation, such as \code{rax}, are assigned to negative integers. In
  5435. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  5436. %% One might wonder why we include registers at all in the liveness
  5437. %% analysis and interference graph. For example, we never allocate a
  5438. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5439. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5440. %% to use register for passing arguments to functions, it will be
  5441. %% necessary for those registers to appear in the interference graph
  5442. %% because those registers will also be assigned to variables, and we
  5443. %% don't want those two uses to encroach on each other. Regarding
  5444. %% registers such as \code{rax} and \code{rsp} that are not used for
  5445. %% variables, we could omit them from the interference graph but that
  5446. %% would require adding special cases to our algorithm, which would
  5447. %% complicate the logic for little gain.
  5448. \begin{figure}[btp]
  5449. \begin{tcolorbox}[colback=white]
  5450. \centering
  5451. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5452. Algorithm: DSATUR
  5453. Input: A graph |$G$|
  5454. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5455. |$W \gets \mathrm{vertices}(G)$|
  5456. while |$W \neq \emptyset$| do
  5457. pick a vertex |$u$| from |$W$| with the highest saturation,
  5458. breaking ties randomly
  5459. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5460. |$\mathrm{color}[u] \gets c$|
  5461. |$W \gets W - \{u\}$|
  5462. \end{lstlisting}
  5463. \end{tcolorbox}
  5464. \caption{The saturation-based greedy graph coloring algorithm.}
  5465. \label{fig:satur-algo}
  5466. \end{figure}
  5467. {\if\edition\racketEd
  5468. With the DSATUR algorithm in hand, let us return to the running
  5469. example and consider how to color the interference graph shown in
  5470. figure~\ref{fig:interfere}.
  5471. %
  5472. We start by assigning each register node to its own color. For
  5473. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  5474. assigned $-2$. The variables are not yet colored, so they are
  5475. annotated with a dash. We then update the saturation for vertices that
  5476. are adjacent to a register, obtaining the following annotated
  5477. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  5478. it interferes with both \code{rax} and \code{rsp}.
  5479. \[
  5480. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5481. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5482. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5483. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5484. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5485. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5486. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5487. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5488. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5489. \draw (t1) to (rax);
  5490. \draw (t1) to (z);
  5491. \draw (z) to (y);
  5492. \draw (z) to (w);
  5493. \draw (x) to (w);
  5494. \draw (y) to (w);
  5495. \draw (v) to (w);
  5496. \draw (v) to (rsp);
  5497. \draw (w) to (rsp);
  5498. \draw (x) to (rsp);
  5499. \draw (y) to (rsp);
  5500. \path[-.,bend left=15] (z) edge node {} (rsp);
  5501. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5502. \draw (rax) to (rsp);
  5503. \end{tikzpicture}
  5504. \]
  5505. The algorithm says to select a maximally saturated vertex. So, we pick
  5506. $\ttm{t}$ and color it with the first available integer, which is
  5507. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5508. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5509. \[
  5510. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5511. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5512. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5513. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5514. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5515. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5516. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5517. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5518. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5519. \draw (t1) to (rax);
  5520. \draw (t1) to (z);
  5521. \draw (z) to (y);
  5522. \draw (z) to (w);
  5523. \draw (x) to (w);
  5524. \draw (y) to (w);
  5525. \draw (v) to (w);
  5526. \draw (v) to (rsp);
  5527. \draw (w) to (rsp);
  5528. \draw (x) to (rsp);
  5529. \draw (y) to (rsp);
  5530. \path[-.,bend left=15] (z) edge node {} (rsp);
  5531. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5532. \draw (rax) to (rsp);
  5533. \end{tikzpicture}
  5534. \]
  5535. We repeat the process, selecting a maximally saturated vertex,
  5536. choosing \code{z}, and coloring it with the first available number, which
  5537. is $1$. We add $1$ to the saturation for the neighboring vertices
  5538. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5539. \[
  5540. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5541. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5542. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5543. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5544. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5545. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5546. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5547. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5548. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5549. \draw (t1) to (rax);
  5550. \draw (t1) to (z);
  5551. \draw (z) to (y);
  5552. \draw (z) to (w);
  5553. \draw (x) to (w);
  5554. \draw (y) to (w);
  5555. \draw (v) to (w);
  5556. \draw (v) to (rsp);
  5557. \draw (w) to (rsp);
  5558. \draw (x) to (rsp);
  5559. \draw (y) to (rsp);
  5560. \path[-.,bend left=15] (z) edge node {} (rsp);
  5561. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5562. \draw (rax) to (rsp);
  5563. \end{tikzpicture}
  5564. \]
  5565. The most saturated vertices are now \code{w} and \code{y}. We color
  5566. \code{w} with the first available color, which is $0$.
  5567. \[
  5568. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5569. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5570. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5571. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5572. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5573. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5574. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5575. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5576. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5577. \draw (t1) to (rax);
  5578. \draw (t1) to (z);
  5579. \draw (z) to (y);
  5580. \draw (z) to (w);
  5581. \draw (x) to (w);
  5582. \draw (y) to (w);
  5583. \draw (v) to (w);
  5584. \draw (v) to (rsp);
  5585. \draw (w) to (rsp);
  5586. \draw (x) to (rsp);
  5587. \draw (y) to (rsp);
  5588. \path[-.,bend left=15] (z) edge node {} (rsp);
  5589. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5590. \draw (rax) to (rsp);
  5591. \end{tikzpicture}
  5592. \]
  5593. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5594. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5595. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5596. and \code{z}, whose colors are $0$ and $1$ respectively.
  5597. \[
  5598. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5599. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5600. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5601. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5602. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5603. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5604. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5605. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5606. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5607. \draw (t1) to (rax);
  5608. \draw (t1) to (z);
  5609. \draw (z) to (y);
  5610. \draw (z) to (w);
  5611. \draw (x) to (w);
  5612. \draw (y) to (w);
  5613. \draw (v) to (w);
  5614. \draw (v) to (rsp);
  5615. \draw (w) to (rsp);
  5616. \draw (x) to (rsp);
  5617. \draw (y) to (rsp);
  5618. \path[-.,bend left=15] (z) edge node {} (rsp);
  5619. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5620. \draw (rax) to (rsp);
  5621. \end{tikzpicture}
  5622. \]
  5623. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5624. \[
  5625. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5626. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5627. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5628. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5629. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5630. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5631. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5632. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5633. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5634. \draw (t1) to (rax);
  5635. \draw (t1) to (z);
  5636. \draw (z) to (y);
  5637. \draw (z) to (w);
  5638. \draw (x) to (w);
  5639. \draw (y) to (w);
  5640. \draw (v) to (w);
  5641. \draw (v) to (rsp);
  5642. \draw (w) to (rsp);
  5643. \draw (x) to (rsp);
  5644. \draw (y) to (rsp);
  5645. \path[-.,bend left=15] (z) edge node {} (rsp);
  5646. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5647. \draw (rax) to (rsp);
  5648. \end{tikzpicture}
  5649. \]
  5650. In the last step of the algorithm, we color \code{x} with $1$.
  5651. \[
  5652. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5653. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5654. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5655. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5656. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5657. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5658. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5659. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5660. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5661. \draw (t1) to (rax);
  5662. \draw (t1) to (z);
  5663. \draw (z) to (y);
  5664. \draw (z) to (w);
  5665. \draw (x) to (w);
  5666. \draw (y) to (w);
  5667. \draw (v) to (w);
  5668. \draw (v) to (rsp);
  5669. \draw (w) to (rsp);
  5670. \draw (x) to (rsp);
  5671. \draw (y) to (rsp);
  5672. \path[-.,bend left=15] (z) edge node {} (rsp);
  5673. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5674. \draw (rax) to (rsp);
  5675. \end{tikzpicture}
  5676. \]
  5677. So, we obtain the following coloring:
  5678. \[
  5679. \{
  5680. \ttm{rax} \mapsto -1,
  5681. \ttm{rsp} \mapsto -2,
  5682. \ttm{t} \mapsto 0,
  5683. \ttm{z} \mapsto 1,
  5684. \ttm{x} \mapsto 1,
  5685. \ttm{y} \mapsto 2,
  5686. \ttm{w} \mapsto 0,
  5687. \ttm{v} \mapsto 1
  5688. \}
  5689. \]
  5690. \fi}
  5691. %
  5692. {\if\edition\pythonEd
  5693. %
  5694. With the DSATUR algorithm in hand, let us return to the running
  5695. example and consider how to color the interference graph in
  5696. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5697. to indicate that it has not yet been assigned a color. The saturation
  5698. sets are also shown for each node; all of them start as the empty set.
  5699. (We do not include the register nodes in the graph below because there
  5700. were no interference edges involving registers in this program, but in
  5701. general there can be.)
  5702. %
  5703. \[
  5704. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5705. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5706. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5707. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5708. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5709. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5710. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5711. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5712. \draw (t0) to (t1);
  5713. \draw (t0) to (z);
  5714. \draw (z) to (y);
  5715. \draw (z) to (w);
  5716. \draw (x) to (w);
  5717. \draw (y) to (w);
  5718. \draw (v) to (w);
  5719. \end{tikzpicture}
  5720. \]
  5721. The algorithm says to select a maximally saturated vertex, but they
  5722. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5723. then color it with the first available integer, which is $0$. We mark
  5724. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5725. they interfere with $\ttm{tmp\_0}$.
  5726. \[
  5727. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5728. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5729. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5730. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5731. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5732. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5733. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5734. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5735. \draw (t0) to (t1);
  5736. \draw (t0) to (z);
  5737. \draw (z) to (y);
  5738. \draw (z) to (w);
  5739. \draw (x) to (w);
  5740. \draw (y) to (w);
  5741. \draw (v) to (w);
  5742. \end{tikzpicture}
  5743. \]
  5744. We repeat the process. The most saturated vertices are \code{z} and
  5745. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5746. available number, which is $1$. We add $1$ to the saturation for the
  5747. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5748. \[
  5749. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5750. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5751. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5752. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5753. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5754. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5755. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5756. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5757. \draw (t0) to (t1);
  5758. \draw (t0) to (z);
  5759. \draw (z) to (y);
  5760. \draw (z) to (w);
  5761. \draw (x) to (w);
  5762. \draw (y) to (w);
  5763. \draw (v) to (w);
  5764. \end{tikzpicture}
  5765. \]
  5766. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5767. \code{y}. We color \code{w} with the first available color, which
  5768. is $0$.
  5769. \[
  5770. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5771. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5772. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5773. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5774. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5775. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5776. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5777. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5778. \draw (t0) to (t1);
  5779. \draw (t0) to (z);
  5780. \draw (z) to (y);
  5781. \draw (z) to (w);
  5782. \draw (x) to (w);
  5783. \draw (y) to (w);
  5784. \draw (v) to (w);
  5785. \end{tikzpicture}
  5786. \]
  5787. Now \code{y} is the most saturated, so we color it with $2$.
  5788. \[
  5789. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5790. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5791. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5792. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5793. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5794. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5795. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5796. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5797. \draw (t0) to (t1);
  5798. \draw (t0) to (z);
  5799. \draw (z) to (y);
  5800. \draw (z) to (w);
  5801. \draw (x) to (w);
  5802. \draw (y) to (w);
  5803. \draw (v) to (w);
  5804. \end{tikzpicture}
  5805. \]
  5806. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5807. We choose to color \code{v} with $1$.
  5808. \[
  5809. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5810. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5811. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5812. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5813. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5814. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5815. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5816. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5817. \draw (t0) to (t1);
  5818. \draw (t0) to (z);
  5819. \draw (z) to (y);
  5820. \draw (z) to (w);
  5821. \draw (x) to (w);
  5822. \draw (y) to (w);
  5823. \draw (v) to (w);
  5824. \end{tikzpicture}
  5825. \]
  5826. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5827. \[
  5828. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5829. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5830. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5831. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5832. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5833. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5834. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5835. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5836. \draw (t0) to (t1);
  5837. \draw (t0) to (z);
  5838. \draw (z) to (y);
  5839. \draw (z) to (w);
  5840. \draw (x) to (w);
  5841. \draw (y) to (w);
  5842. \draw (v) to (w);
  5843. \end{tikzpicture}
  5844. \]
  5845. So, we obtain the following coloring:
  5846. \[
  5847. \{ \ttm{tmp\_0} \mapsto 0,
  5848. \ttm{tmp\_1} \mapsto 1,
  5849. \ttm{z} \mapsto 1,
  5850. \ttm{x} \mapsto 1,
  5851. \ttm{y} \mapsto 2,
  5852. \ttm{w} \mapsto 0,
  5853. \ttm{v} \mapsto 1 \}
  5854. \]
  5855. \fi}
  5856. We recommend creating an auxiliary function named \code{color\_graph}
  5857. that takes an interference graph and a list of all the variables in
  5858. the program. This function should return a mapping of variables to
  5859. their colors (represented as natural numbers). By creating this helper
  5860. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5861. when we add support for functions.
  5862. To prioritize the processing of highly saturated nodes inside the
  5863. \code{color\_graph} function, we recommend using the priority queue
  5864. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5865. addition, you will need to maintain a mapping from variables to their
  5866. handles in the priority queue so that you can notify the priority
  5867. queue when their saturation changes.}
  5868. {\if\edition\racketEd
  5869. \begin{figure}[tp]
  5870. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5871. \small
  5872. \begin{tcolorbox}[title=Priority Queue]
  5873. A \emph{priority queue} is a collection of items in which the
  5874. removal of items is governed by priority. In a min queue,
  5875. lower priority items are removed first. An implementation is in
  5876. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5877. queue} \index{subject}{minimum priority queue}
  5878. \begin{description}
  5879. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5880. priority queue that uses the $\itm{cmp}$ predicate to determine
  5881. whether its first argument has lower or equal priority to its
  5882. second argument.
  5883. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5884. items in the queue.
  5885. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5886. the item into the queue and returns a handle for the item in the
  5887. queue.
  5888. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5889. the lowest priority.
  5890. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5891. notifies the queue that the priority has decreased for the item
  5892. associated with the given handle.
  5893. \end{description}
  5894. \end{tcolorbox}
  5895. %\end{wrapfigure}
  5896. \caption{The priority queue data structure.}
  5897. \label{fig:priority-queue}
  5898. \end{figure}
  5899. \fi}
  5900. With the coloring complete, we finalize the assignment of variables to
  5901. registers and stack locations. We map the first $k$ colors to the $k$
  5902. registers and the rest of the colors to stack locations. Suppose for
  5903. the moment that we have just one register to use for register
  5904. allocation, \key{rcx}. Then we have the following map from colors to
  5905. locations.
  5906. \[
  5907. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5908. \]
  5909. Composing this mapping with the coloring, we arrive at the following
  5910. assignment of variables to locations.
  5911. {\if\edition\racketEd
  5912. \begin{gather*}
  5913. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5914. \ttm{w} \mapsto \key{\%rcx}, \,
  5915. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5916. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5917. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5918. \ttm{t} \mapsto \key{\%rcx} \}
  5919. \end{gather*}
  5920. \fi}
  5921. {\if\edition\pythonEd
  5922. \begin{gather*}
  5923. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5924. \ttm{w} \mapsto \key{\%rcx}, \,
  5925. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5926. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5927. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5928. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5929. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5930. \end{gather*}
  5931. \fi}
  5932. Adapt the code from the \code{assign\_homes} pass
  5933. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5934. assigned location. Applying this assignment to our running
  5935. example shown next, on the left, yields the program on the right.
  5936. % why frame size of 32? -JGS
  5937. \begin{center}
  5938. {\if\edition\racketEd
  5939. \begin{minipage}{0.3\textwidth}
  5940. \begin{lstlisting}
  5941. movq $1, v
  5942. movq $42, w
  5943. movq v, x
  5944. addq $7, x
  5945. movq x, y
  5946. movq x, z
  5947. addq w, z
  5948. movq y, t
  5949. negq t
  5950. movq z, %rax
  5951. addq t, %rax
  5952. jmp conclusion
  5953. \end{lstlisting}
  5954. \end{minipage}
  5955. $\Rightarrow\qquad$
  5956. \begin{minipage}{0.45\textwidth}
  5957. \begin{lstlisting}
  5958. movq $1, -8(%rbp)
  5959. movq $42, %rcx
  5960. movq -8(%rbp), -8(%rbp)
  5961. addq $7, -8(%rbp)
  5962. movq -8(%rbp), -16(%rbp)
  5963. movq -8(%rbp), -8(%rbp)
  5964. addq %rcx, -8(%rbp)
  5965. movq -16(%rbp), %rcx
  5966. negq %rcx
  5967. movq -8(%rbp), %rax
  5968. addq %rcx, %rax
  5969. jmp conclusion
  5970. \end{lstlisting}
  5971. \end{minipage}
  5972. \fi}
  5973. {\if\edition\pythonEd
  5974. \begin{minipage}{0.3\textwidth}
  5975. \begin{lstlisting}
  5976. movq $1, v
  5977. movq $42, w
  5978. movq v, x
  5979. addq $7, x
  5980. movq x, y
  5981. movq x, z
  5982. addq w, z
  5983. movq y, tmp_0
  5984. negq tmp_0
  5985. movq z, tmp_1
  5986. addq tmp_0, tmp_1
  5987. movq tmp_1, %rdi
  5988. callq print_int
  5989. \end{lstlisting}
  5990. \end{minipage}
  5991. $\Rightarrow\qquad$
  5992. \begin{minipage}{0.45\textwidth}
  5993. \begin{lstlisting}
  5994. movq $1, -8(%rbp)
  5995. movq $42, %rcx
  5996. movq -8(%rbp), -8(%rbp)
  5997. addq $7, -8(%rbp)
  5998. movq -8(%rbp), -16(%rbp)
  5999. movq -8(%rbp), -8(%rbp)
  6000. addq %rcx, -8(%rbp)
  6001. movq -16(%rbp), %rcx
  6002. negq %rcx
  6003. movq -8(%rbp), -8(%rbp)
  6004. addq %rcx, -8(%rbp)
  6005. movq -8(%rbp), %rdi
  6006. callq print_int
  6007. \end{lstlisting}
  6008. \end{minipage}
  6009. \fi}
  6010. \end{center}
  6011. \begin{exercise}\normalfont\normalsize
  6012. Implement the \code{allocate\_registers} pass.
  6013. Create five programs that exercise all aspects of the register
  6014. allocation algorithm, including spilling variables to the stack.
  6015. %
  6016. {\if\edition\racketEd
  6017. Replace \code{assign\_homes} in the list of \code{passes} in the
  6018. \code{run-tests.rkt} script with the three new passes:
  6019. \code{uncover\_live}, \code{build\_interference}, and
  6020. \code{allocate\_registers}.
  6021. Temporarily remove the call to \code{compiler-tests}.
  6022. Run the script to test the register allocator.
  6023. \fi}
  6024. %
  6025. {\if\edition\pythonEd
  6026. Run the \code{run-tests.py} script to to check whether the
  6027. output programs produce the same result as the input programs.
  6028. \fi}
  6029. \end{exercise}
  6030. \section{Patch Instructions}
  6031. \label{sec:patch-instructions}
  6032. The remaining step in the compilation to x86 is to ensure that the
  6033. instructions have at most one argument that is a memory access.
  6034. %
  6035. In the running example, the instruction \code{movq -8(\%rbp),
  6036. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6037. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6038. then move \code{rax} into \code{-16(\%rbp)}.
  6039. %
  6040. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6041. problematic, but they can simply be deleted. In general, we recommend
  6042. deleting all the trivial moves whose source and destination are the
  6043. same location.
  6044. %
  6045. The following is the output of \code{patch\_instructions} on the
  6046. running example.
  6047. \begin{center}
  6048. {\if\edition\racketEd
  6049. \begin{minipage}{0.4\textwidth}
  6050. \begin{lstlisting}
  6051. movq $1, -8(%rbp)
  6052. movq $42, %rcx
  6053. movq -8(%rbp), -8(%rbp)
  6054. addq $7, -8(%rbp)
  6055. movq -8(%rbp), -16(%rbp)
  6056. movq -8(%rbp), -8(%rbp)
  6057. addq %rcx, -8(%rbp)
  6058. movq -16(%rbp), %rcx
  6059. negq %rcx
  6060. movq -8(%rbp), %rax
  6061. addq %rcx, %rax
  6062. jmp conclusion
  6063. \end{lstlisting}
  6064. \end{minipage}
  6065. $\Rightarrow\qquad$
  6066. \begin{minipage}{0.45\textwidth}
  6067. \begin{lstlisting}
  6068. movq $1, -8(%rbp)
  6069. movq $42, %rcx
  6070. addq $7, -8(%rbp)
  6071. movq -8(%rbp), %rax
  6072. movq %rax, -16(%rbp)
  6073. addq %rcx, -8(%rbp)
  6074. movq -16(%rbp), %rcx
  6075. negq %rcx
  6076. movq -8(%rbp), %rax
  6077. addq %rcx, %rax
  6078. jmp conclusion
  6079. \end{lstlisting}
  6080. \end{minipage}
  6081. \fi}
  6082. {\if\edition\pythonEd
  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), -8(%rbp)
  6095. addq %rcx, -8(%rbp)
  6096. movq -8(%rbp), %rdi
  6097. callq print_int
  6098. \end{lstlisting}
  6099. \end{minipage}
  6100. $\Rightarrow\qquad$
  6101. \begin{minipage}{0.45\textwidth}
  6102. \begin{lstlisting}
  6103. movq $1, -8(%rbp)
  6104. movq $42, %rcx
  6105. addq $7, -8(%rbp)
  6106. movq -8(%rbp), %rax
  6107. movq %rax, -16(%rbp)
  6108. addq %rcx, -8(%rbp)
  6109. movq -16(%rbp), %rcx
  6110. negq %rcx
  6111. addq %rcx, -8(%rbp)
  6112. movq -8(%rbp), %rdi
  6113. callq print_int
  6114. \end{lstlisting}
  6115. \end{minipage}
  6116. \fi}
  6117. \end{center}
  6118. \begin{exercise}\normalfont\normalsize
  6119. %
  6120. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6121. %
  6122. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6123. %in the \code{run-tests.rkt} script.
  6124. %
  6125. Run the script to test the \code{patch\_instructions} pass.
  6126. \end{exercise}
  6127. \section{Prelude and Conclusion}
  6128. \label{sec:print-x86-reg-alloc}
  6129. \index{subject}{calling conventions}
  6130. \index{subject}{prelude}\index{subject}{conclusion}
  6131. Recall that this pass generates the prelude and conclusion
  6132. instructions to satisfy the x86 calling conventions
  6133. (section~\ref{sec:calling-conventions}). With the addition of the
  6134. register allocator, the callee-saved registers used by the register
  6135. allocator must be saved in the prelude and restored in the conclusion.
  6136. In the \code{allocate\_registers} pass,
  6137. %
  6138. \racket{add an entry to the \itm{info}
  6139. of \code{X86Program} named \code{used\_callee}}
  6140. %
  6141. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6142. %
  6143. that stores the set of callee-saved registers that were assigned to
  6144. variables. The \code{prelude\_and\_conclusion} pass can then access
  6145. this information to decide which callee-saved registers need to be
  6146. saved and restored.
  6147. %
  6148. When calculating the amount to adjust the \code{rsp} in the prelude,
  6149. make sure to take into account the space used for saving the
  6150. callee-saved registers. Also, remember that the frame needs to be a
  6151. multiple of 16 bytes! We recommend using the following equation for
  6152. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6153. of spilled variables and $C$ be the number of callee-saved registers
  6154. that were allocated to variables. The $\itm{align}$ function rounds a
  6155. number up to the nearest 16 bytes.
  6156. \[
  6157. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6158. \]
  6159. The reason we subtract $8\itm{C}$ in this equation is that the
  6160. prelude uses \code{pushq} to save each of the callee-saved registers,
  6161. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6162. \racket{An overview of all the passes involved in register
  6163. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6164. {\if\edition\racketEd
  6165. \begin{figure}[tbp]
  6166. \begin{tcolorbox}[colback=white]
  6167. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6168. \node (Lvar) at (0,2) {\large \LangVar{}};
  6169. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6170. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6171. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6172. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6173. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6174. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6175. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6176. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6177. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6178. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6179. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6180. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  6181. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6182. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6183. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6184. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6185. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6186. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6187. \end{tikzpicture}
  6188. \end{tcolorbox}
  6189. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6190. \label{fig:reg-alloc-passes}
  6191. \end{figure}
  6192. \fi}
  6193. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6194. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6195. use of registers and the stack, we limit the register allocator for
  6196. this example to use just two registers: \code{rbx} and \code{rcx}. In
  6197. the prelude\index{subject}{prelude} of the \code{main} function, we
  6198. push \code{rbx} onto the stack because it is a callee-saved register
  6199. and it was assigned to a variable by the register allocator. We
  6200. subtract \code{8} from the \code{rsp} at the end of the prelude to
  6201. reserve space for the one spilled variable. After that subtraction,
  6202. the \code{rsp} is aligned to 16 bytes.
  6203. Moving on to the program proper, we see how the registers were
  6204. allocated.
  6205. %
  6206. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  6207. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  6208. %
  6209. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6210. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6211. were assigned to \code{rbx}.}
  6212. %
  6213. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  6214. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6215. callee-save register \code{rbx} onto the stack. The spilled variables
  6216. must be placed lower on the stack than the saved callee-save
  6217. registers, so in this case \racket{\code{w}}\python{z} is placed at
  6218. \code{-16(\%rbp)}.
  6219. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6220. done in the prelude. We move the stack pointer up by \code{8} bytes
  6221. (the room for spilled variables), then pop the old values of
  6222. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6223. \code{retq} to return control to the operating system.
  6224. \begin{figure}[tbp]
  6225. \begin{minipage}{0.55\textwidth}
  6226. \begin{tcolorbox}[colback=white]
  6227. % var_test_28.rkt
  6228. % (use-minimal-set-of-registers! #t)
  6229. % and only rbx rcx
  6230. % tmp 0 rbx
  6231. % z 1 rcx
  6232. % y 0 rbx
  6233. % w 2 16(%rbp)
  6234. % v 0 rbx
  6235. % x 0 rbx
  6236. {\if\edition\racketEd
  6237. \begin{lstlisting}
  6238. start:
  6239. movq $1, %rbx
  6240. movq $42, -16(%rbp)
  6241. addq $7, %rbx
  6242. movq %rbx, %rcx
  6243. addq -16(%rbp), %rcx
  6244. negq %rbx
  6245. movq %rcx, %rax
  6246. addq %rbx, %rax
  6247. jmp conclusion
  6248. .globl main
  6249. main:
  6250. pushq %rbp
  6251. movq %rsp, %rbp
  6252. pushq %rbx
  6253. subq $8, %rsp
  6254. jmp start
  6255. conclusion:
  6256. addq $8, %rsp
  6257. popq %rbx
  6258. popq %rbp
  6259. retq
  6260. \end{lstlisting}
  6261. \fi}
  6262. {\if\edition\pythonEd
  6263. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6264. \begin{lstlisting}
  6265. .globl main
  6266. main:
  6267. pushq %rbp
  6268. movq %rsp, %rbp
  6269. pushq %rbx
  6270. subq $8, %rsp
  6271. movq $1, %rcx
  6272. movq $42, %rbx
  6273. addq $7, %rcx
  6274. movq %rcx, -16(%rbp)
  6275. addq %rbx, -16(%rbp)
  6276. negq %rcx
  6277. movq -16(%rbp), %rbx
  6278. addq %rcx, %rbx
  6279. movq %rbx, %rdi
  6280. callq print_int
  6281. addq $8, %rsp
  6282. popq %rbx
  6283. popq %rbp
  6284. retq
  6285. \end{lstlisting}
  6286. \fi}
  6287. \end{tcolorbox}
  6288. \end{minipage}
  6289. \caption{The x86 output from the running example
  6290. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6291. and \code{rcx}.}
  6292. \label{fig:running-example-x86}
  6293. \end{figure}
  6294. \begin{exercise}\normalfont\normalsize
  6295. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6296. %
  6297. \racket{
  6298. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6299. list of passes and the call to \code{compiler-tests}.}
  6300. %
  6301. Run the script to test the complete compiler for \LangVar{} that
  6302. performs register allocation.
  6303. \end{exercise}
  6304. \section{Challenge: Move Biasing}
  6305. \label{sec:move-biasing}
  6306. \index{subject}{move biasing}
  6307. This section describes an enhancement to the register allocator,
  6308. called move biasing, for students who are looking for an extra
  6309. challenge.
  6310. {\if\edition\racketEd
  6311. To motivate the need for move biasing we return to the running example,
  6312. but this time we use all the general purpose registers. So, we have
  6313. the following mapping of color numbers to registers.
  6314. \[
  6315. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6316. \]
  6317. Using the same assignment of variables to color numbers that was
  6318. produced by the register allocator described in the last section, we
  6319. get the following program.
  6320. \begin{center}
  6321. \begin{minipage}{0.3\textwidth}
  6322. \begin{lstlisting}
  6323. movq $1, v
  6324. movq $42, w
  6325. movq v, x
  6326. addq $7, x
  6327. movq x, y
  6328. movq x, z
  6329. addq w, z
  6330. movq y, t
  6331. negq t
  6332. movq z, %rax
  6333. addq t, %rax
  6334. jmp conclusion
  6335. \end{lstlisting}
  6336. \end{minipage}
  6337. $\Rightarrow\qquad$
  6338. \begin{minipage}{0.45\textwidth}
  6339. \begin{lstlisting}
  6340. movq $1, %rdx
  6341. movq $42, %rcx
  6342. movq %rdx, %rdx
  6343. addq $7, %rdx
  6344. movq %rdx, %rsi
  6345. movq %rdx, %rdx
  6346. addq %rcx, %rdx
  6347. movq %rsi, %rcx
  6348. negq %rcx
  6349. movq %rdx, %rax
  6350. addq %rcx, %rax
  6351. jmp conclusion
  6352. \end{lstlisting}
  6353. \end{minipage}
  6354. \end{center}
  6355. In this output code there are two \key{movq} instructions that
  6356. can be removed because their source and target are the same. However,
  6357. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6358. register, we could instead remove three \key{movq} instructions. We
  6359. can accomplish this by taking into account which variables appear in
  6360. \key{movq} instructions with which other variables.
  6361. \fi}
  6362. {\if\edition\pythonEd
  6363. %
  6364. To motivate the need for move biasing we return to the running example
  6365. and recall that in section~\ref{sec:patch-instructions} we were able to
  6366. remove three trivial move instructions from the running
  6367. example. However, we could remove another trivial move if we were able
  6368. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6369. We say that two variables $p$ and $q$ are \emph{move
  6370. related}\index{subject}{move related} if they participate together in
  6371. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6372. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  6373. if there are multiple variables with the same saturation, prefer
  6374. variables that can be assigned to a color that is the same as the
  6375. color of a move-related variable. Furthermore, when the register
  6376. allocator chooses a color for a variable, it should prefer a color
  6377. that has already been used for a move-related variable (assuming that
  6378. they do not interfere). Of course, this preference should not override
  6379. the preference for registers over stack locations. So, this preference
  6380. should be used as a tie breaker in choosing between registers and
  6381. in choosing between stack locations.
  6382. We recommend representing the move relationships in a graph, similarly
  6383. to how we represented interference. The following is the \emph{move
  6384. graph} for our running example.
  6385. {\if\edition\racketEd
  6386. \[
  6387. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6388. \node (rax) at (0,0) {$\ttm{rax}$};
  6389. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6390. \node (t) at (0,2) {$\ttm{t}$};
  6391. \node (z) at (3,2) {$\ttm{z}$};
  6392. \node (x) at (6,2) {$\ttm{x}$};
  6393. \node (y) at (3,0) {$\ttm{y}$};
  6394. \node (w) at (6,0) {$\ttm{w}$};
  6395. \node (v) at (9,0) {$\ttm{v}$};
  6396. \draw (v) to (x);
  6397. \draw (x) to (y);
  6398. \draw (x) to (z);
  6399. \draw (y) to (t);
  6400. \end{tikzpicture}
  6401. \]
  6402. \fi}
  6403. %
  6404. {\if\edition\pythonEd
  6405. \[
  6406. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6407. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6408. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6409. \node (z) at (3,2) {$\ttm{z}$};
  6410. \node (x) at (6,2) {$\ttm{x}$};
  6411. \node (y) at (3,0) {$\ttm{y}$};
  6412. \node (w) at (6,0) {$\ttm{w}$};
  6413. \node (v) at (9,0) {$\ttm{v}$};
  6414. \draw (y) to (t0);
  6415. \draw (z) to (x);
  6416. \draw (z) to (t1);
  6417. \draw (x) to (y);
  6418. \draw (x) to (v);
  6419. \end{tikzpicture}
  6420. \]
  6421. \fi}
  6422. {\if\edition\racketEd
  6423. Now we replay the graph coloring, pausing to see the coloring of
  6424. \code{y}. Recall the following configuration. The most saturated vertices
  6425. were \code{w} and \code{y}.
  6426. \[
  6427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6428. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6429. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6430. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6431. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6432. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6433. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6434. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6435. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6436. \draw (t1) to (rax);
  6437. \draw (t1) to (z);
  6438. \draw (z) to (y);
  6439. \draw (z) to (w);
  6440. \draw (x) to (w);
  6441. \draw (y) to (w);
  6442. \draw (v) to (w);
  6443. \draw (v) to (rsp);
  6444. \draw (w) to (rsp);
  6445. \draw (x) to (rsp);
  6446. \draw (y) to (rsp);
  6447. \path[-.,bend left=15] (z) edge node {} (rsp);
  6448. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6449. \draw (rax) to (rsp);
  6450. \end{tikzpicture}
  6451. \]
  6452. %
  6453. The last time, we chose to color \code{w} with $0$. This time, we see
  6454. that \code{w} is not move-related to any vertex, but \code{y} is
  6455. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6456. the same color as \code{t}.
  6457. \[
  6458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6459. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6460. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6461. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6462. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6463. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6464. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6465. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6466. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6467. \draw (t1) to (rax);
  6468. \draw (t1) to (z);
  6469. \draw (z) to (y);
  6470. \draw (z) to (w);
  6471. \draw (x) to (w);
  6472. \draw (y) to (w);
  6473. \draw (v) to (w);
  6474. \draw (v) to (rsp);
  6475. \draw (w) to (rsp);
  6476. \draw (x) to (rsp);
  6477. \draw (y) to (rsp);
  6478. \path[-.,bend left=15] (z) edge node {} (rsp);
  6479. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6480. \draw (rax) to (rsp);
  6481. \end{tikzpicture}
  6482. \]
  6483. Now \code{w} is the most saturated, so we color it $2$.
  6484. \[
  6485. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6486. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6487. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6488. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6489. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6490. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6491. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6492. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6493. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6494. \draw (t1) to (rax);
  6495. \draw (t1) to (z);
  6496. \draw (z) to (y);
  6497. \draw (z) to (w);
  6498. \draw (x) to (w);
  6499. \draw (y) to (w);
  6500. \draw (v) to (w);
  6501. \draw (v) to (rsp);
  6502. \draw (w) to (rsp);
  6503. \draw (x) to (rsp);
  6504. \draw (y) to (rsp);
  6505. \path[-.,bend left=15] (z) edge node {} (rsp);
  6506. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6507. \draw (rax) to (rsp);
  6508. \end{tikzpicture}
  6509. \]
  6510. At this point, vertices \code{x} and \code{v} are most saturated, but
  6511. \code{x} is move related to \code{y} and \code{z}, so we color
  6512. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6513. \[
  6514. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6515. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6516. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6517. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6518. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6519. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6520. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6521. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6522. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6523. \draw (t1) to (rax);
  6524. \draw (t) to (z);
  6525. \draw (z) to (y);
  6526. \draw (z) to (w);
  6527. \draw (x) to (w);
  6528. \draw (y) to (w);
  6529. \draw (v) to (w);
  6530. \draw (v) to (rsp);
  6531. \draw (w) to (rsp);
  6532. \draw (x) to (rsp);
  6533. \draw (y) to (rsp);
  6534. \path[-.,bend left=15] (z) edge node {} (rsp);
  6535. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6536. \draw (rax) to (rsp);
  6537. \end{tikzpicture}
  6538. \]
  6539. \fi}
  6540. %
  6541. {\if\edition\pythonEd
  6542. Now we replay the graph coloring, pausing before the coloring of
  6543. \code{w}. Recall the following configuration. The most saturated vertices
  6544. were \code{tmp\_1}, \code{w}, and \code{y}.
  6545. \[
  6546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6547. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6548. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6549. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6550. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6551. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6552. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6553. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6554. \draw (t0) to (t1);
  6555. \draw (t0) to (z);
  6556. \draw (z) to (y);
  6557. \draw (z) to (w);
  6558. \draw (x) to (w);
  6559. \draw (y) to (w);
  6560. \draw (v) to (w);
  6561. \end{tikzpicture}
  6562. \]
  6563. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6564. or \code{y}, but note that \code{w} is not move related to any
  6565. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6566. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6567. \code{y} and color it $0$, we can delete another move instruction.
  6568. \[
  6569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6570. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6571. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6572. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6573. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6574. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6575. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6576. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6577. \draw (t0) to (t1);
  6578. \draw (t0) to (z);
  6579. \draw (z) to (y);
  6580. \draw (z) to (w);
  6581. \draw (x) to (w);
  6582. \draw (y) to (w);
  6583. \draw (v) to (w);
  6584. \end{tikzpicture}
  6585. \]
  6586. Now \code{w} is the most saturated, so we color it $2$.
  6587. \[
  6588. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6589. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6590. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6591. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6592. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6593. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6594. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6595. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6596. \draw (t0) to (t1);
  6597. \draw (t0) to (z);
  6598. \draw (z) to (y);
  6599. \draw (z) to (w);
  6600. \draw (x) to (w);
  6601. \draw (y) to (w);
  6602. \draw (v) to (w);
  6603. \end{tikzpicture}
  6604. \]
  6605. To finish the coloring, \code{x} and \code{v} get $0$ and
  6606. \code{tmp\_1} gets $1$.
  6607. \[
  6608. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6609. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6610. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6611. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6612. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6613. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6614. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6615. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6616. \draw (t0) to (t1);
  6617. \draw (t0) to (z);
  6618. \draw (z) to (y);
  6619. \draw (z) to (w);
  6620. \draw (x) to (w);
  6621. \draw (y) to (w);
  6622. \draw (v) to (w);
  6623. \end{tikzpicture}
  6624. \]
  6625. \fi}
  6626. So, we have the following assignment of variables to registers.
  6627. {\if\edition\racketEd
  6628. \begin{gather*}
  6629. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6630. \ttm{w} \mapsto \key{\%rsi}, \,
  6631. \ttm{x} \mapsto \key{\%rcx}, \,
  6632. \ttm{y} \mapsto \key{\%rcx}, \,
  6633. \ttm{z} \mapsto \key{\%rdx}, \,
  6634. \ttm{t} \mapsto \key{\%rcx} \}
  6635. \end{gather*}
  6636. \fi}
  6637. {\if\edition\pythonEd
  6638. \begin{gather*}
  6639. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6640. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6641. \ttm{x} \mapsto \key{\%rcx}, \,
  6642. \ttm{y} \mapsto \key{\%rcx}, \\
  6643. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6644. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6645. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6646. \end{gather*}
  6647. \fi}
  6648. %
  6649. We apply this register assignment to the running example shown next,
  6650. on the left, to obtain the code in the middle. The
  6651. \code{patch\_instructions} then deletes the trivial moves to obtain
  6652. the code on the right.
  6653. {\if\edition\racketEd
  6654. \begin{minipage}{0.25\textwidth}
  6655. \begin{lstlisting}
  6656. movq $1, v
  6657. movq $42, w
  6658. movq v, x
  6659. addq $7, x
  6660. movq x, y
  6661. movq x, z
  6662. addq w, z
  6663. movq y, t
  6664. negq t
  6665. movq z, %rax
  6666. addq t, %rax
  6667. jmp conclusion
  6668. \end{lstlisting}
  6669. \end{minipage}
  6670. $\Rightarrow\qquad$
  6671. \begin{minipage}{0.25\textwidth}
  6672. \begin{lstlisting}
  6673. movq $1, %rcx
  6674. movq $42, %rsi
  6675. movq %rcx, %rcx
  6676. addq $7, %rcx
  6677. movq %rcx, %rcx
  6678. movq %rcx, %rdx
  6679. addq %rsi, %rdx
  6680. movq %rcx, %rcx
  6681. negq %rcx
  6682. movq %rdx, %rax
  6683. addq %rcx, %rax
  6684. jmp conclusion
  6685. \end{lstlisting}
  6686. \end{minipage}
  6687. $\Rightarrow\qquad$
  6688. \begin{minipage}{0.25\textwidth}
  6689. \begin{lstlisting}
  6690. movq $1, %rcx
  6691. movq $42, %rsi
  6692. addq $7, %rcx
  6693. movq %rcx, %rdx
  6694. addq %rsi, %rdx
  6695. negq %rcx
  6696. movq %rdx, %rax
  6697. addq %rcx, %rax
  6698. jmp conclusion
  6699. \end{lstlisting}
  6700. \end{minipage}
  6701. \fi}
  6702. {\if\edition\pythonEd
  6703. \begin{minipage}{0.20\textwidth}
  6704. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6705. movq $1, v
  6706. movq $42, w
  6707. movq v, x
  6708. addq $7, x
  6709. movq x, y
  6710. movq x, z
  6711. addq w, z
  6712. movq y, tmp_0
  6713. negq tmp_0
  6714. movq z, tmp_1
  6715. addq tmp_0, tmp_1
  6716. movq tmp_1, %rdi
  6717. callq _print_int
  6718. \end{lstlisting}
  6719. \end{minipage}
  6720. ${\Rightarrow\qquad}$
  6721. \begin{minipage}{0.30\textwidth}
  6722. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6723. movq $1, %rcx
  6724. movq $42, -16(%rbp)
  6725. movq %rcx, %rcx
  6726. addq $7, %rcx
  6727. movq %rcx, %rcx
  6728. movq %rcx, -8(%rbp)
  6729. addq -16(%rbp), -8(%rbp)
  6730. movq %rcx, %rcx
  6731. negq %rcx
  6732. movq -8(%rbp), -8(%rbp)
  6733. addq %rcx, -8(%rbp)
  6734. movq -8(%rbp), %rdi
  6735. callq _print_int
  6736. \end{lstlisting}
  6737. \end{minipage}
  6738. ${\Rightarrow\qquad}$
  6739. \begin{minipage}{0.20\textwidth}
  6740. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6741. movq $1, %rcx
  6742. movq $42, -16(%rbp)
  6743. addq $7, %rcx
  6744. movq %rcx, -8(%rbp)
  6745. movq -16(%rbp), %rax
  6746. addq %rax, -8(%rbp)
  6747. negq %rcx
  6748. addq %rcx, -8(%rbp)
  6749. movq -8(%rbp), %rdi
  6750. callq print_int
  6751. \end{lstlisting}
  6752. \end{minipage}
  6753. \fi}
  6754. \begin{exercise}\normalfont\normalsize
  6755. Change your implementation of \code{allocate\_registers} to take move
  6756. biasing into account. Create two new tests that include at least one
  6757. opportunity for move biasing, and visually inspect the output x86
  6758. programs to make sure that your move biasing is working properly. Make
  6759. sure that your compiler still passes all the tests.
  6760. \end{exercise}
  6761. %To do: another neat challenge would be to do
  6762. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6763. %% \subsection{Output of the Running Example}
  6764. %% \label{sec:reg-alloc-output}
  6765. % challenge: prioritize variables based on execution frequencies
  6766. % and the number of uses of a variable
  6767. % challenge: enhance the coloring algorithm using Chaitin's
  6768. % approach of prioritizing high-degree variables
  6769. % by removing low-degree variables (coloring them later)
  6770. % from the interference graph
  6771. \section{Further Reading}
  6772. \label{sec:register-allocation-further-reading}
  6773. Early register allocation algorithms were developed for Fortran
  6774. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6775. of graph coloring began in the late 1970s and early 1980s with the
  6776. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6777. algorithm is based on the following observation of
  6778. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6779. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6780. $v$ removed is also $k$ colorable. To see why, suppose that the
  6781. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6782. different colors, but because there are fewer than $k$ neighbors, there
  6783. will be one or more colors left over to use for coloring $v$ in $G$.
  6784. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6785. less than $k$ from the graph and recursively colors the rest of the
  6786. graph. Upon returning from the recursion, it colors $v$ with one of
  6787. the available colors and returns. \citet{Chaitin:1982vn} augments
  6788. this algorithm to handle spilling as follows. If there are no vertices
  6789. of degree lower than $k$ then pick a vertex at random, spill it,
  6790. remove it from the graph, and proceed recursively to color the rest of
  6791. the graph.
  6792. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6793. move-related and that don't interfere with each other, in a process
  6794. called \emph{coalescing}. Although coalescing decreases the number of
  6795. moves, it can make the graph more difficult to
  6796. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6797. which two variables are merged only if they have fewer than $k$
  6798. neighbors of high degree. \citet{George:1996aa} observed that
  6799. conservative coalescing is sometimes too conservative and made it more
  6800. aggressive by iterating the coalescing with the removal of low-degree
  6801. vertices.
  6802. %
  6803. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6804. also proposed \emph{biased coloring}, in which a variable is assigned to
  6805. the same color as another move-related variable if possible, as
  6806. discussed in section~\ref{sec:move-biasing}.
  6807. %
  6808. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6809. performs coalescing, graph coloring, and spill code insertion until
  6810. all variables have been assigned a location.
  6811. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6812. spilled variables that don't have to be: a high-degree variable can be
  6813. colorable if many of its neighbors are assigned the same color.
  6814. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6815. high-degree vertex is not immediately spilled. Instead the decision is
  6816. deferred until after the recursive call, at which point it is apparent
  6817. whether there is actually an available color or not. We observe that
  6818. this algorithm is equivalent to the smallest-last ordering
  6819. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6820. be registers and the rest to be stack locations.
  6821. %% biased coloring
  6822. Earlier editions of the compiler course at Indiana University
  6823. \citep{Dybvig:2010aa} were based on the algorithm of
  6824. \citet{Briggs:1994kx}.
  6825. The smallest-last ordering algorithm is one of many \emph{greedy}
  6826. coloring algorithms. A greedy coloring algorithm visits all the
  6827. vertices in a particular order and assigns each one the first
  6828. available color. An \emph{offline} greedy algorithm chooses the
  6829. ordering up front, prior to assigning colors. The algorithm of
  6830. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6831. ordering does not depend on the colors assigned. Other orderings are
  6832. possible. For example, \citet{Chow:1984ys} ordered variables according
  6833. to an estimate of runtime cost.
  6834. An \emph{online} greedy coloring algorithm uses information about the
  6835. current assignment of colors to influence the order in which the
  6836. remaining vertices are colored. The saturation-based algorithm
  6837. described in this chapter is one such algorithm. We choose to use
  6838. saturation-based coloring because it is fun to introduce graph
  6839. coloring via sudoku!
  6840. A register allocator may choose to map each variable to just one
  6841. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6842. variable to one or more locations. The latter can be achieved by
  6843. \emph{live range splitting}, where a variable is replaced by several
  6844. variables that each handle part of its live
  6845. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6846. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6847. %% replacement algorithm, bottom-up local
  6848. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6849. %% Cooper: top-down (priority bassed), bottom-up
  6850. %% top-down
  6851. %% order variables by priority (estimated cost)
  6852. %% caveat: split variables into two groups:
  6853. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6854. %% color the constrained ones first
  6855. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6856. %% cite J. Cocke for an algorithm that colors variables
  6857. %% in a high-degree first ordering
  6858. %Register Allocation via Usage Counts, Freiburghouse CACM
  6859. \citet{Palsberg:2007si} observed that many of the interference graphs
  6860. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6861. that is, every cycle with four or more edges has an edge that is not
  6862. part of the cycle but that connects two vertices on the cycle. Such
  6863. graphs can be optimally colored by the greedy algorithm with a vertex
  6864. ordering determined by maximum cardinality search.
  6865. In situations in which compile time is of utmost importance, such as
  6866. in just-in-time compilers, graph coloring algorithms can be too
  6867. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6868. be more appropriate.
  6869. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6870. \chapter{Booleans and Conditionals}
  6871. \label{ch:Lif}
  6872. \index{subject}{Boolean}
  6873. \index{subject}{control flow}
  6874. \index{subject}{conditional expression}
  6875. \setcounter{footnote}{0}
  6876. The \LangVar{} language has only a single kind of value, the
  6877. integers. In this chapter we add a second kind of value, the Booleans,
  6878. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6879. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6880. and \FALSE{}, respectively. The \LangIf{} language includes several
  6881. operations that involve Booleans (\key{and}, \key{not},
  6882. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6883. expression \python{and statement}. With the addition of \key{if},
  6884. programs can have nontrivial control flow which
  6885. %
  6886. \racket{impacts \code{explicate\_control} and liveness analysis}
  6887. %
  6888. \python{impacts liveness analysis and motivates a new pass named
  6889. \code{explicate\_control}}.
  6890. %
  6891. Also, because we now have two kinds of values, we need to handle
  6892. programs that apply an operation to the wrong kind of value, such as
  6893. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6894. There are two language design options for such situations. One option
  6895. is to signal an error and the other is to provide a wider
  6896. interpretation of the operation. \racket{The Racket
  6897. language}\python{Python} uses a mixture of these two options,
  6898. depending on the operation and the kind of value. For example, the
  6899. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6900. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6901. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6902. %
  6903. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6904. in Racket because \code{car} expects a pair.}
  6905. %
  6906. \python{On the other hand, \code{1[0]} results in a runtime error
  6907. in Python because an ``\code{int} object is not subscriptable''.}
  6908. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6909. design choices as \racket{Racket}\python{Python}, except that much of the
  6910. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6911. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6912. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6913. \python{MyPy} reports a compile-time error
  6914. %
  6915. \racket{because Racket expects the type of the argument to be of the form
  6916. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6917. %
  6918. \python{stating that a ``value of type \code{int} is not indexable''.}
  6919. The \LangIf{} language performs type checking during compilation just as
  6920. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6921. the alternative choice, that is, a dynamically typed language like
  6922. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6923. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6924. restrictive, for example, rejecting \racket{\code{(not
  6925. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6926. fairly simple because the focus of this book is on compilation and not
  6927. type systems, about which there are already several excellent
  6928. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6929. This chapter is organized as follows. We begin by defining the syntax
  6930. and interpreter for the \LangIf{} language
  6931. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6932. checking and define a type checker for \LangIf{}
  6933. (section~\ref{sec:type-check-Lif}).
  6934. %
  6935. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6936. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6937. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6938. %
  6939. The remaining sections of this chapter discuss how Booleans and
  6940. conditional control flow require changes to the existing compiler
  6941. passes and the addition of new ones. We introduce the \code{shrink}
  6942. pass to translate some operators into others, thereby reducing the
  6943. number of operators that need to be handled in later passes.
  6944. %
  6945. The main event of this chapter is the \code{explicate\_control} pass
  6946. that is responsible for translating \code{if}s into conditional
  6947. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6948. %
  6949. Regarding register allocation, there is the interesting question of
  6950. how to handle conditional \code{goto}s during liveness analysis.
  6951. \section{The \LangIf{} Language}
  6952. \label{sec:lang-if}
  6953. Definitions of the concrete syntax and abstract syntax of the
  6954. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6955. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6956. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6957. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6958. %
  6959. \python{, and the \code{if} statement}. We expand the set of
  6960. operators to include
  6961. \begin{enumerate}
  6962. \item the logical operators \key{and}, \key{or}, and \key{not},
  6963. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6964. for comparing integers or Booleans for equality, and
  6965. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6966. comparing integers.
  6967. \end{enumerate}
  6968. \racket{We reorganize the abstract syntax for the primitive
  6969. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6970. rule for all of them. This means that the grammar no longer checks
  6971. whether the arity of an operators matches the number of
  6972. arguments. That responsibility is moved to the type checker for
  6973. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6974. \newcommand{\LifGrammarRacket}{
  6975. \begin{array}{lcl}
  6976. \Type &::=& \key{Boolean} \\
  6977. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6978. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6979. \Exp &::=& \itm{bool}
  6980. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6981. \MID (\key{not}\;\Exp) \\
  6982. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6983. \end{array}
  6984. }
  6985. \newcommand{\LifASTRacket}{
  6986. \begin{array}{lcl}
  6987. \Type &::=& \key{Boolean} \\
  6988. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6989. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6990. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6991. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6992. \end{array}
  6993. }
  6994. \newcommand{\LintOpAST}{
  6995. \begin{array}{rcl}
  6996. \Type &::=& \key{Integer} \\
  6997. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6998. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6999. \end{array}
  7000. }
  7001. \newcommand{\LifGrammarPython}{
  7002. \begin{array}{rcl}
  7003. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7004. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7005. \MID \key{not}~\Exp \\
  7006. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7007. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7008. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7009. \end{array}
  7010. }
  7011. \newcommand{\LifASTPython}{
  7012. \begin{array}{lcl}
  7013. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7014. \itm{unaryop} &::=& \code{Not()} \\
  7015. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7016. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7017. \Exp &::=& \BOOL{\itm{bool}}
  7018. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7019. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7020. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7021. \end{array}
  7022. }
  7023. \begin{figure}[tp]
  7024. \centering
  7025. \begin{tcolorbox}[colback=white]
  7026. {\if\edition\racketEd
  7027. \[
  7028. \begin{array}{l}
  7029. \gray{\LintGrammarRacket{}} \\ \hline
  7030. \gray{\LvarGrammarRacket{}} \\ \hline
  7031. \LifGrammarRacket{} \\
  7032. \begin{array}{lcl}
  7033. \LangIfM{} &::=& \Exp
  7034. \end{array}
  7035. \end{array}
  7036. \]
  7037. \fi}
  7038. {\if\edition\pythonEd
  7039. \[
  7040. \begin{array}{l}
  7041. \gray{\LintGrammarPython} \\ \hline
  7042. \gray{\LvarGrammarPython} \\ \hline
  7043. \LifGrammarPython \\
  7044. \begin{array}{rcl}
  7045. \LangIfM{} &::=& \Stmt^{*}
  7046. \end{array}
  7047. \end{array}
  7048. \]
  7049. \fi}
  7050. \end{tcolorbox}
  7051. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7052. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7053. \label{fig:Lif-concrete-syntax}
  7054. \end{figure}
  7055. \begin{figure}[tp]
  7056. %\begin{minipage}{0.66\textwidth}
  7057. \begin{tcolorbox}[colback=white]
  7058. \centering
  7059. {\if\edition\racketEd
  7060. \[
  7061. \begin{array}{l}
  7062. \gray{\LintOpAST} \\ \hline
  7063. \gray{\LvarASTRacket{}} \\ \hline
  7064. \LifASTRacket{} \\
  7065. \begin{array}{lcl}
  7066. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7067. \end{array}
  7068. \end{array}
  7069. \]
  7070. \fi}
  7071. {\if\edition\pythonEd
  7072. \[
  7073. \begin{array}{l}
  7074. \gray{\LintASTPython} \\ \hline
  7075. \gray{\LvarASTPython} \\ \hline
  7076. \LifASTPython \\
  7077. \begin{array}{lcl}
  7078. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7079. \end{array}
  7080. \end{array}
  7081. \]
  7082. \fi}
  7083. \end{tcolorbox}
  7084. %\end{minipage}
  7085. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  7086. \index{subject}{IfExp@\IFNAME{}}
  7087. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  7088. \index{subject}{and@\ANDNAME{}}
  7089. \index{subject}{or@\ORNAME{}}
  7090. \index{subject}{not@\NOTNAME{}}
  7091. \index{subject}{equal@\EQNAME{}}
  7092. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7093. \racket{
  7094. \index{subject}{lessthan@\texttt{<}}
  7095. \index{subject}{lessthaneq@\texttt{<=}}
  7096. \index{subject}{greaterthan@\texttt{>}}
  7097. \index{subject}{greaterthaneq@\texttt{>=}}
  7098. }
  7099. \python{
  7100. \index{subject}{BoolOp@\texttt{BoolOp}}
  7101. \index{subject}{Compare@\texttt{Compare}}
  7102. \index{subject}{Lt@\texttt{Lt}}
  7103. \index{subject}{LtE@\texttt{LtE}}
  7104. \index{subject}{Gt@\texttt{Gt}}
  7105. \index{subject}{GtE@\texttt{GtE}}
  7106. }
  7107. \caption{The abstract syntax of \LangIf{}.}
  7108. \label{fig:Lif-syntax}
  7109. \end{figure}
  7110. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7111. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7112. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7113. evaluate to the corresponding Boolean values. The conditional
  7114. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7115. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7116. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7117. \code{or}, and \code{not} behave according to propositional logic. In
  7118. addition, the \code{and} and \code{or} operations perform
  7119. \emph{short-circuit evaluation}.
  7120. %
  7121. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7122. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7123. %
  7124. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7125. evaluated if $e_1$ evaluates to \TRUE{}.
  7126. \racket{With the increase in the number of primitive operations, the
  7127. interpreter would become repetitive without some care. We refactor
  7128. the case for \code{Prim}, moving the code that differs with each
  7129. operation into the \code{interp\_op} method shown in
  7130. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7131. \code{or} operations separately because of their short-circuiting
  7132. behavior.}
  7133. \begin{figure}[tbp]
  7134. \begin{tcolorbox}[colback=white]
  7135. {\if\edition\racketEd
  7136. \begin{lstlisting}
  7137. (define interp-Lif-class
  7138. (class interp-Lvar-class
  7139. (super-new)
  7140. (define/public (interp_op op) ...)
  7141. (define/override ((interp_exp env) e)
  7142. (define recur (interp_exp env))
  7143. (match e
  7144. [(Bool b) b]
  7145. [(If cnd thn els)
  7146. (match (recur cnd)
  7147. [#t (recur thn)]
  7148. [#f (recur els)])]
  7149. [(Prim 'and (list e1 e2))
  7150. (match (recur e1)
  7151. [#t (match (recur e2) [#t #t] [#f #f])]
  7152. [#f #f])]
  7153. [(Prim 'or (list e1 e2))
  7154. (define v1 (recur e1))
  7155. (match v1
  7156. [#t #t]
  7157. [#f (match (recur e2) [#t #t] [#f #f])])]
  7158. [(Prim op args)
  7159. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7160. [else ((super interp_exp env) e)]))
  7161. ))
  7162. (define (interp_Lif p)
  7163. (send (new interp-Lif-class) interp_program p))
  7164. \end{lstlisting}
  7165. \fi}
  7166. {\if\edition\pythonEd
  7167. \begin{lstlisting}
  7168. class InterpLif(InterpLvar):
  7169. def interp_exp(self, e, env):
  7170. match e:
  7171. case IfExp(test, body, orelse):
  7172. if self.interp_exp(test, env):
  7173. return self.interp_exp(body, env)
  7174. else:
  7175. return self.interp_exp(orelse, env)
  7176. case UnaryOp(Not(), v):
  7177. return not self.interp_exp(v, env)
  7178. case BoolOp(And(), values):
  7179. if self.interp_exp(values[0], env):
  7180. return self.interp_exp(values[1], env)
  7181. else:
  7182. return False
  7183. case BoolOp(Or(), values):
  7184. if self.interp_exp(values[0], env):
  7185. return True
  7186. else:
  7187. return self.interp_exp(values[1], env)
  7188. case Compare(left, [cmp], [right]):
  7189. l = self.interp_exp(left, env)
  7190. r = self.interp_exp(right, env)
  7191. return self.interp_cmp(cmp)(l, r)
  7192. case _:
  7193. return super().interp_exp(e, env)
  7194. def interp_stmts(self, ss, env):
  7195. if len(ss) == 0:
  7196. return
  7197. match ss[0]:
  7198. case If(test, body, orelse):
  7199. if self.interp_exp(test, env):
  7200. return self.interp_stmts(body + ss[1:], env)
  7201. else:
  7202. return self.interp_stmts(orelse + ss[1:], env)
  7203. case _:
  7204. return super().interp_stmts(ss, env)
  7205. ...
  7206. \end{lstlisting}
  7207. \fi}
  7208. \end{tcolorbox}
  7209. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7210. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7211. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7212. \label{fig:interp-Lif}
  7213. \end{figure}
  7214. {\if\edition\racketEd
  7215. \begin{figure}[tbp]
  7216. \begin{tcolorbox}[colback=white]
  7217. \begin{lstlisting}
  7218. (define/public (interp_op op)
  7219. (match op
  7220. ['+ fx+]
  7221. ['- fx-]
  7222. ['read read-fixnum]
  7223. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7224. ['eq? (lambda (v1 v2)
  7225. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7226. (and (boolean? v1) (boolean? v2))
  7227. (and (vector? v1) (vector? v2)))
  7228. (eq? v1 v2)]))]
  7229. ['< (lambda (v1 v2)
  7230. (cond [(and (fixnum? v1) (fixnum? v2))
  7231. (< v1 v2)]))]
  7232. ['<= (lambda (v1 v2)
  7233. (cond [(and (fixnum? v1) (fixnum? v2))
  7234. (<= v1 v2)]))]
  7235. ['> (lambda (v1 v2)
  7236. (cond [(and (fixnum? v1) (fixnum? v2))
  7237. (> v1 v2)]))]
  7238. ['>= (lambda (v1 v2)
  7239. (cond [(and (fixnum? v1) (fixnum? v2))
  7240. (>= v1 v2)]))]
  7241. [else (error 'interp_op "unknown operator")]))
  7242. \end{lstlisting}
  7243. \end{tcolorbox}
  7244. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7245. \label{fig:interp-op-Lif}
  7246. \end{figure}
  7247. \fi}
  7248. {\if\edition\pythonEd
  7249. \begin{figure}
  7250. \begin{tcolorbox}[colback=white]
  7251. \begin{lstlisting}
  7252. class InterpLif(InterpLvar):
  7253. ...
  7254. def interp_cmp(self, cmp):
  7255. match cmp:
  7256. case Lt():
  7257. return lambda x, y: x < y
  7258. case LtE():
  7259. return lambda x, y: x <= y
  7260. case Gt():
  7261. return lambda x, y: x > y
  7262. case GtE():
  7263. return lambda x, y: x >= y
  7264. case Eq():
  7265. return lambda x, y: x == y
  7266. case NotEq():
  7267. return lambda x, y: x != y
  7268. \end{lstlisting}
  7269. \end{tcolorbox}
  7270. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7271. \label{fig:interp-cmp-Lif}
  7272. \end{figure}
  7273. \fi}
  7274. \section{Type Checking \LangIf{} Programs}
  7275. \label{sec:type-check-Lif}
  7276. \index{subject}{type checking}
  7277. \index{subject}{semantic analysis}
  7278. It is helpful to think about type checking in two complementary
  7279. ways. A type checker predicts the type of value that will be produced
  7280. by each expression in the program. For \LangIf{}, we have just two types,
  7281. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  7282. {\if\edition\racketEd
  7283. \begin{lstlisting}
  7284. (+ 10 (- (+ 12 20)))
  7285. \end{lstlisting}
  7286. \fi}
  7287. {\if\edition\pythonEd
  7288. \begin{lstlisting}
  7289. 10 + -(12 + 20)
  7290. \end{lstlisting}
  7291. \fi}
  7292. \noindent produces a value of type \INTTY{}, whereas
  7293. {\if\edition\racketEd
  7294. \begin{lstlisting}
  7295. (and (not #f) #t)
  7296. \end{lstlisting}
  7297. \fi}
  7298. {\if\edition\pythonEd
  7299. \begin{lstlisting}
  7300. (not False) and True
  7301. \end{lstlisting}
  7302. \fi}
  7303. \noindent produces a value of type \BOOLTY{}.
  7304. A second way to think about type checking is that it enforces a set of
  7305. rules about which operators can be applied to which kinds of
  7306. values. For example, our type checker for \LangIf{} signals an error
  7307. for the following expression:
  7308. %
  7309. {\if\edition\racketEd
  7310. \begin{lstlisting}
  7311. (not (+ 10 (- (+ 12 20))))
  7312. \end{lstlisting}
  7313. \fi}
  7314. {\if\edition\pythonEd
  7315. \begin{lstlisting}
  7316. not (10 + -(12 + 20))
  7317. \end{lstlisting}
  7318. \fi}
  7319. \noindent The subexpression
  7320. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7321. \python{\code{(10 + -(12 + 20))}}
  7322. has type \INTTY{}, but the type checker enforces the rule that the
  7323. argument of \code{not} must be an expression of type \BOOLTY{}.
  7324. We implement type checking using classes and methods because they
  7325. provide the open recursion needed to reuse code as we extend the type
  7326. checker in subsequent chapters, analogous to the use of classes and methods
  7327. for the interpreters (section~\ref{sec:extensible-interp}).
  7328. We separate the type checker for the \LangVar{} subset into its own
  7329. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7330. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7331. from the type checker for \LangVar{}. These type checkers are in the
  7332. files
  7333. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7334. and
  7335. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7336. of the support code.
  7337. %
  7338. Each type checker is a structurally recursive function over the AST.
  7339. Given an input expression \code{e}, the type checker either signals an
  7340. error or returns \racket{an expression and} its type.
  7341. %
  7342. \racket{It returns an expression because there are situations in which
  7343. we want to change or update the expression.}
  7344. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7345. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7346. constant is \INTTY{}. To handle variables, the type checker uses the
  7347. environment \code{env} to map variables to types.
  7348. %
  7349. \racket{Consider the case for \key{let}. We type check the
  7350. initializing expression to obtain its type \key{T} and then
  7351. associate type \code{T} with the variable \code{x} in the
  7352. environment used to type check the body of the \key{let}. Thus,
  7353. when the type checker encounters a use of variable \code{x}, it can
  7354. find its type in the environment.}
  7355. %
  7356. \python{Consider the case for assignment. We type check the
  7357. initializing expression to obtain its type \key{t}. If the variable
  7358. \code{lhs.id} is already in the environment because there was a
  7359. prior assignment, we check that this initializer has the same type
  7360. as the prior one. If this is the first assignment to the variable,
  7361. we associate type \code{t} with the variable \code{lhs.id} in the
  7362. environment. Thus, when the type checker encounters a use of
  7363. variable \code{x}, it can find its type in the environment.}
  7364. %
  7365. \racket{Regarding primitive operators, we recursively analyze the
  7366. arguments and then invoke \code{type\_check\_op} to check whether
  7367. the argument types are allowed.}
  7368. %
  7369. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7370. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7371. \racket{Several auxiliary methods are used in the type checker. The
  7372. method \code{operator-types} defines a dictionary that maps the
  7373. operator names to their parameter and return types. The
  7374. \code{type-equal?} method determines whether two types are equal,
  7375. which for now simply dispatches to \code{equal?} (deep
  7376. equality). The \code{check-type-equal?} method triggers an error if
  7377. the two types are not equal. The \code{type-check-op} method looks
  7378. up the operator in the \code{operator-types} dictionary and then
  7379. checks whether the argument types are equal to the parameter types.
  7380. The result is the return type of the operator.}
  7381. %
  7382. \python{The auxiliary method \code{check\_type\_equal} triggers
  7383. an error if the two types are not equal.}
  7384. \begin{figure}[tbp]
  7385. \begin{tcolorbox}[colback=white]
  7386. {\if\edition\racketEd
  7387. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7388. (define type-check-Lvar-class
  7389. (class object%
  7390. (super-new)
  7391. (define/public (operator-types)
  7392. '((+ . ((Integer Integer) . Integer))
  7393. (- . ((Integer Integer) . Integer))
  7394. (read . (() . Integer))))
  7395. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7396. (define/public (check-type-equal? t1 t2 e)
  7397. (unless (type-equal? t1 t2)
  7398. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7399. (define/public (type-check-op op arg-types e)
  7400. (match (dict-ref (operator-types) op)
  7401. [`(,param-types . ,return-type)
  7402. (for ([at arg-types] [pt param-types])
  7403. (check-type-equal? at pt e))
  7404. return-type]
  7405. [else (error 'type-check-op "unrecognized ~a" op)]))
  7406. (define/public (type-check-exp env)
  7407. (lambda (e)
  7408. (match e
  7409. [(Int n) (values (Int n) 'Integer)]
  7410. [(Var x) (values (Var x) (dict-ref env x))]
  7411. [(Let x e body)
  7412. (define-values (e^ Te) ((type-check-exp env) e))
  7413. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7414. (values (Let x e^ b) Tb)]
  7415. [(Prim op es)
  7416. (define-values (new-es ts)
  7417. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7418. (values (Prim op new-es) (type-check-op op ts e))]
  7419. [else (error 'type-check-exp "couldn't match" e)])))
  7420. (define/public (type-check-program e)
  7421. (match e
  7422. [(Program info body)
  7423. (define-values (body^ Tb) ((type-check-exp '()) body))
  7424. (check-type-equal? Tb 'Integer body)
  7425. (Program info body^)]
  7426. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7427. ))
  7428. (define (type-check-Lvar p)
  7429. (send (new type-check-Lvar-class) type-check-program p))
  7430. \end{lstlisting}
  7431. \fi}
  7432. {\if\edition\pythonEd
  7433. \begin{lstlisting}[escapechar=`]
  7434. class TypeCheckLvar:
  7435. def check_type_equal(self, t1, t2, e):
  7436. if t1 != t2:
  7437. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7438. raise Exception(msg)
  7439. def type_check_exp(self, e, env):
  7440. match e:
  7441. case BinOp(left, (Add() | Sub()), right):
  7442. l = self.type_check_exp(left, env)
  7443. check_type_equal(l, int, left)
  7444. r = self.type_check_exp(right, env)
  7445. check_type_equal(r, int, right)
  7446. return int
  7447. case UnaryOp(USub(), v):
  7448. t = self.type_check_exp(v, env)
  7449. check_type_equal(t, int, v)
  7450. return int
  7451. case Name(id):
  7452. return env[id]
  7453. case Constant(value) if isinstance(value, int):
  7454. return int
  7455. case Call(Name('input_int'), []):
  7456. return int
  7457. def type_check_stmts(self, ss, env):
  7458. if len(ss) == 0:
  7459. return
  7460. match ss[0]:
  7461. case Assign([lhs], value):
  7462. t = self.type_check_exp(value, env)
  7463. if lhs.id in env:
  7464. check_type_equal(env[lhs.id], t, value)
  7465. else:
  7466. env[lhs.id] = t
  7467. return self.type_check_stmts(ss[1:], env)
  7468. case Expr(Call(Name('print'), [arg])):
  7469. t = self.type_check_exp(arg, env)
  7470. check_type_equal(t, int, arg)
  7471. return self.type_check_stmts(ss[1:], env)
  7472. case Expr(value):
  7473. self.type_check_exp(value, env)
  7474. return self.type_check_stmts(ss[1:], env)
  7475. def type_check_P(self, p):
  7476. match p:
  7477. case Module(body):
  7478. self.type_check_stmts(body, {})
  7479. \end{lstlisting}
  7480. \fi}
  7481. \end{tcolorbox}
  7482. \caption{Type checker for the \LangVar{} language.}
  7483. \label{fig:type-check-Lvar}
  7484. \end{figure}
  7485. \begin{figure}[tbp]
  7486. \begin{tcolorbox}[colback=white]
  7487. {\if\edition\racketEd
  7488. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7489. (define type-check-Lif-class
  7490. (class type-check-Lvar-class
  7491. (super-new)
  7492. (inherit check-type-equal?)
  7493. (define/override (operator-types)
  7494. (append '((and . ((Boolean Boolean) . Boolean))
  7495. (or . ((Boolean Boolean) . Boolean))
  7496. (< . ((Integer Integer) . Boolean))
  7497. (<= . ((Integer Integer) . Boolean))
  7498. (> . ((Integer Integer) . Boolean))
  7499. (>= . ((Integer Integer) . Boolean))
  7500. (not . ((Boolean) . Boolean)))
  7501. (super operator-types)))
  7502. (define/override (type-check-exp env)
  7503. (lambda (e)
  7504. (match e
  7505. [(Bool b) (values (Bool b) 'Boolean)]
  7506. [(Prim 'eq? (list e1 e2))
  7507. (define-values (e1^ T1) ((type-check-exp env) e1))
  7508. (define-values (e2^ T2) ((type-check-exp env) e2))
  7509. (check-type-equal? T1 T2 e)
  7510. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7511. [(If cnd thn els)
  7512. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7513. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7514. (define-values (els^ Te) ((type-check-exp env) els))
  7515. (check-type-equal? Tc 'Boolean e)
  7516. (check-type-equal? Tt Te e)
  7517. (values (If cnd^ thn^ els^) Te)]
  7518. [else ((super type-check-exp env) e)])))
  7519. ))
  7520. (define (type-check-Lif p)
  7521. (send (new type-check-Lif-class) type-check-program p))
  7522. \end{lstlisting}
  7523. \fi}
  7524. {\if\edition\pythonEd
  7525. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7526. class TypeCheckLif(TypeCheckLvar):
  7527. def type_check_exp(self, e, env):
  7528. match e:
  7529. case Constant(value) if isinstance(value, bool):
  7530. return bool
  7531. case BinOp(left, Sub(), right):
  7532. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7533. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7534. return int
  7535. case UnaryOp(Not(), v):
  7536. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7537. return bool
  7538. case BoolOp(op, values):
  7539. left = values[0] ; right = values[1]
  7540. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7541. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7542. return bool
  7543. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7544. or isinstance(cmp, NotEq):
  7545. l = self.type_check_exp(left, env)
  7546. r = self.type_check_exp(right, env)
  7547. check_type_equal(l, r, e)
  7548. return bool
  7549. case Compare(left, [cmp], [right]):
  7550. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7551. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7552. return bool
  7553. case IfExp(test, body, orelse):
  7554. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7555. b = self.type_check_exp(body, env)
  7556. o = self.type_check_exp(orelse, env)
  7557. check_type_equal(b, o, e)
  7558. return b
  7559. case _:
  7560. return super().type_check_exp(e, env)
  7561. def type_check_stmts(self, ss, env):
  7562. if len(ss) == 0:
  7563. return
  7564. match ss[0]:
  7565. case If(test, body, orelse):
  7566. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7567. b = self.type_check_stmts(body, env)
  7568. o = self.type_check_stmts(orelse, env)
  7569. check_type_equal(b, o, ss[0])
  7570. return self.type_check_stmts(ss[1:], env)
  7571. case _:
  7572. return super().type_check_stmts(ss, env)
  7573. \end{lstlisting}
  7574. \fi}
  7575. \end{tcolorbox}
  7576. \caption{Type checker for the \LangIf{} language.}
  7577. \label{fig:type-check-Lif}
  7578. \end{figure}
  7579. The definition of the type checker for \LangIf{} is shown in
  7580. figure~\ref{fig:type-check-Lif}.
  7581. %
  7582. The type of a Boolean constant is \BOOLTY{}.
  7583. %
  7584. \racket{The \code{operator-types} function adds dictionary entries for
  7585. the new operators.}
  7586. %
  7587. \python{Logical not requires its argument to be a \BOOLTY{} and
  7588. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7589. %
  7590. The equality operator requires the two arguments to have the same type,
  7591. and therefore we handle it separately from the other operators.
  7592. %
  7593. \python{The other comparisons (less-than, etc.) require their
  7594. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7595. %
  7596. The condition of an \code{if} must
  7597. be of \BOOLTY{} type, and the two branches must have the same type.
  7598. \begin{exercise}\normalfont\normalsize
  7599. Create ten new test programs in \LangIf{}. Half the programs should
  7600. have a type error. For those programs, create an empty file with the
  7601. same base name and with file extension \code{.tyerr}. For example, if
  7602. the test
  7603. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7604. is expected to error, then create
  7605. an empty file named \code{cond\_test\_14.tyerr}.
  7606. %
  7607. \racket{This indicates to \code{interp-tests} and
  7608. \code{compiler-tests} that a type error is expected. }
  7609. %
  7610. The other half of the test programs should not have type errors.
  7611. %
  7612. \racket{In the \code{run-tests.rkt} script, change the second argument
  7613. of \code{interp-tests} and \code{compiler-tests} to
  7614. \code{type-check-Lif}, which causes the type checker to run prior to
  7615. the compiler passes. Temporarily change the \code{passes} to an
  7616. empty list and run the script, thereby checking that the new test
  7617. programs either type check or do not, as intended.}
  7618. %
  7619. Run the test script to check that these test programs type check as
  7620. expected.
  7621. \end{exercise}
  7622. \clearpage
  7623. \section{The \LangCIf{} Intermediate Language}
  7624. \label{sec:Cif}
  7625. {\if\edition\racketEd
  7626. %
  7627. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7628. comparison operators to the \Exp{} nonterminal and the literals
  7629. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7630. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7631. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7632. comparison operation and the branches are \code{goto} statements,
  7633. making it straightforward to compile \code{if} statements to x86. The
  7634. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7635. expressions. A \code{goto} statement transfers control to the $\Tail$
  7636. expression corresponding to its label.
  7637. %
  7638. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7639. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7640. defines its abstract syntax.
  7641. %
  7642. \fi}
  7643. %
  7644. {\if\edition\pythonEd
  7645. %
  7646. The output of \key{explicate\_control} is a language similar to the
  7647. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7648. \code{goto} statements, so we name it \LangCIf{}.
  7649. %
  7650. The \LangCIf{} language supports the same operators as \LangIf{} but
  7651. the arguments of operators are restricted to atomic expressions. The
  7652. \LangCIf{} language does not include \code{if} expressions but it does
  7653. include a restricted form of \code{if} statement. The condition must be
  7654. a comparison and the two branches may only contain \code{goto}
  7655. statements. These restrictions make it easier to translate \code{if}
  7656. statements to x86. The \LangCIf{} language also adds a \code{return}
  7657. statement to finish the program with a specified value.
  7658. %
  7659. The \key{CProgram} construct contains a dictionary mapping labels to
  7660. lists of statements that end with a \code{return} statement, a
  7661. \code{goto}, or a conditional \code{goto}.
  7662. %% Statement lists of this
  7663. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7664. %% is a control transfer at the end and control only enters at the
  7665. %% beginning of the list, which is marked by the label.
  7666. %
  7667. A \code{goto} statement transfers control to the sequence of statements
  7668. associated with its label.
  7669. %
  7670. The concrete syntax for \LangCIf{} is defined in
  7671. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7672. in figure~\ref{fig:c1-syntax}.
  7673. %
  7674. \fi}
  7675. %
  7676. \newcommand{\CifGrammarRacket}{
  7677. \begin{array}{lcl}
  7678. \Atm &::=& \itm{bool} \\
  7679. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7680. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7681. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7682. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7683. \end{array}
  7684. }
  7685. \newcommand{\CifASTRacket}{
  7686. \begin{array}{lcl}
  7687. \Atm &::=& \BOOL{\itm{bool}} \\
  7688. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7689. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7690. \Tail &::= & \GOTO{\itm{label}} \\
  7691. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7692. \end{array}
  7693. }
  7694. \newcommand{\CifGrammarPython}{
  7695. \begin{array}{lcl}
  7696. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7697. \Exp &::= & \Atm \MID \CREAD{}
  7698. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7699. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7700. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7701. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7702. &\MID& \CASSIGN{\Var}{\Exp}
  7703. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7704. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7705. \end{array}
  7706. }
  7707. \newcommand{\CifASTPython}{
  7708. \begin{array}{lcl}
  7709. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7710. \Exp &::= & \Atm \MID \READ{} \\
  7711. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7712. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7713. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7714. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7715. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7716. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7717. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7718. \end{array}
  7719. }
  7720. \begin{figure}[tbp]
  7721. \begin{tcolorbox}[colback=white]
  7722. \small
  7723. {\if\edition\racketEd
  7724. \[
  7725. \begin{array}{l}
  7726. \gray{\CvarGrammarRacket} \\ \hline
  7727. \CifGrammarRacket \\
  7728. \begin{array}{lcl}
  7729. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7730. \end{array}
  7731. \end{array}
  7732. \]
  7733. \fi}
  7734. {\if\edition\pythonEd
  7735. \[
  7736. \begin{array}{l}
  7737. \CifGrammarPython \\
  7738. \begin{array}{lcl}
  7739. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7740. \end{array}
  7741. \end{array}
  7742. \]
  7743. \fi}
  7744. \end{tcolorbox}
  7745. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7746. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7747. \label{fig:c1-concrete-syntax}
  7748. \end{figure}
  7749. \begin{figure}[tp]
  7750. \begin{tcolorbox}[colback=white]
  7751. \small
  7752. {\if\edition\racketEd
  7753. \[
  7754. \begin{array}{l}
  7755. \gray{\CvarASTRacket} \\ \hline
  7756. \CifASTRacket \\
  7757. \begin{array}{lcl}
  7758. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7759. \end{array}
  7760. \end{array}
  7761. \]
  7762. \fi}
  7763. {\if\edition\pythonEd
  7764. \[
  7765. \begin{array}{l}
  7766. \CifASTPython \\
  7767. \begin{array}{lcl}
  7768. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7769. \end{array}
  7770. \end{array}
  7771. \]
  7772. \fi}
  7773. \end{tcolorbox}
  7774. \racket{
  7775. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7776. }
  7777. \index{subject}{Goto@\texttt{Goto}}
  7778. \index{subject}{Return@\texttt{Return}}
  7779. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7780. (figure~\ref{fig:c0-syntax})}.}
  7781. \label{fig:c1-syntax}
  7782. \end{figure}
  7783. \section{The \LangXIf{} Language}
  7784. \label{sec:x86-if}
  7785. \index{subject}{x86} To implement the new logical operations, the
  7786. comparison operations, and the \key{if} expression\python{ and
  7787. statement}, we delve further into the x86
  7788. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7789. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7790. subset of x86, which includes instructions for logical operations,
  7791. comparisons, and \racket{conditional} jumps.
  7792. %
  7793. \python{The abstract syntax for an \LangXIf{} program contains a
  7794. dictionary mapping labels to sequences of instructions, each of
  7795. which we refer to as a \emph{basic block}\index{subject}{basic
  7796. block}.}
  7797. One challenge is that x86 does not provide an instruction that
  7798. directly implements logical negation (\code{not} in \LangIf{} and
  7799. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7800. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7801. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7802. bit of its arguments, and writes the results into its second argument.
  7803. Recall the following truth table for exclusive-or:
  7804. \begin{center}
  7805. \begin{tabular}{l|cc}
  7806. & 0 & 1 \\ \hline
  7807. 0 & 0 & 1 \\
  7808. 1 & 1 & 0
  7809. \end{tabular}
  7810. \end{center}
  7811. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7812. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7813. for the bit $1$, the result is the opposite of the second bit. Thus,
  7814. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7815. the first argument, as follows, where $\Arg$ is the translation of
  7816. $\Atm$ to x86:
  7817. \[
  7818. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7819. \qquad\Rightarrow\qquad
  7820. \begin{array}{l}
  7821. \key{movq}~ \Arg\key{,} \Var\\
  7822. \key{xorq}~ \key{\$1,} \Var
  7823. \end{array}
  7824. \]
  7825. \newcommand{\GrammarXIf}{
  7826. \begin{array}{lcl}
  7827. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7828. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7829. \Arg &::=& \key{\%}\itm{bytereg}\\
  7830. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7831. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7832. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7833. \MID \key{set}cc~\Arg
  7834. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7835. &\MID& \key{j}cc~\itm{label} \\
  7836. \end{array}
  7837. }
  7838. \begin{figure}[tp]
  7839. \begin{tcolorbox}[colback=white]
  7840. \[
  7841. \begin{array}{l}
  7842. \gray{\GrammarXInt} \\ \hline
  7843. \GrammarXIf \\
  7844. \begin{array}{lcl}
  7845. \LangXIfM{} &::= & \key{.globl main} \\
  7846. & & \key{main:} \; \Instr\ldots
  7847. \end{array}
  7848. \end{array}
  7849. \]
  7850. \end{tcolorbox}
  7851. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7852. \label{fig:x86-1-concrete}
  7853. \end{figure}
  7854. \newcommand{\ASTXIfRacket}{
  7855. \begin{array}{lcl}
  7856. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7857. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7858. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7859. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7860. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7861. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7862. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7863. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7864. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7865. \end{array}
  7866. }
  7867. \begin{figure}[tp]
  7868. \begin{tcolorbox}[colback=white]
  7869. \small
  7870. {\if\edition\racketEd
  7871. \[\arraycolsep=3pt
  7872. \begin{array}{l}
  7873. \gray{\ASTXIntRacket} \\ \hline
  7874. \ASTXIfRacket \\
  7875. \begin{array}{lcl}
  7876. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7877. \end{array}
  7878. \end{array}
  7879. \]
  7880. \fi}
  7881. %
  7882. {\if\edition\pythonEd
  7883. \[
  7884. \begin{array}{lcl}
  7885. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7886. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7887. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7888. \MID \BYTEREG{\itm{bytereg}} \\
  7889. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7890. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7891. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7892. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7893. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7894. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7895. \MID \PUSHQ{\Arg}} \\
  7896. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7897. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7898. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7899. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7900. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7901. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7902. \Block &::= & \Instr^{+} \\
  7903. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7904. \end{array}
  7905. \]
  7906. \fi}
  7907. \end{tcolorbox}
  7908. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7909. \label{fig:x86-1}
  7910. \end{figure}
  7911. Next we consider the x86 instructions that are relevant for compiling
  7912. the comparison operations. The \key{cmpq} instruction compares its two
  7913. arguments to determine whether one argument is less than, equal to, or
  7914. greater than the other argument. The \key{cmpq} instruction is unusual
  7915. regarding the order of its arguments and where the result is
  7916. placed. The argument order is backward: if you want to test whether
  7917. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7918. \key{cmpq} is placed in the special EFLAGS register. This register
  7919. cannot be accessed directly, but it can be queried by a number of
  7920. instructions, including the \key{set} instruction. The instruction
  7921. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7922. depending on whether the contents of the EFLAGS register matches the
  7923. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7924. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7925. The \key{set} instruction has a quirk in that its destination argument
  7926. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7927. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7928. register. Thankfully, the \key{movzbq} instruction can be used to
  7929. move from a single-byte register to a normal 64-bit register. The
  7930. abstract syntax for the \code{set} instruction differs from the
  7931. concrete syntax in that it separates the instruction name from the
  7932. condition code.
  7933. \python{The x86 instructions for jumping are relevant to the
  7934. compilation of \key{if} expressions.}
  7935. %
  7936. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7937. counter to the address of the instruction after the specified
  7938. label.}
  7939. %
  7940. \racket{The x86 instruction for conditional jump is relevant to the
  7941. compilation of \key{if} expressions.}
  7942. %
  7943. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7944. counter to point to the instruction after \itm{label}, depending on
  7945. whether the result in the EFLAGS register matches the condition code
  7946. \itm{cc}; otherwise, the jump instruction falls through to the next
  7947. instruction. Like the abstract syntax for \code{set}, the abstract
  7948. syntax for conditional jump separates the instruction name from the
  7949. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7950. corresponds to \code{jle foo}. Because the conditional jump instruction
  7951. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7952. a \key{cmpq} instruction to set the EFLAGS register.
  7953. \section{Shrink the \LangIf{} Language}
  7954. \label{sec:shrink-Lif}
  7955. The \LangIf{} language includes several features that are easily
  7956. expressible with other features. For example, \code{and} and \code{or}
  7957. are expressible using \code{if} as follows.
  7958. \begin{align*}
  7959. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7960. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7961. \end{align*}
  7962. By performing these translations in the front end of the compiler,
  7963. subsequent passes of the compiler do not need to deal with these features,
  7964. thus making the passes shorter.
  7965. On the other hand, translations sometimes reduce the efficiency of the
  7966. generated code by increasing the number of instructions. For example,
  7967. expressing subtraction in terms of negation
  7968. \[
  7969. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7970. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7971. \]
  7972. produces code with two x86 instructions (\code{negq} and \code{addq})
  7973. instead of just one (\code{subq}).
  7974. \begin{exercise}\normalfont\normalsize
  7975. %
  7976. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7977. the language by translating them to \code{if} expressions in \LangIf{}.
  7978. %
  7979. Create four test programs that involve these operators.
  7980. %
  7981. {\if\edition\racketEd
  7982. In the \code{run-tests.rkt} script, add the following entry for
  7983. \code{shrink} to the list of passes (it should be the only pass at
  7984. this point).
  7985. \begin{lstlisting}
  7986. (list "shrink" shrink interp_Lif type-check-Lif)
  7987. \end{lstlisting}
  7988. This instructs \code{interp-tests} to run the interpreter
  7989. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7990. output of \code{shrink}.
  7991. \fi}
  7992. %
  7993. Run the script to test your compiler on all the test programs.
  7994. \end{exercise}
  7995. {\if\edition\racketEd
  7996. \section{Uniquify Variables}
  7997. \label{sec:uniquify-Lif}
  7998. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7999. \code{if} expressions.
  8000. \begin{exercise}\normalfont\normalsize
  8001. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8002. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8003. \begin{lstlisting}
  8004. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8005. \end{lstlisting}
  8006. Run the script to test your compiler.
  8007. \end{exercise}
  8008. \fi}
  8009. \section{Remove Complex Operands}
  8010. \label{sec:remove-complex-opera-Lif}
  8011. The output language of \code{remove\_complex\_operands} is
  8012. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8013. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8014. but the \code{if} expression is not. All three subexpressions of an
  8015. \code{if} are allowed to be complex expressions, but the operands of
  8016. the \code{not} operator and comparison operators must be atomic.
  8017. %
  8018. \python{We add a new language form, the \code{Begin} expression, to aid
  8019. in the translation of \code{if} expressions. When we recursively
  8020. process the two branches of the \code{if}, we generate temporary
  8021. variables and their initializing expressions. However, these
  8022. expressions may contain side effects and should only be executed
  8023. when the condition of the \code{if} is true (for the ``then''
  8024. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8025. a way to initialize the temporary variables within the two branches
  8026. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8027. form execute the statements $ss$ and then returns the result of
  8028. expression $e$.}
  8029. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8030. the new features in \LangIf{}. In recursively processing
  8031. subexpressions, recall that you should invoke \code{rco\_atom} when
  8032. the output needs to be an \Atm{} (as specified in the grammar for
  8033. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8034. \Exp{}. Regarding \code{if}, it is particularly important
  8035. \textbf{not} to replace its condition with a temporary variable, because
  8036. that would interfere with the generation of high-quality output in the
  8037. upcoming \code{explicate\_control} pass.
  8038. \newcommand{\LifMonadASTRacket}{
  8039. \begin{array}{rcl}
  8040. \Atm &::=& \BOOL{\itm{bool}}\\
  8041. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8042. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8043. \MID \IF{\Exp}{\Exp}{\Exp}
  8044. \end{array}
  8045. }
  8046. \newcommand{\LifMonadASTPython}{
  8047. \begin{array}{rcl}
  8048. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8049. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8050. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8051. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8052. \Atm &::=& \BOOL{\itm{bool}}\\
  8053. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8054. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8055. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8056. \end{array}
  8057. }
  8058. \begin{figure}[tp]
  8059. \centering
  8060. \begin{tcolorbox}[colback=white]
  8061. {\if\edition\racketEd
  8062. \[
  8063. \begin{array}{l}
  8064. \gray{\LvarMonadASTRacket} \\ \hline
  8065. \LifMonadASTRacket \\
  8066. \begin{array}{rcl}
  8067. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8068. \end{array}
  8069. \end{array}
  8070. \]
  8071. \fi}
  8072. {\if\edition\pythonEd
  8073. \[
  8074. \begin{array}{l}
  8075. \gray{\LvarMonadASTPython} \\ \hline
  8076. \LifMonadASTPython \\
  8077. \begin{array}{rcl}
  8078. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8079. \end{array}
  8080. \end{array}
  8081. \]
  8082. \fi}
  8083. \end{tcolorbox}
  8084. \python{\index{subject}{Begin@\texttt{Begin}}}
  8085. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8086. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8087. \label{fig:Lif-anf-syntax}
  8088. \end{figure}
  8089. \begin{exercise}\normalfont\normalsize
  8090. %
  8091. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8092. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8093. %
  8094. Create three new \LangIf{} programs that exercise the interesting
  8095. code in this pass.
  8096. %
  8097. {\if\edition\racketEd
  8098. In the \code{run-tests.rkt} script, add the following entry to the
  8099. list of \code{passes} and then run the script to test your compiler.
  8100. \begin{lstlisting}
  8101. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8102. \end{lstlisting}
  8103. \fi}
  8104. \end{exercise}
  8105. \section{Explicate Control}
  8106. \label{sec:explicate-control-Lif}
  8107. \racket{Recall that the purpose of \code{explicate\_control} is to
  8108. make the order of evaluation explicit in the syntax of the program.
  8109. With the addition of \key{if}, this becomes more interesting.}
  8110. %
  8111. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8112. %
  8113. The main challenge to overcome is that the condition of an \key{if}
  8114. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8115. condition must be a comparison.
  8116. As a motivating example, consider the following program that has an
  8117. \key{if} expression nested in the condition of another \key{if}:%
  8118. \python{\footnote{Programmers rarely write nested \code{if}
  8119. expressions, but it is not uncommon for the condition of an
  8120. \code{if} statement to be a call of a function that also contains an
  8121. \code{if} statement. When such a function is inlined, the result is
  8122. a nested \code{if} that requires the techniques discussed in this
  8123. section.}}
  8124. % cond_test_41.rkt, if_lt_eq.py
  8125. \begin{center}
  8126. \begin{minipage}{0.96\textwidth}
  8127. {\if\edition\racketEd
  8128. \begin{lstlisting}
  8129. (let ([x (read)])
  8130. (let ([y (read)])
  8131. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8132. (+ y 2)
  8133. (+ y 10))))
  8134. \end{lstlisting}
  8135. \fi}
  8136. {\if\edition\pythonEd
  8137. \begin{lstlisting}
  8138. x = input_int()
  8139. y = input_int()
  8140. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8141. \end{lstlisting}
  8142. \fi}
  8143. \end{minipage}
  8144. \end{center}
  8145. %
  8146. The naive way to compile \key{if} and the comparison operations would
  8147. be to handle each of them in isolation, regardless of their context.
  8148. Each comparison would be translated into a \key{cmpq} instruction
  8149. followed by several instructions to move the result from the EFLAGS
  8150. register into a general purpose register or stack location. Each
  8151. \key{if} would be translated into a \key{cmpq} instruction followed by
  8152. a conditional jump. The generated code for the inner \key{if} in this
  8153. example would be as follows:
  8154. \begin{center}
  8155. \begin{minipage}{0.96\textwidth}
  8156. \begin{lstlisting}
  8157. cmpq $1, x
  8158. setl %al
  8159. movzbq %al, tmp
  8160. cmpq $1, tmp
  8161. je then_branch_1
  8162. jmp else_branch_1
  8163. \end{lstlisting}
  8164. \end{minipage}
  8165. \end{center}
  8166. Notice that the three instructions starting with \code{setl} are
  8167. redundant: the conditional jump could come immediately after the first
  8168. \code{cmpq}.
  8169. Our goal is to compile \key{if} expressions so that the relevant
  8170. comparison instruction appears directly before the conditional jump.
  8171. For example, we want to generate the following code for the inner
  8172. \code{if}:
  8173. \begin{center}
  8174. \begin{minipage}{0.96\textwidth}
  8175. \begin{lstlisting}
  8176. cmpq $1, x
  8177. jl then_branch_1
  8178. jmp else_branch_1
  8179. \end{lstlisting}
  8180. \end{minipage}
  8181. \end{center}
  8182. One way to achieve this goal is to reorganize the code at the level of
  8183. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8184. the following code:
  8185. \begin{center}
  8186. \begin{minipage}{0.96\textwidth}
  8187. {\if\edition\racketEd
  8188. \begin{lstlisting}
  8189. (let ([x (read)])
  8190. (let ([y (read)])
  8191. (if (< x 1)
  8192. (if (eq? x 0)
  8193. (+ y 2)
  8194. (+ y 10))
  8195. (if (eq? x 2)
  8196. (+ y 2)
  8197. (+ y 10)))))
  8198. \end{lstlisting}
  8199. \fi}
  8200. {\if\edition\pythonEd
  8201. \begin{lstlisting}
  8202. x = input_int()
  8203. y = input_int()
  8204. print(((y + 2) if x == 0 else (y + 10)) \
  8205. if (x < 1) \
  8206. else ((y + 2) if (x == 2) else (y + 10)))
  8207. \end{lstlisting}
  8208. \fi}
  8209. \end{minipage}
  8210. \end{center}
  8211. Unfortunately, this approach duplicates the two branches from the
  8212. outer \code{if}, and a compiler must never duplicate code! After all,
  8213. the two branches could be very large expressions.
  8214. How can we apply this transformation without duplicating code? In
  8215. other words, how can two different parts of a program refer to one
  8216. piece of code?
  8217. %
  8218. The answer is that we must move away from abstract syntax \emph{trees}
  8219. and instead use \emph{graphs}.
  8220. %
  8221. At the level of x86 assembly, this is straightforward because we can
  8222. label the code for each branch and insert jumps in all the places that
  8223. need to execute the branch. In this way, jump instructions are edges
  8224. in the graph and the basic blocks are the nodes.
  8225. %
  8226. Likewise, our language \LangCIf{} provides the ability to label a
  8227. sequence of statements and to jump to a label via \code{goto}.
  8228. As a preview of what \code{explicate\_control} will do,
  8229. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8230. \code{explicate\_control} on this example. Note how the condition of
  8231. every \code{if} is a comparison operation and that we have not
  8232. duplicated any code but instead have used labels and \code{goto} to
  8233. enable sharing of code.
  8234. \begin{figure}[tbp]
  8235. \begin{tcolorbox}[colback=white]
  8236. {\if\edition\racketEd
  8237. \begin{tabular}{lll}
  8238. \begin{minipage}{0.4\textwidth}
  8239. % cond_test_41.rkt
  8240. \begin{lstlisting}
  8241. (let ([x (read)])
  8242. (let ([y (read)])
  8243. (if (if (< x 1)
  8244. (eq? x 0)
  8245. (eq? x 2))
  8246. (+ y 2)
  8247. (+ y 10))))
  8248. \end{lstlisting}
  8249. \end{minipage}
  8250. &
  8251. $\Rightarrow$
  8252. &
  8253. \begin{minipage}{0.55\textwidth}
  8254. \begin{lstlisting}
  8255. start:
  8256. x = (read);
  8257. y = (read);
  8258. if (< x 1)
  8259. goto block_4;
  8260. else
  8261. goto block_5;
  8262. block_4:
  8263. if (eq? x 0)
  8264. goto block_2;
  8265. else
  8266. goto block_3;
  8267. block_5:
  8268. if (eq? x 2)
  8269. goto block_2;
  8270. else
  8271. goto block_3;
  8272. block_2:
  8273. return (+ y 2);
  8274. block_3:
  8275. return (+ y 10);
  8276. \end{lstlisting}
  8277. \end{minipage}
  8278. \end{tabular}
  8279. \fi}
  8280. {\if\edition\pythonEd
  8281. \begin{tabular}{lll}
  8282. \begin{minipage}{0.4\textwidth}
  8283. % cond_test_41.rkt
  8284. \begin{lstlisting}
  8285. x = input_int()
  8286. y = input_int()
  8287. print(y + 2 \
  8288. if (x == 0 \
  8289. if x < 1 \
  8290. else x == 2) \
  8291. else y + 10)
  8292. \end{lstlisting}
  8293. \end{minipage}
  8294. &
  8295. $\Rightarrow$
  8296. &
  8297. \begin{minipage}{0.55\textwidth}
  8298. \begin{lstlisting}
  8299. start:
  8300. x = input_int()
  8301. y = input_int()
  8302. if x < 1:
  8303. goto block_8
  8304. else:
  8305. goto block_9
  8306. block_8:
  8307. if x == 0:
  8308. goto block_4
  8309. else:
  8310. goto block_5
  8311. block_9:
  8312. if x == 2:
  8313. goto block_6
  8314. else:
  8315. goto block_7
  8316. block_4:
  8317. goto block_2
  8318. block_5:
  8319. goto block_3
  8320. block_6:
  8321. goto block_2
  8322. block_7:
  8323. goto block_3
  8324. block_2:
  8325. tmp_0 = y + 2
  8326. goto block_1
  8327. block_3:
  8328. tmp_0 = y + 10
  8329. goto block_1
  8330. block_1:
  8331. print(tmp_0)
  8332. return 0
  8333. \end{lstlisting}
  8334. \end{minipage}
  8335. \end{tabular}
  8336. \fi}
  8337. \end{tcolorbox}
  8338. \caption{Translation from \LangIf{} to \LangCIf{}
  8339. via the \code{explicate\_control}.}
  8340. \label{fig:explicate-control-s1-38}
  8341. \end{figure}
  8342. {\if\edition\racketEd
  8343. %
  8344. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8345. \code{explicate\_control} for \LangVar{} using two recursive
  8346. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8347. former function translates expressions in tail position, whereas the
  8348. latter function translates expressions on the right-hand side of a
  8349. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8350. have a new kind of position to deal with: the predicate position of
  8351. the \key{if}. We need another function, \code{explicate\_pred}, that
  8352. decides how to compile an \key{if} by analyzing its condition. So,
  8353. \code{explicate\_pred} takes an \LangIf{} expression and two
  8354. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8355. and outputs a tail. In the following paragraphs we discuss specific
  8356. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8357. \code{explicate\_pred} functions.
  8358. %
  8359. \fi}
  8360. %
  8361. {\if\edition\pythonEd
  8362. %
  8363. We recommend implementing \code{explicate\_control} using the
  8364. following four auxiliary functions.
  8365. \begin{description}
  8366. \item[\code{explicate\_effect}] generates code for expressions as
  8367. statements, so their result is ignored and only their side effects
  8368. matter.
  8369. \item[\code{explicate\_assign}] generates code for expressions
  8370. on the right-hand side of an assignment.
  8371. \item[\code{explicate\_pred}] generates code for an \code{if}
  8372. expression or statement by analyzing the condition expression.
  8373. \item[\code{explicate\_stmt}] generates code for statements.
  8374. \end{description}
  8375. These four functions should build the dictionary of basic blocks. The
  8376. following auxiliary function can be used to create a new basic block
  8377. from a list of statements. It returns a \code{goto} statement that
  8378. jumps to the new basic block.
  8379. \begin{center}
  8380. \begin{minipage}{\textwidth}
  8381. \begin{lstlisting}
  8382. def create_block(stmts, basic_blocks):
  8383. label = label_name(generate_name('block'))
  8384. basic_blocks[label] = stmts
  8385. return Goto(label)
  8386. \end{lstlisting}
  8387. \end{minipage}
  8388. \end{center}
  8389. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8390. \code{explicate\_control} pass.
  8391. The \code{explicate\_effect} function has three parameters: 1) the
  8392. expression to be compiled, 2) the already-compiled code for this
  8393. expression's \emph{continuation}, that is, the list of statements that
  8394. should execute after this expression, and 3) the dictionary of
  8395. generated basic blocks. The \code{explicate\_effect} function returns
  8396. a list of \LangCIf{} statements and it may add to the dictionary of
  8397. basic blocks.
  8398. %
  8399. Let's consider a few of the cases for the expression to be compiled.
  8400. If the expression to be compiled is a constant, then it can be
  8401. discarded because it has no side effects. If it's a \CREAD{}, then it
  8402. has a side-effect and should be preserved. So the expression should be
  8403. translated into a statement using the \code{Expr} AST class. If the
  8404. expression to be compiled is an \code{if} expression, we translate the
  8405. two branches using \code{explicate\_effect} and then translate the
  8406. condition expression using \code{explicate\_pred}, which generates
  8407. code for the entire \code{if}.
  8408. The \code{explicate\_assign} function has four parameters: 1) the
  8409. right-hand side of the assignment, 2) the left-hand side of the
  8410. assignment (the variable), 3) the continuation, and 4) the dictionary
  8411. of basic blocks. The \code{explicate\_assign} function returns a list
  8412. of \LangCIf{} statements and it may add to the dictionary of basic
  8413. blocks.
  8414. When the right-hand side is an \code{if} expression, there is some
  8415. work to do. In particular, the two branches should be translated using
  8416. \code{explicate\_assign} and the condition expression should be
  8417. translated using \code{explicate\_pred}. Otherwise we can simply
  8418. generate an assignment statement, with the given left and right-hand
  8419. sides, concatenated with its continuation.
  8420. \begin{figure}[tbp]
  8421. \begin{tcolorbox}[colback=white]
  8422. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8423. def explicate_effect(e, cont, basic_blocks):
  8424. match e:
  8425. case IfExp(test, body, orelse):
  8426. ...
  8427. case Call(func, args):
  8428. ...
  8429. case Begin(body, result):
  8430. ...
  8431. case _:
  8432. ...
  8433. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8434. match rhs:
  8435. case IfExp(test, body, orelse):
  8436. ...
  8437. case Begin(body, result):
  8438. ...
  8439. case _:
  8440. return [Assign([lhs], rhs)] + cont
  8441. def explicate_pred(cnd, thn, els, basic_blocks):
  8442. match cnd:
  8443. case Compare(left, [op], [right]):
  8444. goto_thn = create_block(thn, basic_blocks)
  8445. goto_els = create_block(els, basic_blocks)
  8446. return [If(cnd, [goto_thn], [goto_els])]
  8447. case Constant(True):
  8448. return thn;
  8449. case Constant(False):
  8450. return els;
  8451. case UnaryOp(Not(), operand):
  8452. ...
  8453. case IfExp(test, body, orelse):
  8454. ...
  8455. case Begin(body, result):
  8456. ...
  8457. case _:
  8458. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8459. [create_block(els, basic_blocks)],
  8460. [create_block(thn, basic_blocks)])]
  8461. def explicate_stmt(s, cont, basic_blocks):
  8462. match s:
  8463. case Assign([lhs], rhs):
  8464. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8465. case Expr(value):
  8466. return explicate_effect(value, cont, basic_blocks)
  8467. case If(test, body, orelse):
  8468. ...
  8469. def explicate_control(p):
  8470. match p:
  8471. case Module(body):
  8472. new_body = [Return(Constant(0))]
  8473. basic_blocks = {}
  8474. for s in reversed(body):
  8475. new_body = explicate_stmt(s, new_body, basic_blocks)
  8476. basic_blocks[label_name('start')] = new_body
  8477. return CProgram(basic_blocks)
  8478. \end{lstlisting}
  8479. \end{tcolorbox}
  8480. \caption{Skeleton for the \code{explicate\_control} pass.}
  8481. \label{fig:explicate-control-Lif}
  8482. \end{figure}
  8483. \fi}
  8484. {\if\edition\racketEd
  8485. \subsection{Explicate Tail and Assign}
  8486. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8487. additional cases for Boolean constants and \key{if}. The cases for
  8488. \code{if} should recursively compile the two branches using either
  8489. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8490. cases should then invoke \code{explicate\_pred} on the condition
  8491. expression, passing in the generated code for the two branches. For
  8492. example, consider the following program with an \code{if} in tail
  8493. position.
  8494. % cond_test_6.rkt
  8495. \begin{lstlisting}
  8496. (let ([x (read)])
  8497. (if (eq? x 0) 42 777))
  8498. \end{lstlisting}
  8499. The two branches are recursively compiled to return statements. We
  8500. then delegate to \code{explicate\_pred}, passing the condition
  8501. \code{(eq? x 0)} and the two return statements. We return to this
  8502. example shortly when we discuss \code{explicate\_pred}.
  8503. Next let us consider a program with an \code{if} on the right-hand
  8504. side of a \code{let}.
  8505. \begin{lstlisting}
  8506. (let ([y (read)])
  8507. (let ([x (if (eq? y 0) 40 777)])
  8508. (+ x 2)))
  8509. \end{lstlisting}
  8510. Note that the body of the inner \code{let} will have already been
  8511. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8512. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8513. to recursively process both branches of the \code{if}, and we do not
  8514. want to duplicate code, so we generate the following block using an
  8515. auxiliary function named \code{create\_block}, discussed in the next
  8516. section.
  8517. \begin{lstlisting}
  8518. block_6:
  8519. return (+ x 2)
  8520. \end{lstlisting}
  8521. We then use \code{goto block\_6;} as the \code{cont} argument for
  8522. compiling the branches. So the two branches compile to
  8523. \begin{center}
  8524. \begin{minipage}{0.2\textwidth}
  8525. \begin{lstlisting}
  8526. x = 40;
  8527. goto block_6;
  8528. \end{lstlisting}
  8529. \end{minipage}
  8530. \hspace{0.5in} and \hspace{0.5in}
  8531. \begin{minipage}{0.2\textwidth}
  8532. \begin{lstlisting}
  8533. x = 777;
  8534. goto block_6;
  8535. \end{lstlisting}
  8536. \end{minipage}
  8537. \end{center}
  8538. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8539. \code{(eq? y 0)} and the previously presented code for the branches.
  8540. \subsection{Create Block}
  8541. We recommend implementing the \code{create\_block} auxiliary function
  8542. as follows, using a global variable \code{basic-blocks} to store a
  8543. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8544. that \code{create\_block} generates a new label and then associates
  8545. the given \code{tail} with the new label in the \code{basic-blocks}
  8546. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8547. new label. However, if the given \code{tail} is already a \code{Goto},
  8548. then there is no need to generate a new label and entry in
  8549. \code{basic-blocks}; we can simply return that \code{Goto}.
  8550. %
  8551. \begin{lstlisting}
  8552. (define (create_block tail)
  8553. (match tail
  8554. [(Goto label) (Goto label)]
  8555. [else
  8556. (let ([label (gensym 'block)])
  8557. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8558. (Goto label))]))
  8559. \end{lstlisting}
  8560. \fi}
  8561. {\if\edition\racketEd
  8562. \subsection{Explicate Predicate}
  8563. \begin{figure}[tbp]
  8564. \begin{tcolorbox}[colback=white]
  8565. \begin{lstlisting}
  8566. (define (explicate_pred cnd thn els)
  8567. (match cnd
  8568. [(Var x) ___]
  8569. [(Let x rhs body) ___]
  8570. [(Prim 'not (list e)) ___]
  8571. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8572. (IfStmt (Prim op es) (create_block thn)
  8573. (create_block els))]
  8574. [(Bool b) (if b thn els)]
  8575. [(If cnd^ thn^ els^) ___]
  8576. [else (error "explicate_pred unhandled case" cnd)]))
  8577. \end{lstlisting}
  8578. \end{tcolorbox}
  8579. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8580. \label{fig:explicate-pred}
  8581. \end{figure}
  8582. \fi}
  8583. \racket{The skeleton for the \code{explicate\_pred} function is given
  8584. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  8585. (1) \code{cnd}, the condition expression of the \code{if};
  8586. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  8587. and (3) \code{els}, the code generated by
  8588. explicate for the \emph{else} branch. The \code{explicate\_pred}
  8589. function should match on \code{cnd} with a case for
  8590. every kind of expression that can have type \BOOLTY{}.}
  8591. %
  8592. \python{The \code{explicate\_pred} function has four parameters: 1)
  8593. the condition expression, 2) the generated statements for the
  8594. ``then'' branch, 3) the generated statements for the ``else''
  8595. branch, and 4) the dictionary of basic blocks. The
  8596. \code{explicate\_pred} function returns a list of \LangCIf{}
  8597. statements and it may add to the dictionary of basic blocks.}
  8598. Consider the case for comparison operators. We translate the
  8599. comparison to an \code{if} statement whose branches are \code{goto}
  8600. statements created by applying \code{create\_block} to the code
  8601. generated for the \code{thn} and \code{els} branches. Let us
  8602. illustrate this translation by returning to the program with an
  8603. \code{if} expression in tail position, shown next. We invoke
  8604. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  8605. \python{\code{x == 0}}.
  8606. %
  8607. {\if\edition\racketEd
  8608. \begin{lstlisting}
  8609. (let ([x (read)])
  8610. (if (eq? x 0) 42 777))
  8611. \end{lstlisting}
  8612. \fi}
  8613. %
  8614. {\if\edition\pythonEd
  8615. \begin{lstlisting}
  8616. x = input_int()
  8617. 42 if x == 0 else 777
  8618. \end{lstlisting}
  8619. \fi}
  8620. %
  8621. \noindent The two branches \code{42} and \code{777} were already
  8622. compiled to \code{return} statements, from which we now create the
  8623. following blocks:
  8624. %
  8625. \begin{center}
  8626. \begin{minipage}{\textwidth}
  8627. \begin{lstlisting}
  8628. block_1:
  8629. return 42;
  8630. block_2:
  8631. return 777;
  8632. \end{lstlisting}
  8633. \end{minipage}
  8634. \end{center}
  8635. %
  8636. After that, \code{explicate\_pred} compiles the comparison
  8637. \racket{\code{(eq? x 0)}}
  8638. \python{\code{x == 0}}
  8639. to the following \code{if} statement:
  8640. %
  8641. {\if\edition\racketEd
  8642. \begin{center}
  8643. \begin{minipage}{\textwidth}
  8644. \begin{lstlisting}
  8645. if (eq? x 0)
  8646. goto block_1;
  8647. else
  8648. goto block_2;
  8649. \end{lstlisting}
  8650. \end{minipage}
  8651. \end{center}
  8652. \fi}
  8653. {\if\edition\pythonEd
  8654. \begin{center}
  8655. \begin{minipage}{\textwidth}
  8656. \begin{lstlisting}
  8657. if x == 0:
  8658. goto block_1;
  8659. else
  8660. goto block_2;
  8661. \end{lstlisting}
  8662. \end{minipage}
  8663. \end{center}
  8664. \fi}
  8665. Next consider the case for Boolean constants. We perform a kind of
  8666. partial evaluation\index{subject}{partial evaluation} and output
  8667. either the \code{thn} or \code{els} branch, depending on whether the
  8668. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8669. following program:
  8670. {\if\edition\racketEd
  8671. \begin{lstlisting}
  8672. (if #t 42 777)
  8673. \end{lstlisting}
  8674. \fi}
  8675. {\if\edition\pythonEd
  8676. \begin{lstlisting}
  8677. 42 if True else 777
  8678. \end{lstlisting}
  8679. \fi}
  8680. %
  8681. \noindent Again, the two branches \code{42} and \code{777} were
  8682. compiled to \code{return} statements, so \code{explicate\_pred}
  8683. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8684. code for the \emph{then} branch.
  8685. \begin{lstlisting}
  8686. return 42;
  8687. \end{lstlisting}
  8688. This case demonstrates that we sometimes discard the \code{thn} or
  8689. \code{els} blocks that are input to \code{explicate\_pred}.
  8690. The case for \key{if} expressions in \code{explicate\_pred} is
  8691. particularly illuminating because it deals with the challenges
  8692. discussed previously regarding nested \key{if} expressions
  8693. (figure~\ref{fig:explicate-control-s1-38}). The
  8694. \racket{\lstinline{thn^}}\python{\code{body}} and
  8695. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8696. \key{if} inherit their context from the current one, that is,
  8697. predicate context. So, you should recursively apply
  8698. \code{explicate\_pred} to the
  8699. \racket{\lstinline{thn^}}\python{\code{body}} and
  8700. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8701. those recursive calls, pass \code{thn} and \code{els} as the extra
  8702. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8703. inside each recursive call. As discussed previously, to avoid
  8704. duplicating code, we need to add them to the dictionary of basic
  8705. blocks so that we can instead refer to them by name and execute them
  8706. with a \key{goto}.
  8707. {\if\edition\pythonEd
  8708. %
  8709. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8710. three parameters: 1) the statement to be compiled, 2) the code for its
  8711. continuation, and 3) the dictionary of basic blocks. The
  8712. \code{explicate\_stmt} returns a list of statements and it may add to
  8713. the dictionary of basic blocks. The cases for assignment and an
  8714. expression-statement are given in full in the skeleton code: they
  8715. simply dispatch to \code{explicate\_assign} and
  8716. \code{explicate\_effect}, respectively. The case for \code{if}
  8717. statements is not given, and is similar to the case for \code{if}
  8718. expressions.
  8719. The \code{explicate\_control} function itself is given in
  8720. figure~\ref{fig:explicate-control-Lif}. It applies
  8721. \code{explicate\_stmt} to each statement in the program, from back to
  8722. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8723. used as the continuation parameter in the next call to
  8724. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8725. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8726. the dictionary of basic blocks, labeling it as the ``start'' block.
  8727. %
  8728. \fi}
  8729. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8730. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8731. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8732. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8733. %% results from the two recursive calls. We complete the case for
  8734. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8735. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8736. %% the result $B_5$.
  8737. %% \[
  8738. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8739. %% \quad\Rightarrow\quad
  8740. %% B_5
  8741. %% \]
  8742. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8743. %% inherit the current context, so they are in tail position. Thus, the
  8744. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8745. %% \code{explicate\_tail}.
  8746. %% %
  8747. %% We need to pass $B_0$ as the accumulator argument for both of these
  8748. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8749. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8750. %% to the control-flow graph and obtain a promised goto $G_0$.
  8751. %% %
  8752. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8753. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8754. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8755. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8756. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8757. %% \[
  8758. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8759. %% \]
  8760. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8761. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8762. %% should not be confused with the labels for the blocks that appear in
  8763. %% the generated code. We initially construct unlabeled blocks; we only
  8764. %% attach labels to blocks when we add them to the control-flow graph, as
  8765. %% we see in the next case.
  8766. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8767. %% function. The context of the \key{if} is an assignment to some
  8768. %% variable $x$ and then the control continues to some promised block
  8769. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8770. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8771. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8772. %% branches of the \key{if} inherit the current context, so they are in
  8773. %% assignment positions. Let $B_2$ be the result of applying
  8774. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8775. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8776. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8777. %% the result of applying \code{explicate\_pred} to the predicate
  8778. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8779. %% translates to the promise $B_4$.
  8780. %% \[
  8781. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8782. %% \]
  8783. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8784. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8785. \code{remove\_complex\_operands} pass and then the
  8786. \code{explicate\_control} pass on the example program. We walk through
  8787. the output program.
  8788. %
  8789. Following the order of evaluation in the output of
  8790. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8791. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8792. in the predicate of the inner \key{if}. In the output of
  8793. \code{explicate\_control}, in the
  8794. block labeled \code{start}, two assignment statements are followed by an
  8795. \code{if} statement that branches to \code{block\_4} or
  8796. \code{block\_5}. The blocks associated with those labels contain the
  8797. translations of the code
  8798. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8799. and
  8800. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8801. respectively. In particular, we start \code{block\_4} with the
  8802. comparison
  8803. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8804. and then branch to \code{block\_2} or \code{block\_3},
  8805. which correspond to the two branches of the outer \key{if}, that is,
  8806. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8807. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8808. %
  8809. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8810. %
  8811. \python{The \code{block\_1} corresponds to the \code{print} statement
  8812. at the end of the program.}
  8813. {\if\edition\racketEd
  8814. \subsection{Interactions between Explicate and Shrink}
  8815. The way in which the \code{shrink} pass transforms logical operations
  8816. such as \code{and} and \code{or} can impact the quality of code
  8817. generated by \code{explicate\_control}. For example, consider the
  8818. following program:
  8819. % cond_test_21.rkt, and_eq_input.py
  8820. \begin{lstlisting}
  8821. (if (and (eq? (read) 0) (eq? (read) 1))
  8822. 0
  8823. 42)
  8824. \end{lstlisting}
  8825. The \code{and} operation should transform into something that the
  8826. \code{explicate\_pred} function can analyze and descend through to
  8827. reach the underlying \code{eq?} conditions. Ideally, for this program
  8828. your \code{explicate\_control} pass should generate code similar to
  8829. the following:
  8830. \begin{center}
  8831. \begin{minipage}{\textwidth}
  8832. \begin{lstlisting}
  8833. start:
  8834. tmp1 = (read);
  8835. if (eq? tmp1 0) goto block40;
  8836. else goto block39;
  8837. block40:
  8838. tmp2 = (read);
  8839. if (eq? tmp2 1) goto block38;
  8840. else goto block39;
  8841. block38:
  8842. return 0;
  8843. block39:
  8844. return 42;
  8845. \end{lstlisting}
  8846. \end{minipage}
  8847. \end{center}
  8848. \fi}
  8849. \begin{exercise}\normalfont\normalsize
  8850. \racket{
  8851. Implement the pass \code{explicate\_control} by adding the cases for
  8852. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8853. \code{explicate\_assign} functions. Implement the auxiliary function
  8854. \code{explicate\_pred} for predicate contexts.}
  8855. \python{Implement \code{explicate\_control} pass with its
  8856. four auxiliary functions.}
  8857. %
  8858. Create test cases that exercise all the new cases in the code for
  8859. this pass.
  8860. %
  8861. {\if\edition\racketEd
  8862. Add the following entry to the list of \code{passes} in
  8863. \code{run-tests.rkt}:
  8864. \begin{lstlisting}
  8865. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8866. \end{lstlisting}
  8867. and then run \code{run-tests.rkt} to test your compiler.
  8868. \fi}
  8869. \end{exercise}
  8870. \section{Select Instructions}
  8871. \label{sec:select-Lif}
  8872. \index{subject}{instruction selection}
  8873. The \code{select\_instructions} pass translates \LangCIf{} to
  8874. \LangXIfVar{}.
  8875. %
  8876. \racket{Recall that we implement this pass using three auxiliary
  8877. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8878. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8879. %
  8880. \racket{For $\Atm$, we have new cases for the Booleans.}
  8881. %
  8882. \python{We begin with the Boolean constants.}
  8883. We take the usual approach of encoding them as integers.
  8884. \[
  8885. \TRUE{} \quad\Rightarrow\quad \key{1}
  8886. \qquad\qquad
  8887. \FALSE{} \quad\Rightarrow\quad \key{0}
  8888. \]
  8889. For translating statements, we discuss some of the cases. The
  8890. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8891. discussed at the beginning of this section. Given an assignment, if
  8892. the left-hand-side variable is the same as the argument of \code{not},
  8893. then just the \code{xorq} instruction suffices.
  8894. \[
  8895. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8896. \quad\Rightarrow\quad
  8897. \key{xorq}~\key{\$}1\key{,}~\Var
  8898. \]
  8899. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8900. semantics of x86. In the following translation, let $\Arg$ be the
  8901. result of translating $\Atm$ to x86.
  8902. \[
  8903. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8904. \quad\Rightarrow\quad
  8905. \begin{array}{l}
  8906. \key{movq}~\Arg\key{,}~\Var\\
  8907. \key{xorq}~\key{\$}1\key{,}~\Var
  8908. \end{array}
  8909. \]
  8910. Next consider the cases for equality comparisons. Translating this
  8911. operation to x86 is slightly involved due to the unusual nature of the
  8912. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8913. We recommend translating an assignment with an equality on the
  8914. right-hand side into a sequence of three instructions. \\
  8915. \begin{tabular}{lll}
  8916. \begin{minipage}{0.4\textwidth}
  8917. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8918. \end{minipage}
  8919. &
  8920. $\Rightarrow$
  8921. &
  8922. \begin{minipage}{0.4\textwidth}
  8923. \begin{lstlisting}
  8924. cmpq |$\Arg_2$|, |$\Arg_1$|
  8925. sete %al
  8926. movzbq %al, |$\Var$|
  8927. \end{lstlisting}
  8928. \end{minipage}
  8929. \end{tabular} \\
  8930. The translations for the other comparison operators are similar to
  8931. this but use different condition codes for the \code{set} instruction.
  8932. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8933. \key{goto} and \key{if} statements. Both are straightforward to
  8934. translate to x86.}
  8935. %
  8936. A \key{goto} statement becomes a jump instruction.
  8937. \[
  8938. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8939. \]
  8940. %
  8941. An \key{if} statement becomes a compare instruction followed by a
  8942. conditional jump (for the \emph{then} branch), and the fall-through is to
  8943. a regular jump (for the \emph{else} branch).\\
  8944. \begin{tabular}{lll}
  8945. \begin{minipage}{0.4\textwidth}
  8946. \begin{lstlisting}
  8947. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8948. goto |$\ell_1$||$\racket{\key{;}}$|
  8949. else|$\python{\key{:}}$|
  8950. goto |$\ell_2$||$\racket{\key{;}}$|
  8951. \end{lstlisting}
  8952. \end{minipage}
  8953. &
  8954. $\Rightarrow$
  8955. &
  8956. \begin{minipage}{0.4\textwidth}
  8957. \begin{lstlisting}
  8958. cmpq |$\Arg_2$|, |$\Arg_1$|
  8959. je |$\ell_1$|
  8960. jmp |$\ell_2$|
  8961. \end{lstlisting}
  8962. \end{minipage}
  8963. \end{tabular} \\
  8964. Again, the translations for the other comparison operators are similar to this
  8965. but use different condition codes for the conditional jump instruction.
  8966. \python{Regarding the \key{return} statement, we recommend treating it
  8967. as an assignment to the \key{rax} register followed by a jump to the
  8968. conclusion of the \code{main} function.}
  8969. \begin{exercise}\normalfont\normalsize
  8970. Expand your \code{select\_instructions} pass to handle the new
  8971. features of the \LangCIf{} language.
  8972. %
  8973. {\if\edition\racketEd
  8974. Add the following entry to the list of \code{passes} in
  8975. \code{run-tests.rkt}
  8976. \begin{lstlisting}
  8977. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8978. \end{lstlisting}
  8979. \fi}
  8980. %
  8981. Run the script to test your compiler on all the test programs.
  8982. \end{exercise}
  8983. \section{Register Allocation}
  8984. \label{sec:register-allocation-Lif}
  8985. \index{subject}{register allocation}
  8986. The changes required for compiling \LangIf{} affect liveness analysis,
  8987. building the interference graph, and assigning homes, but the graph
  8988. coloring algorithm itself does not change.
  8989. \subsection{Liveness Analysis}
  8990. \label{sec:liveness-analysis-Lif}
  8991. \index{subject}{liveness analysis}
  8992. Recall that for \LangVar{} we implemented liveness analysis for a
  8993. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8994. the addition of \key{if} expressions to \LangIf{},
  8995. \code{explicate\_control} produces many basic blocks.
  8996. %% We recommend that you create a new auxiliary function named
  8997. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8998. %% control-flow graph.
  8999. The first question is, in what order should we process the basic blocks?
  9000. Recall that to perform liveness analysis on a basic block we need to
  9001. know the live-after set for the last instruction in the block. If a
  9002. basic block has no successors (i.e., contains no jumps to other
  9003. blocks), then it has an empty live-after set and we can immediately
  9004. apply liveness analysis to it. If a basic block has some successors,
  9005. then we need to complete liveness analysis on those blocks
  9006. first. These ordering constraints are the reverse of a
  9007. \emph{topological order}\index{subject}{topological order} on a graph
  9008. representation of the program. In particular, the \emph{control flow
  9009. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9010. of a program has a node for each basic block and an edge for each jump
  9011. from one block to another. It is straightforward to generate a CFG
  9012. from the dictionary of basic blocks. One then transposes the CFG and
  9013. applies the topological sort algorithm.
  9014. %
  9015. %
  9016. \racket{We recommend using the \code{tsort} and \code{transpose}
  9017. functions of the Racket \code{graph} package to accomplish this.}
  9018. %
  9019. \python{We provide implementations of \code{topological\_sort} and
  9020. \code{transpose} in the file \code{graph.py} of the support code.}
  9021. %
  9022. As an aside, a topological ordering is only guaranteed to exist if the
  9023. graph does not contain any cycles. This is the case for the
  9024. control-flow graphs that we generate from \LangIf{} programs.
  9025. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9026. and learn how to handle cycles in the control-flow graph.
  9027. \racket{You need to construct a directed graph to represent the
  9028. control-flow graph. Do not use the \code{directed-graph} of the
  9029. \code{graph} package because that allows at most one edge
  9030. between each pair of vertices, whereas a control-flow graph may have
  9031. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9032. file in the support code implements a graph representation that
  9033. allows multiple edges between a pair of vertices.}
  9034. {\if\edition\racketEd
  9035. The next question is how to analyze jump instructions. Recall that in
  9036. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9037. \code{label->live} that maps each label to the set of live locations
  9038. at the beginning of its block. We use \code{label->live} to determine
  9039. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9040. that we have many basic blocks, \code{label->live} needs to be updated
  9041. as we process the blocks. In particular, after performing liveness
  9042. analysis on a block, we take the live-before set of its first
  9043. instruction and associate that with the block's label in the
  9044. \code{label->live} alist.
  9045. \fi}
  9046. %
  9047. {\if\edition\pythonEd
  9048. %
  9049. The next question is how to analyze jump instructions. The locations
  9050. that are live before a \code{jmp} should be the locations in
  9051. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9052. maintaining a dictionary named \code{live\_before\_block} that maps each
  9053. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9054. block. After performing liveness analysis on each block, we take the
  9055. live-before set of its first instruction and associate that with the
  9056. block's label in the \code{live\_before\_block} dictionary.
  9057. %
  9058. \fi}
  9059. In \LangXIfVar{} we also have the conditional jump
  9060. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9061. this instruction is particularly interesting because during
  9062. compilation, we do not know which way a conditional jump will go. Thus
  9063. we do not know whether to use the live-before set for the block
  9064. associated with the $\itm{label}$ or the live-before set for the
  9065. following instruction. However, there is no harm to the correctness
  9066. of the generated code if we classify more locations as live than the
  9067. ones that are truly live during one particular execution of the
  9068. instruction. Thus, we can take the union of the live-before sets from
  9069. the following instruction and from the mapping for $\itm{label}$ in
  9070. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9071. The auxiliary functions for computing the variables in an
  9072. instruction's argument and for computing the variables read-from ($R$)
  9073. or written-to ($W$) by an instruction need to be updated to handle the
  9074. new kinds of arguments and instructions in \LangXIfVar{}.
  9075. \begin{exercise}\normalfont\normalsize
  9076. {\if\edition\racketEd
  9077. %
  9078. Update the \code{uncover\_live} pass to apply liveness analysis to
  9079. every basic block in the program.
  9080. %
  9081. Add the following entry to the list of \code{passes} in the
  9082. \code{run-tests.rkt} script:
  9083. \begin{lstlisting}
  9084. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9085. \end{lstlisting}
  9086. \fi}
  9087. {\if\edition\pythonEd
  9088. %
  9089. Update the \code{uncover\_live} function to perform liveness analysis,
  9090. in reverse topological order, on all the basic blocks in the
  9091. program.
  9092. %
  9093. \fi}
  9094. % Check that the live-after sets that you generate for
  9095. % example X matches the following... -Jeremy
  9096. \end{exercise}
  9097. \subsection{Build the Interference Graph}
  9098. \label{sec:build-interference-Lif}
  9099. Many of the new instructions in \LangXIfVar{} can be handled in the
  9100. same way as the instructions in \LangXVar{}.
  9101. % Thus, if your code was
  9102. % already quite general, it will not need to be changed to handle the
  9103. % new instructions. If your code is not general enough, we recommend that
  9104. % you change your code to be more general. For example, you can factor
  9105. % out the computing of the the read and write sets for each kind of
  9106. % instruction into auxiliary functions.
  9107. %
  9108. Some instructions, such as the \key{movzbq} instruction, require special care,
  9109. similar to the \key{movq} instruction. Refer to rule number 1 in
  9110. section~\ref{sec:build-interference}.
  9111. \begin{exercise}\normalfont\normalsize
  9112. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9113. {\if\edition\racketEd
  9114. Add the following entries to the list of \code{passes} in the
  9115. \code{run-tests.rkt} script:
  9116. \begin{lstlisting}
  9117. (list "build_interference" build_interference interp-pseudo-x86-1)
  9118. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9119. \end{lstlisting}
  9120. \fi}
  9121. % Check that the interference graph that you generate for
  9122. % example X matches the following graph G... -Jeremy
  9123. \end{exercise}
  9124. \section{Patch Instructions}
  9125. The new instructions \key{cmpq} and \key{movzbq} have some special
  9126. restrictions that need to be handled in the \code{patch\_instructions}
  9127. pass.
  9128. %
  9129. The second argument of the \key{cmpq} instruction must not be an
  9130. immediate value (such as an integer). So, if you are comparing two
  9131. immediates, we recommend inserting a \key{movq} instruction to put the
  9132. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9133. one memory reference.
  9134. %
  9135. The second argument of the \key{movzbq} must be a register.
  9136. \begin{exercise}\normalfont\normalsize
  9137. %
  9138. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9139. %
  9140. {\if\edition\racketEd
  9141. Add the following entry to the list of \code{passes} in
  9142. \code{run-tests.rkt}, and then run this script to test your compiler.
  9143. \begin{lstlisting}
  9144. (list "patch_instructions" patch_instructions interp-x86-1)
  9145. \end{lstlisting}
  9146. \fi}
  9147. \end{exercise}
  9148. {\if\edition\pythonEd
  9149. \section{Prelude and Conclusion}
  9150. \label{sec:prelude-conclusion-cond}
  9151. The generation of the \code{main} function with its prelude and
  9152. conclusion must change to accommodate how the program now consists of
  9153. one or more basic blocks. After the prelude in \code{main}, jump to
  9154. the \code{start} block. Place the conclusion in a basic block labeled
  9155. with \code{conclusion}.
  9156. \fi}
  9157. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9158. \LangIf{} translated to x86, showing the results of
  9159. \code{explicate\_control}, \code{select\_instructions}, and the final
  9160. x86 assembly.
  9161. \begin{figure}[tbp]
  9162. \begin{tcolorbox}[colback=white]
  9163. {\if\edition\racketEd
  9164. \begin{tabular}{lll}
  9165. \begin{minipage}{0.4\textwidth}
  9166. % cond_test_20.rkt, eq_input.py
  9167. \begin{lstlisting}
  9168. (if (eq? (read) 1) 42 0)
  9169. \end{lstlisting}
  9170. $\Downarrow$
  9171. \begin{lstlisting}
  9172. start:
  9173. tmp7951 = (read);
  9174. if (eq? tmp7951 1)
  9175. goto block7952;
  9176. else
  9177. goto block7953;
  9178. block7952:
  9179. return 42;
  9180. block7953:
  9181. return 0;
  9182. \end{lstlisting}
  9183. $\Downarrow$
  9184. \begin{lstlisting}
  9185. start:
  9186. callq read_int
  9187. movq %rax, tmp7951
  9188. cmpq $1, tmp7951
  9189. je block7952
  9190. jmp block7953
  9191. block7953:
  9192. movq $0, %rax
  9193. jmp conclusion
  9194. block7952:
  9195. movq $42, %rax
  9196. jmp conclusion
  9197. \end{lstlisting}
  9198. \end{minipage}
  9199. &
  9200. $\Rightarrow\qquad$
  9201. \begin{minipage}{0.4\textwidth}
  9202. \begin{lstlisting}
  9203. start:
  9204. callq read_int
  9205. movq %rax, %rcx
  9206. cmpq $1, %rcx
  9207. je block7952
  9208. jmp block7953
  9209. block7953:
  9210. movq $0, %rax
  9211. jmp conclusion
  9212. block7952:
  9213. movq $42, %rax
  9214. jmp conclusion
  9215. .globl main
  9216. main:
  9217. pushq %rbp
  9218. movq %rsp, %rbp
  9219. pushq %r13
  9220. pushq %r12
  9221. pushq %rbx
  9222. pushq %r14
  9223. subq $0, %rsp
  9224. jmp start
  9225. conclusion:
  9226. addq $0, %rsp
  9227. popq %r14
  9228. popq %rbx
  9229. popq %r12
  9230. popq %r13
  9231. popq %rbp
  9232. retq
  9233. \end{lstlisting}
  9234. \end{minipage}
  9235. \end{tabular}
  9236. \fi}
  9237. {\if\edition\pythonEd
  9238. \begin{tabular}{lll}
  9239. \begin{minipage}{0.4\textwidth}
  9240. % cond_test_20.rkt, eq_input.py
  9241. \begin{lstlisting}
  9242. print(42 if input_int() == 1 else 0)
  9243. \end{lstlisting}
  9244. $\Downarrow$
  9245. \begin{lstlisting}
  9246. start:
  9247. tmp_0 = input_int()
  9248. if tmp_0 == 1:
  9249. goto block_3
  9250. else:
  9251. goto block_4
  9252. block_3:
  9253. tmp_1 = 42
  9254. goto block_2
  9255. block_4:
  9256. tmp_1 = 0
  9257. goto block_2
  9258. block_2:
  9259. print(tmp_1)
  9260. return 0
  9261. \end{lstlisting}
  9262. $\Downarrow$
  9263. \begin{lstlisting}
  9264. start:
  9265. callq read_int
  9266. movq %rax, tmp_0
  9267. cmpq 1, tmp_0
  9268. je block_3
  9269. jmp block_4
  9270. block_3:
  9271. movq 42, tmp_1
  9272. jmp block_2
  9273. block_4:
  9274. movq 0, tmp_1
  9275. jmp block_2
  9276. block_2:
  9277. movq tmp_1, %rdi
  9278. callq print_int
  9279. movq 0, %rax
  9280. jmp conclusion
  9281. \end{lstlisting}
  9282. \end{minipage}
  9283. &
  9284. $\Rightarrow\qquad$
  9285. \begin{minipage}{0.4\textwidth}
  9286. \begin{lstlisting}
  9287. .globl main
  9288. main:
  9289. pushq %rbp
  9290. movq %rsp, %rbp
  9291. subq $0, %rsp
  9292. jmp start
  9293. start:
  9294. callq read_int
  9295. movq %rax, %rcx
  9296. cmpq $1, %rcx
  9297. je block_3
  9298. jmp block_4
  9299. block_3:
  9300. movq $42, %rcx
  9301. jmp block_2
  9302. block_4:
  9303. movq $0, %rcx
  9304. jmp block_2
  9305. block_2:
  9306. movq %rcx, %rdi
  9307. callq print_int
  9308. movq $0, %rax
  9309. jmp conclusion
  9310. conclusion:
  9311. addq $0, %rsp
  9312. popq %rbp
  9313. retq
  9314. \end{lstlisting}
  9315. \end{minipage}
  9316. \end{tabular}
  9317. \fi}
  9318. \end{tcolorbox}
  9319. \caption{Example compilation of an \key{if} expression to x86, showing
  9320. the results of \code{explicate\_control},
  9321. \code{select\_instructions}, and the final x86 assembly code. }
  9322. \label{fig:if-example-x86}
  9323. \end{figure}
  9324. \begin{figure}[tbp]
  9325. \begin{tcolorbox}[colback=white]
  9326. {\if\edition\racketEd
  9327. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9328. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9329. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9330. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9331. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9332. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9333. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9334. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9335. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9336. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9337. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9338. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9339. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9340. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9341. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9342. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  9343. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9344. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9345. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9346. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9347. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9348. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9349. \end{tikzpicture}
  9350. \fi}
  9351. {\if\edition\pythonEd
  9352. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9353. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9354. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9355. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9356. \node (C-1) at (0,0) {\large \LangCIf{}};
  9357. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9358. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9359. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9360. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9361. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9362. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9363. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  9364. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9365. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9366. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9367. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9368. \end{tikzpicture}
  9369. \fi}
  9370. \end{tcolorbox}
  9371. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9372. \label{fig:Lif-passes}
  9373. \end{figure}
  9374. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9375. compilation of \LangIf{}.
  9376. \section{Challenge: Optimize Blocks and Remove Jumps}
  9377. \label{sec:opt-jumps}
  9378. We discuss two optional challenges that involve optimizing the
  9379. control-flow of the program.
  9380. \subsection{Optimize Blocks}
  9381. The algorithm for \code{explicate\_control} that we discussed in
  9382. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9383. blocks. It creates a basic block whenever a continuation \emph{might}
  9384. get used more than once (e.g., whenever the \code{cont} parameter is
  9385. passed into two or more recursive calls). However, some continuation
  9386. arguments may not be used at all. For example, consider the case for
  9387. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9388. \code{els} continuation.
  9389. %
  9390. {\if\edition\racketEd
  9391. The following example program falls into this
  9392. case, and it creates two unused blocks.
  9393. \begin{center}
  9394. \begin{tabular}{lll}
  9395. \begin{minipage}{0.4\textwidth}
  9396. % cond_test_82.rkt
  9397. \begin{lstlisting}
  9398. (let ([y (if #t
  9399. (read)
  9400. (if (eq? (read) 0)
  9401. 777
  9402. (let ([x (read)])
  9403. (+ 1 x))))])
  9404. (+ y 2))
  9405. \end{lstlisting}
  9406. \end{minipage}
  9407. &
  9408. $\Rightarrow$
  9409. &
  9410. \begin{minipage}{0.55\textwidth}
  9411. \begin{lstlisting}
  9412. start:
  9413. y = (read);
  9414. goto block_5;
  9415. block_5:
  9416. return (+ y 2);
  9417. block_6:
  9418. y = 777;
  9419. goto block_5;
  9420. block_7:
  9421. x = (read);
  9422. y = (+ 1 x2);
  9423. goto block_5;
  9424. \end{lstlisting}
  9425. \end{minipage}
  9426. \end{tabular}
  9427. \end{center}
  9428. \fi}
  9429. The question is, how can we decide whether to create a basic block?
  9430. \emph{Lazy evaluation}\index{subject}{lazy
  9431. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9432. delaying the creation of a basic block until the point in time at which
  9433. we know that it will be used.
  9434. %
  9435. {\if\edition\racketEd
  9436. %
  9437. Racket provides support for
  9438. lazy evaluation with the
  9439. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9440. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9441. \index{subject}{delay} creates a
  9442. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9443. expressions is postponed. When \key{(force}
  9444. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9445. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9446. result of $e_n$ is cached in the promise and returned. If \code{force}
  9447. is applied again to the same promise, then the cached result is
  9448. returned. If \code{force} is applied to an argument that is not a
  9449. promise, \code{force} simply returns the argument.
  9450. %
  9451. \fi}
  9452. %
  9453. {\if\edition\pythonEd
  9454. %
  9455. While Python does not provide direct support for lazy evaluation, it
  9456. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9457. by wrapping it inside a function with no parameters. We can
  9458. \emph{force} its evaluation by calling the function. However, in some
  9459. cases of \code{explicate\_pred}, etc., we will return a list of
  9460. statements and in other cases we will return a function that computes
  9461. a list of statements. We use the term \emph{promise} to refer to a
  9462. value that may be delayed. To uniformly deal with
  9463. promises, we define the following \code{force} function that checks
  9464. whether its input is delayed (i.e., whether it is a function) and then
  9465. either 1) calls the function, or 2) returns the input.
  9466. \begin{lstlisting}
  9467. def force(promise):
  9468. if isinstance(promise, types.FunctionType):
  9469. return promise()
  9470. else:
  9471. return promise
  9472. \end{lstlisting}
  9473. %
  9474. \fi}
  9475. We use promises for the input and output of the functions
  9476. \code{explicate\_pred}, \code{explicate\_assign},
  9477. %
  9478. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9479. %
  9480. So, instead of taking and returning \racket{$\Tail$
  9481. expressions}\python{lists of statements}, they take and return
  9482. promises. Furthermore, when we come to a situation in which a
  9483. continuation might be used more than once, as in the case for
  9484. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9485. that creates a basic block for each continuation (if there is not
  9486. already one) and then returns a \code{goto} statement to that basic
  9487. block. When we come to a situation in which we have a promise but need an
  9488. actual piece of code, for example, to create a larger piece of code with a
  9489. constructor such as \code{Seq}, then insert a call to \code{force}.
  9490. %
  9491. {\if\edition\racketEd
  9492. %
  9493. Also, we must modify the \code{create\_block} function to begin with
  9494. \code{delay} to create a promise. When forced, this promise forces the
  9495. original promise. If that returns a \code{Goto} (because the block was
  9496. already added to \code{basic-blocks}), then we return the
  9497. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9498. return a \code{Goto} to the new label.
  9499. \begin{center}
  9500. \begin{minipage}{\textwidth}
  9501. \begin{lstlisting}
  9502. (define (create_block tail)
  9503. (delay
  9504. (define t (force tail))
  9505. (match t
  9506. [(Goto label) (Goto label)]
  9507. [else
  9508. (let ([label (gensym 'block)])
  9509. (set! basic-blocks (cons (cons label t) basic-blocks))
  9510. (Goto label))])))
  9511. \end{lstlisting}
  9512. \end{minipage}
  9513. \end{center}
  9514. \fi}
  9515. {\if\edition\pythonEd
  9516. %
  9517. Here is the new version of the \code{create\_block} auxiliary function
  9518. that works on promises and that checks whether the block consists of a
  9519. solitary \code{goto} statement.\\
  9520. \begin{minipage}{\textwidth}
  9521. \begin{lstlisting}
  9522. def create_block(promise, basic_blocks):
  9523. stmts = force(promise)
  9524. match stmts:
  9525. case [Goto(l)]:
  9526. return Goto(l)
  9527. case _:
  9528. label = label_name(generate_name('block'))
  9529. basic_blocks[label] = stmts
  9530. return Goto(label)
  9531. \end{lstlisting}
  9532. \end{minipage}
  9533. \fi}
  9534. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9535. improved \code{explicate\_control} on this example. As you can
  9536. see, the number of basic blocks has been reduced from four blocks (see
  9537. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9538. \begin{figure}[tbp]
  9539. \begin{tcolorbox}[colback=white]
  9540. {\if\edition\racketEd
  9541. \begin{tabular}{lll}
  9542. \begin{minipage}{0.4\textwidth}
  9543. % cond_test_82.rkt
  9544. \begin{lstlisting}
  9545. (let ([y (if #t
  9546. (read)
  9547. (if (eq? (read) 0)
  9548. 777
  9549. (let ([x (read)])
  9550. (+ 1 x))))])
  9551. (+ y 2))
  9552. \end{lstlisting}
  9553. \end{minipage}
  9554. &
  9555. $\Rightarrow$
  9556. &
  9557. \begin{minipage}{0.55\textwidth}
  9558. \begin{lstlisting}
  9559. start:
  9560. y = (read);
  9561. goto block_5;
  9562. block_5:
  9563. return (+ y 2);
  9564. \end{lstlisting}
  9565. \end{minipage}
  9566. \end{tabular}
  9567. \fi}
  9568. {\if\edition\pythonEd
  9569. \begin{tabular}{lll}
  9570. \begin{minipage}{0.4\textwidth}
  9571. % cond_test_41.rkt
  9572. \begin{lstlisting}
  9573. x = input_int()
  9574. y = input_int()
  9575. print(y + 2 \
  9576. if (x == 0 \
  9577. if x < 1 \
  9578. else x == 2) \
  9579. else y + 10)
  9580. \end{lstlisting}
  9581. \end{minipage}
  9582. &
  9583. $\Rightarrow$
  9584. &
  9585. \begin{minipage}{0.55\textwidth}
  9586. \begin{lstlisting}
  9587. start:
  9588. x = input_int()
  9589. y = input_int()
  9590. if x < 1:
  9591. goto block_4
  9592. else:
  9593. goto block_5
  9594. block_4:
  9595. if x == 0:
  9596. goto block_2
  9597. else:
  9598. goto block_3
  9599. block_5:
  9600. if x == 2:
  9601. goto block_2
  9602. else:
  9603. goto block_3
  9604. block_2:
  9605. tmp_0 = y + 2
  9606. goto block_1
  9607. block_3:
  9608. tmp_0 = y + 10
  9609. goto block_1
  9610. block_1:
  9611. print(tmp_0)
  9612. return 0
  9613. \end{lstlisting}
  9614. \end{minipage}
  9615. \end{tabular}
  9616. \fi}
  9617. \end{tcolorbox}
  9618. \caption{Translation from \LangIf{} to \LangCIf{}
  9619. via the improved \code{explicate\_control}.}
  9620. \label{fig:explicate-control-challenge}
  9621. \end{figure}
  9622. %% Recall that in the example output of \code{explicate\_control} in
  9623. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9624. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9625. %% block. The first goal of this challenge assignment is to remove those
  9626. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9627. %% \code{explicate\_control} on the left and shows the result of bypassing
  9628. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9629. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9630. %% \code{block55}. The optimized code on the right of
  9631. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9632. %% \code{then} branch jumping directly to \code{block55}. The story is
  9633. %% similar for the \code{else} branch, as well as for the two branches in
  9634. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9635. %% have been optimized in this way, there are no longer any jumps to
  9636. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9637. %% \begin{figure}[tbp]
  9638. %% \begin{tabular}{lll}
  9639. %% \begin{minipage}{0.4\textwidth}
  9640. %% \begin{lstlisting}
  9641. %% block62:
  9642. %% tmp54 = (read);
  9643. %% if (eq? tmp54 2) then
  9644. %% goto block59;
  9645. %% else
  9646. %% goto block60;
  9647. %% block61:
  9648. %% tmp53 = (read);
  9649. %% if (eq? tmp53 0) then
  9650. %% goto block57;
  9651. %% else
  9652. %% goto block58;
  9653. %% block60:
  9654. %% goto block56;
  9655. %% block59:
  9656. %% goto block55;
  9657. %% block58:
  9658. %% goto block56;
  9659. %% block57:
  9660. %% goto block55;
  9661. %% block56:
  9662. %% return (+ 700 77);
  9663. %% block55:
  9664. %% return (+ 10 32);
  9665. %% start:
  9666. %% tmp52 = (read);
  9667. %% if (eq? tmp52 1) then
  9668. %% goto block61;
  9669. %% else
  9670. %% goto block62;
  9671. %% \end{lstlisting}
  9672. %% \end{minipage}
  9673. %% &
  9674. %% $\Rightarrow$
  9675. %% &
  9676. %% \begin{minipage}{0.55\textwidth}
  9677. %% \begin{lstlisting}
  9678. %% block62:
  9679. %% tmp54 = (read);
  9680. %% if (eq? tmp54 2) then
  9681. %% goto block55;
  9682. %% else
  9683. %% goto block56;
  9684. %% block61:
  9685. %% tmp53 = (read);
  9686. %% if (eq? tmp53 0) then
  9687. %% goto block55;
  9688. %% else
  9689. %% goto block56;
  9690. %% block56:
  9691. %% return (+ 700 77);
  9692. %% block55:
  9693. %% return (+ 10 32);
  9694. %% start:
  9695. %% tmp52 = (read);
  9696. %% if (eq? tmp52 1) then
  9697. %% goto block61;
  9698. %% else
  9699. %% goto block62;
  9700. %% \end{lstlisting}
  9701. %% \end{minipage}
  9702. %% \end{tabular}
  9703. %% \caption{Optimize jumps by removing trivial blocks.}
  9704. %% \label{fig:optimize-jumps}
  9705. %% \end{figure}
  9706. %% The name of this pass is \code{optimize-jumps}. We recommend
  9707. %% implementing this pass in two phases. The first phrase builds a hash
  9708. %% table that maps labels to possibly improved labels. The second phase
  9709. %% changes the target of each \code{goto} to use the improved label. If
  9710. %% the label is for a trivial block, then the hash table should map the
  9711. %% label to the first non-trivial block that can be reached from this
  9712. %% label by jumping through trivial blocks. If the label is for a
  9713. %% non-trivial block, then the hash table should map the label to itself;
  9714. %% we do not want to change jumps to non-trivial blocks.
  9715. %% The first phase can be accomplished by constructing an empty hash
  9716. %% table, call it \code{short-cut}, and then iterating over the control
  9717. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9718. %% then update the hash table, mapping the block's source to the target
  9719. %% of the \code{goto}. Also, the hash table may already have mapped some
  9720. %% labels to the block's source, to you must iterate through the hash
  9721. %% table and update all of those so that they instead map to the target
  9722. %% of the \code{goto}.
  9723. %% For the second phase, we recommend iterating through the $\Tail$ of
  9724. %% each block in the program, updating the target of every \code{goto}
  9725. %% according to the mapping in \code{short-cut}.
  9726. \begin{exercise}\normalfont\normalsize
  9727. Implement the improvements to the \code{explicate\_control} pass.
  9728. Check that it removes trivial blocks in a few example programs. Then
  9729. check that your compiler still passes all your tests.
  9730. \end{exercise}
  9731. \subsection{Remove Jumps}
  9732. There is an opportunity for removing jumps that is apparent in the
  9733. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9734. ends with a jump to \code{block\_5}, and there are no other jumps to
  9735. \code{block\_5} in the rest of the program. In this situation we can
  9736. avoid the runtime overhead of this jump by merging \code{block\_5}
  9737. into the preceding block, which in this case is the \code{start} block.
  9738. Figure~\ref{fig:remove-jumps} shows the output of
  9739. \code{allocate\_registers} on the left and the result of this
  9740. optimization on the right.
  9741. \begin{figure}[tbp]
  9742. \begin{tcolorbox}[colback=white]
  9743. {\if\edition\racketEd
  9744. \begin{tabular}{lll}
  9745. \begin{minipage}{0.5\textwidth}
  9746. % cond_test_82.rkt
  9747. \begin{lstlisting}
  9748. start:
  9749. callq read_int
  9750. movq %rax, %rcx
  9751. jmp block_5
  9752. block_5:
  9753. movq %rcx, %rax
  9754. addq $2, %rax
  9755. jmp conclusion
  9756. \end{lstlisting}
  9757. \end{minipage}
  9758. &
  9759. $\Rightarrow\qquad$
  9760. \begin{minipage}{0.4\textwidth}
  9761. \begin{lstlisting}
  9762. start:
  9763. callq read_int
  9764. movq %rax, %rcx
  9765. movq %rcx, %rax
  9766. addq $2, %rax
  9767. jmp conclusion
  9768. \end{lstlisting}
  9769. \end{minipage}
  9770. \end{tabular}
  9771. \fi}
  9772. {\if\edition\pythonEd
  9773. \begin{tabular}{lll}
  9774. \begin{minipage}{0.5\textwidth}
  9775. % cond_test_20.rkt
  9776. \begin{lstlisting}
  9777. start:
  9778. callq read_int
  9779. movq %rax, tmp_0
  9780. cmpq 1, tmp_0
  9781. je block_3
  9782. jmp block_4
  9783. block_3:
  9784. movq 42, tmp_1
  9785. jmp block_2
  9786. block_4:
  9787. movq 0, tmp_1
  9788. jmp block_2
  9789. block_2:
  9790. movq tmp_1, %rdi
  9791. callq print_int
  9792. movq 0, %rax
  9793. jmp conclusion
  9794. \end{lstlisting}
  9795. \end{minipage}
  9796. &
  9797. $\Rightarrow\qquad$
  9798. \begin{minipage}{0.4\textwidth}
  9799. \begin{lstlisting}
  9800. start:
  9801. callq read_int
  9802. movq %rax, tmp_0
  9803. cmpq 1, tmp_0
  9804. je block_3
  9805. movq 0, tmp_1
  9806. jmp block_2
  9807. block_3:
  9808. movq 42, tmp_1
  9809. jmp block_2
  9810. block_2:
  9811. movq tmp_1, %rdi
  9812. callq print_int
  9813. movq 0, %rax
  9814. jmp conclusion
  9815. \end{lstlisting}
  9816. \end{minipage}
  9817. \end{tabular}
  9818. \fi}
  9819. \end{tcolorbox}
  9820. \caption{Merging basic blocks by removing unnecessary jumps.}
  9821. \label{fig:remove-jumps}
  9822. \end{figure}
  9823. \begin{exercise}\normalfont\normalsize
  9824. %
  9825. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9826. into their preceding basic block, when there is only one preceding
  9827. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9828. %
  9829. {\if\edition\racketEd
  9830. In the \code{run-tests.rkt} script, add the following entry to the
  9831. list of \code{passes} between \code{allocate\_registers}
  9832. and \code{patch\_instructions}:
  9833. \begin{lstlisting}
  9834. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9835. \end{lstlisting}
  9836. \fi}
  9837. %
  9838. Run the script to test your compiler.
  9839. %
  9840. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9841. blocks on several test programs.
  9842. \end{exercise}
  9843. \section{Further Reading}
  9844. \label{sec:cond-further-reading}
  9845. The algorithm for the \code{explicate\_control} pass is based on the
  9846. \code{expose-basic-blocks} pass in the course notes of
  9847. \citet{Dybvig:2010aa}.
  9848. %
  9849. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9850. \citet{Appel:2003fk}, and is related to translations into continuation
  9851. passing
  9852. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9853. %
  9854. The treatment of conditionals in the \code{explicate\_control} pass is
  9855. similar to short-cut boolean
  9856. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9857. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9858. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9859. \chapter{Loops and Dataflow Analysis}
  9860. \label{ch:Lwhile}
  9861. \setcounter{footnote}{0}
  9862. % TODO: define R'_8
  9863. % TODO: multi-graph
  9864. {\if\edition\racketEd
  9865. %
  9866. In this chapter we study two features that are the hallmarks of
  9867. imperative programming languages: loops and assignments to local
  9868. variables. The following example demonstrates these new features by
  9869. computing the sum of the first five positive integers:
  9870. % similar to loop_test_1.rkt
  9871. \begin{lstlisting}
  9872. (let ([sum 0])
  9873. (let ([i 5])
  9874. (begin
  9875. (while (> i 0)
  9876. (begin
  9877. (set! sum (+ sum i))
  9878. (set! i (- i 1))))
  9879. sum)))
  9880. \end{lstlisting}
  9881. The \code{while} loop consists of a condition and a
  9882. body.\footnote{The \code{while} loop is not a built-in
  9883. feature of the Racket language, but Racket includes many looping
  9884. constructs and it is straightforward to define \code{while} as a
  9885. macro.} The body is evaluated repeatedly so long as the condition
  9886. remains true.
  9887. %
  9888. The \code{set!} consists of a variable and a right-hand side
  9889. expression. The \code{set!} updates value of the variable to the
  9890. value of the right-hand side.
  9891. %
  9892. The primary purpose of both the \code{while} loop and \code{set!} is
  9893. to cause side effects, so they do not give a meaningful result
  9894. value. Instead, their result is the \code{\#<void>} value. The
  9895. expression \code{(void)} is an explicit way to create the
  9896. \code{\#<void>} value, and it has type \code{Void}. The
  9897. \code{\#<void>} value can be passed around just like other values
  9898. inside an \LangLoop{} program, and it can be compared for equality with
  9899. another \code{\#<void>} value. However, there are no other operations
  9900. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9901. Racket defines the \code{void?} predicate that returns \code{\#t}
  9902. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9903. %
  9904. \footnote{Racket's \code{Void} type corresponds to what is often
  9905. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9906. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9907. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9908. %
  9909. With the addition of side effect-producing features such as
  9910. \code{while} loop and \code{set!}, it is helpful to include a language
  9911. feature for sequencing side effects: the \code{begin} expression. It
  9912. consists of one or more subexpressions that are evaluated
  9913. left to right.
  9914. %
  9915. \fi}
  9916. {\if\edition\pythonEd
  9917. %
  9918. In this chapter we study loops, one of the hallmarks of imperative
  9919. programming languages. The following example demonstrates the
  9920. \code{while} loop by computing the sum of the first five positive
  9921. integers.
  9922. \begin{lstlisting}
  9923. sum = 0
  9924. i = 5
  9925. while i > 0:
  9926. sum = sum + i
  9927. i = i - 1
  9928. print(sum)
  9929. \end{lstlisting}
  9930. The \code{while} loop consists of a condition expression and a body (a
  9931. sequence of statements). The body is evaluated repeatedly so long as
  9932. the condition remains true.
  9933. %
  9934. \fi}
  9935. \section{The \LangLoop{} Language}
  9936. \newcommand{\LwhileGrammarRacket}{
  9937. \begin{array}{lcl}
  9938. \Type &::=& \key{Void}\\
  9939. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9940. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9941. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9942. \end{array}
  9943. }
  9944. \newcommand{\LwhileASTRacket}{
  9945. \begin{array}{lcl}
  9946. \Type &::=& \key{Void}\\
  9947. \Exp &::=& \SETBANG{\Var}{\Exp}
  9948. \MID \BEGIN{\Exp^{*}}{\Exp}
  9949. \MID \WHILE{\Exp}{\Exp}
  9950. \MID \VOID{}
  9951. \end{array}
  9952. }
  9953. \newcommand{\LwhileGrammarPython}{
  9954. \begin{array}{rcl}
  9955. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9956. \end{array}
  9957. }
  9958. \newcommand{\LwhileASTPython}{
  9959. \begin{array}{lcl}
  9960. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9961. \end{array}
  9962. }
  9963. \begin{figure}[tp]
  9964. \centering
  9965. \begin{tcolorbox}[colback=white]
  9966. \small
  9967. {\if\edition\racketEd
  9968. \[
  9969. \begin{array}{l}
  9970. \gray{\LintGrammarRacket{}} \\ \hline
  9971. \gray{\LvarGrammarRacket{}} \\ \hline
  9972. \gray{\LifGrammarRacket{}} \\ \hline
  9973. \LwhileGrammarRacket \\
  9974. \begin{array}{lcl}
  9975. \LangLoopM{} &::=& \Exp
  9976. \end{array}
  9977. \end{array}
  9978. \]
  9979. \fi}
  9980. {\if\edition\pythonEd
  9981. \[
  9982. \begin{array}{l}
  9983. \gray{\LintGrammarPython} \\ \hline
  9984. \gray{\LvarGrammarPython} \\ \hline
  9985. \gray{\LifGrammarPython} \\ \hline
  9986. \LwhileGrammarPython \\
  9987. \begin{array}{rcl}
  9988. \LangLoopM{} &::=& \Stmt^{*}
  9989. \end{array}
  9990. \end{array}
  9991. \]
  9992. \fi}
  9993. \end{tcolorbox}
  9994. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9995. \label{fig:Lwhile-concrete-syntax}
  9996. \end{figure}
  9997. \begin{figure}[tp]
  9998. \centering
  9999. \begin{tcolorbox}[colback=white]
  10000. \small
  10001. {\if\edition\racketEd
  10002. \[
  10003. \begin{array}{l}
  10004. \gray{\LintOpAST} \\ \hline
  10005. \gray{\LvarASTRacket{}} \\ \hline
  10006. \gray{\LifASTRacket{}} \\ \hline
  10007. \LwhileASTRacket{} \\
  10008. \begin{array}{lcl}
  10009. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10010. \end{array}
  10011. \end{array}
  10012. \]
  10013. \fi}
  10014. {\if\edition\pythonEd
  10015. \[
  10016. \begin{array}{l}
  10017. \gray{\LintASTPython} \\ \hline
  10018. \gray{\LvarASTPython} \\ \hline
  10019. \gray{\LifASTPython} \\ \hline
  10020. \LwhileASTPython \\
  10021. \begin{array}{lcl}
  10022. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10023. \end{array}
  10024. \end{array}
  10025. \]
  10026. \fi}
  10027. \end{tcolorbox}
  10028. \python{
  10029. \index{subject}{While@\texttt{While}}
  10030. }
  10031. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10032. \label{fig:Lwhile-syntax}
  10033. \end{figure}
  10034. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10035. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10036. shows the definition of its abstract syntax.
  10037. %
  10038. The definitional interpreter for \LangLoop{} is shown in
  10039. figure~\ref{fig:interp-Lwhile}.
  10040. %
  10041. {\if\edition\racketEd
  10042. %
  10043. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10044. and \code{Void}, and we make changes to the cases for \code{Var} and
  10045. \code{Let} regarding variables. To support assignment to variables and
  10046. to make their lifetimes indefinite (see the second example in
  10047. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10048. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10049. value.
  10050. %
  10051. Now we discuss the new cases. For \code{SetBang}, we find the
  10052. variable in the environment to obtain a boxed value, and then we change
  10053. it using \code{set-box!} to the result of evaluating the right-hand
  10054. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10055. %
  10056. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10057. if the result is true, (2) evaluate the body.
  10058. The result value of a \code{while} loop is also \code{\#<void>}.
  10059. %
  10060. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10061. subexpressions \itm{es} for their effects and then evaluates
  10062. and returns the result from \itm{body}.
  10063. %
  10064. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10065. %
  10066. \fi}
  10067. {\if\edition\pythonEd
  10068. %
  10069. We add a new case for \code{While} in the \code{interp\_stmts}
  10070. function, where we repeatedly interpret the \code{body} so long as the
  10071. \code{test} expression remains true.
  10072. %
  10073. \fi}
  10074. \begin{figure}[tbp]
  10075. \begin{tcolorbox}[colback=white]
  10076. {\if\edition\racketEd
  10077. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10078. (define interp-Lwhile-class
  10079. (class interp-Lif-class
  10080. (super-new)
  10081. (define/override ((interp-exp env) e)
  10082. (define recur (interp-exp env))
  10083. (match e
  10084. [(Let x e body)
  10085. (define new-env (dict-set env x (box (recur e))))
  10086. ((interp-exp new-env) body)]
  10087. [(Var x) (unbox (dict-ref env x))]
  10088. [(SetBang x rhs)
  10089. (set-box! (dict-ref env x) (recur rhs))]
  10090. [(WhileLoop cnd body)
  10091. (define (loop)
  10092. (cond [(recur cnd) (recur body) (loop)]
  10093. [else (void)]))
  10094. (loop)]
  10095. [(Begin es body)
  10096. (for ([e es]) (recur e))
  10097. (recur body)]
  10098. [(Void) (void)]
  10099. [else ((super interp-exp env) e)]))
  10100. ))
  10101. (define (interp-Lwhile p)
  10102. (send (new interp-Lwhile-class) interp-program p))
  10103. \end{lstlisting}
  10104. \fi}
  10105. {\if\edition\pythonEd
  10106. \begin{lstlisting}
  10107. class InterpLwhile(InterpLif):
  10108. def interp_stmts(self, ss, env):
  10109. if len(ss) == 0:
  10110. return
  10111. match ss[0]:
  10112. case While(test, body, []):
  10113. while self.interp_exp(test, env):
  10114. self.interp_stmts(body, env)
  10115. return self.interp_stmts(ss[1:], env)
  10116. case _:
  10117. return super().interp_stmts(ss, env)
  10118. \end{lstlisting}
  10119. \fi}
  10120. \end{tcolorbox}
  10121. \caption{Interpreter for \LangLoop{}.}
  10122. \label{fig:interp-Lwhile}
  10123. \end{figure}
  10124. The definition of the type checker for \LangLoop{} is shown in
  10125. figure~\ref{fig:type-check-Lwhile}.
  10126. %
  10127. {\if\edition\racketEd
  10128. %
  10129. The type checking of the \code{SetBang} expression requires the type
  10130. of the variable and the right-hand side to agree. The result type is
  10131. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10132. and the result type is \code{Void}. For \code{Begin}, the result type
  10133. is the type of its last subexpression.
  10134. %
  10135. \fi}
  10136. %
  10137. {\if\edition\pythonEd
  10138. %
  10139. A \code{while} loop is well typed if the type of the \code{test}
  10140. expression is \code{bool} and the statements in the \code{body} are
  10141. well typed.
  10142. %
  10143. \fi}
  10144. \begin{figure}[tbp]
  10145. \begin{tcolorbox}[colback=white]
  10146. {\if\edition\racketEd
  10147. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10148. (define type-check-Lwhile-class
  10149. (class type-check-Lif-class
  10150. (super-new)
  10151. (inherit check-type-equal?)
  10152. (define/override (type-check-exp env)
  10153. (lambda (e)
  10154. (define recur (type-check-exp env))
  10155. (match e
  10156. [(SetBang x rhs)
  10157. (define-values (rhs^ rhsT) (recur rhs))
  10158. (define varT (dict-ref env x))
  10159. (check-type-equal? rhsT varT e)
  10160. (values (SetBang x rhs^) 'Void)]
  10161. [(WhileLoop cnd body)
  10162. (define-values (cnd^ Tc) (recur cnd))
  10163. (check-type-equal? Tc 'Boolean e)
  10164. (define-values (body^ Tbody) ((type-check-exp env) body))
  10165. (values (WhileLoop cnd^ body^) 'Void)]
  10166. [(Begin es body)
  10167. (define-values (es^ ts)
  10168. (for/lists (l1 l2) ([e es]) (recur e)))
  10169. (define-values (body^ Tbody) (recur body))
  10170. (values (Begin es^ body^) Tbody)]
  10171. [else ((super type-check-exp env) e)])))
  10172. ))
  10173. (define (type-check-Lwhile p)
  10174. (send (new type-check-Lwhile-class) type-check-program p))
  10175. \end{lstlisting}
  10176. \fi}
  10177. {\if\edition\pythonEd
  10178. \begin{lstlisting}
  10179. class TypeCheckLwhile(TypeCheckLif):
  10180. def type_check_stmts(self, ss, env):
  10181. if len(ss) == 0:
  10182. return
  10183. match ss[0]:
  10184. case While(test, body, []):
  10185. test_t = self.type_check_exp(test, env)
  10186. check_type_equal(bool, test_t, test)
  10187. body_t = self.type_check_stmts(body, env)
  10188. return self.type_check_stmts(ss[1:], env)
  10189. case _:
  10190. return super().type_check_stmts(ss, env)
  10191. \end{lstlisting}
  10192. \fi}
  10193. \end{tcolorbox}
  10194. \caption{Type checker for the \LangLoop{} language.}
  10195. \label{fig:type-check-Lwhile}
  10196. \end{figure}
  10197. {\if\edition\racketEd
  10198. %
  10199. At first glance, the translation of these language features to x86
  10200. seems straightforward because the \LangCIf{} intermediate language
  10201. already supports all the ingredients that we need: assignment,
  10202. \code{goto}, conditional branching, and sequencing. However, there are
  10203. complications that arise, which we discuss in the next section. After
  10204. that we introduce the changes necessary to the existing passes.
  10205. %
  10206. \fi}
  10207. {\if\edition\pythonEd
  10208. %
  10209. At first glance, the translation of \code{while} loops to x86 seems
  10210. straightforward because the \LangCIf{} intermediate language already
  10211. supports \code{goto} and conditional branching. However, there are
  10212. complications that arise which we discuss in the next section. After
  10213. that we introduce the changes necessary to the existing passes.
  10214. %
  10215. \fi}
  10216. \section{Cyclic Control Flow and Dataflow Analysis}
  10217. \label{sec:dataflow-analysis}
  10218. Up until this point, the programs generated in
  10219. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10220. \code{while} loop introduces a cycle. Does that matter?
  10221. %
  10222. Indeed, it does. Recall that for register allocation, the compiler
  10223. performs liveness analysis to determine which variables can share the
  10224. same register. To accomplish this, we analyzed the control-flow graph
  10225. in reverse topological order
  10226. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10227. well defined only for acyclic graphs.
  10228. Let us return to the example of computing the sum of the first five
  10229. positive integers. Here is the program after instruction selection but
  10230. before register allocation.
  10231. \begin{center}
  10232. {\if\edition\racketEd
  10233. \begin{minipage}{0.45\textwidth}
  10234. \begin{lstlisting}
  10235. (define (main) : Integer
  10236. mainstart:
  10237. movq $0, sum
  10238. movq $5, i
  10239. jmp block5
  10240. block5:
  10241. movq i, tmp3
  10242. cmpq tmp3, $0
  10243. jl block7
  10244. jmp block8
  10245. \end{lstlisting}
  10246. \end{minipage}
  10247. \begin{minipage}{0.45\textwidth}
  10248. \begin{lstlisting}
  10249. block7:
  10250. addq i, sum
  10251. movq $1, tmp4
  10252. negq tmp4
  10253. addq tmp4, i
  10254. jmp block5
  10255. block8:
  10256. movq $27, %rax
  10257. addq sum, %rax
  10258. jmp mainconclusion
  10259. )
  10260. \end{lstlisting}
  10261. \end{minipage}
  10262. \fi}
  10263. {\if\edition\pythonEd
  10264. \begin{minipage}{0.45\textwidth}
  10265. \begin{lstlisting}
  10266. mainstart:
  10267. movq $0, sum
  10268. movq $5, i
  10269. jmp block5
  10270. block5:
  10271. cmpq $0, i
  10272. jg block7
  10273. jmp block8
  10274. \end{lstlisting}
  10275. \end{minipage}
  10276. \begin{minipage}{0.45\textwidth}
  10277. \begin{lstlisting}
  10278. block7:
  10279. addq i, sum
  10280. subq $1, i
  10281. jmp block5
  10282. block8:
  10283. movq sum, %rdi
  10284. callq print_int
  10285. movq $0, %rax
  10286. jmp mainconclusion
  10287. \end{lstlisting}
  10288. \end{minipage}
  10289. \fi}
  10290. \end{center}
  10291. Recall that liveness analysis works backward, starting at the end
  10292. of each function. For this example we could start with \code{block8}
  10293. because we know what is live at the beginning of the conclusion:
  10294. only \code{rax} and \code{rsp}. So the live-before set
  10295. for \code{block8} is \code{\{rsp,sum\}}.
  10296. %
  10297. Next we might try to analyze \code{block5} or \code{block7}, but
  10298. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10299. we are stuck.
  10300. The way out of this impasse is to realize that we can compute an
  10301. underapproximation of each live-before set by starting with empty
  10302. live-after sets. By \emph{underapproximation}, we mean that the set
  10303. contains only variables that are live for some execution of the
  10304. program, but the set may be missing some variables that are live.
  10305. Next, the underapproximations for each block can be improved by (1)
  10306. updating the live-after set for each block using the approximate
  10307. live-before sets from the other blocks, and (2) performing liveness
  10308. analysis again on each block. In fact, by iterating this process, the
  10309. underapproximations eventually become the correct solutions!
  10310. %
  10311. This approach of iteratively analyzing a control-flow graph is
  10312. applicable to many static analysis problems and goes by the name
  10313. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10314. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10315. Washington.
  10316. Let us apply this approach to the previously presented example. We use
  10317. the empty set for the initial live-before set for each block. Let
  10318. $m_0$ be the following mapping from label names to sets of locations
  10319. (variables and registers):
  10320. \begin{center}
  10321. \begin{lstlisting}
  10322. mainstart: {}, block5: {}, block7: {}, block8: {}
  10323. \end{lstlisting}
  10324. \end{center}
  10325. Using the above live-before approximations, we determine the
  10326. live-after for each block and then apply liveness analysis to each
  10327. block. This produces our next approximation $m_1$ of the live-before
  10328. sets.
  10329. \begin{center}
  10330. \begin{lstlisting}
  10331. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10332. \end{lstlisting}
  10333. \end{center}
  10334. For the second round, the live-after for \code{mainstart} is the
  10335. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10336. the liveness analysis for \code{mainstart} computes the empty set. The
  10337. live-after for \code{block5} is the union of the live-before sets for
  10338. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  10339. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  10340. sum\}}. The live-after for \code{block7} is the live-before for
  10341. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10342. So the liveness analysis for \code{block7} remains \code{\{i,
  10343. sum\}}. Together these yield the following approximation $m_2$ of
  10344. the live-before sets:
  10345. \begin{center}
  10346. \begin{lstlisting}
  10347. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10348. \end{lstlisting}
  10349. \end{center}
  10350. In the preceding iteration, only \code{block5} changed, so we can
  10351. limit our attention to \code{mainstart} and \code{block7}, the two
  10352. blocks that jump to \code{block5}. As a result, the live-before sets
  10353. for \code{mainstart} and \code{block7} are updated to include
  10354. \code{rsp}, yielding the following approximation $m_3$:
  10355. \begin{center}
  10356. \begin{lstlisting}
  10357. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10358. \end{lstlisting}
  10359. \end{center}
  10360. Because \code{block7} changed, we analyze \code{block5} once more, but
  10361. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10362. our approximations have converged, so $m_3$ is the solution.
  10363. This iteration process is guaranteed to converge to a solution by the
  10364. Kleene fixed-point theorem, a general theorem about functions on
  10365. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10366. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10367. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10368. join operator
  10369. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10370. ordering}\index{subject}{join}\footnote{Technically speaking, we
  10371. will be working with join semilattices.} When two elements are
  10372. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10373. as much information as $m_i$, so we can think of $m_j$ as a
  10374. better-than-or-equal-to approximation in relation to $m_i$. The
  10375. bottom element $\bot$ represents the complete lack of information,
  10376. that is, the worst approximation. The join operator takes two lattice
  10377. elements and combines their information; that is, it produces the
  10378. least upper bound of the two.\index{subject}{least upper bound}
  10379. A dataflow analysis typically involves two lattices: one lattice to
  10380. represent abstract states and another lattice that aggregates the
  10381. abstract states of all the blocks in the control-flow graph. For
  10382. liveness analysis, an abstract state is a set of locations. We form
  10383. the lattice $L$ by taking its elements to be sets of locations, the
  10384. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10385. set, and the join operator to be set union.
  10386. %
  10387. We form a second lattice $M$ by taking its elements to be mappings
  10388. from the block labels to sets of locations (elements of $L$). We
  10389. order the mappings point-wise, using the ordering of $L$. So, given any
  10390. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10391. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10392. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10393. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10394. We can think of one iteration of liveness analysis applied to the
  10395. whole program as being a function $f$ on the lattice $M$. It takes a
  10396. mapping as input and computes a new mapping.
  10397. \[
  10398. f(m_i) = m_{i+1}
  10399. \]
  10400. Next let us think for a moment about what a final solution $m_s$
  10401. should look like. If we perform liveness analysis using the solution
  10402. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10403. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10404. \[
  10405. f(m_s) = m_s
  10406. \]
  10407. Furthermore, the solution should include only locations that are
  10408. forced to be there by performing liveness analysis on the program, so
  10409. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10410. The Kleene fixed-point theorem states that if a function $f$ is
  10411. monotone (better inputs produce better outputs), then the least fixed
  10412. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10413. chain} obtained by starting at $\bot$ and iterating $f$, as
  10414. follows:\index{subject}{Kleene fixed-point theorem}
  10415. \[
  10416. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10417. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10418. \]
  10419. When a lattice contains only finitely long ascending chains, then
  10420. every Kleene chain tops out at some fixed point after some number of
  10421. iterations of $f$.
  10422. \[
  10423. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10424. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10425. \]
  10426. The liveness analysis is indeed a monotone function and the lattice
  10427. $M$ has finitely long ascending chains because there are only a
  10428. finite number of variables and blocks in the program. Thus we are
  10429. guaranteed that iteratively applying liveness analysis to all blocks
  10430. in the program will eventually produce the least fixed point solution.
  10431. Next let us consider dataflow analysis in general and discuss the
  10432. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10433. %
  10434. The algorithm has four parameters: the control-flow graph \code{G}, a
  10435. function \code{transfer} that applies the analysis to one block, and the
  10436. \code{bottom} and \code{join} operators for the lattice of abstract
  10437. states. The \code{analyze\_dataflow} function is formulated as a
  10438. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10439. function come from the predecessor nodes in the control-flow
  10440. graph. However, liveness analysis is a \emph{backward} dataflow
  10441. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10442. function with the transpose of the control-flow graph.
  10443. The algorithm begins by creating the bottom mapping, represented by a
  10444. hash table. It then pushes all the nodes in the control-flow graph
  10445. onto the work list (a queue). The algorithm repeats the \code{while}
  10446. loop as long as there are items in the work list. In each iteration, a
  10447. node is popped from the work list and processed. The \code{input} for
  10448. the node is computed by taking the join of the abstract states of all
  10449. the predecessor nodes. The \code{transfer} function is then applied to
  10450. obtain the \code{output} abstract state. If the output differs from
  10451. the previous state for this block, the mapping for this block is
  10452. updated and its successor nodes are pushed onto the work list.
  10453. \begin{figure}[tb]
  10454. \begin{tcolorbox}[colback=white]
  10455. {\if\edition\racketEd
  10456. \begin{lstlisting}
  10457. (define (analyze_dataflow G transfer bottom join)
  10458. (define mapping (make-hash))
  10459. (for ([v (in-vertices G)])
  10460. (dict-set! mapping v bottom))
  10461. (define worklist (make-queue))
  10462. (for ([v (in-vertices G)])
  10463. (enqueue! worklist v))
  10464. (define trans-G (transpose G))
  10465. (while (not (queue-empty? worklist))
  10466. (define node (dequeue! worklist))
  10467. (define input (for/fold ([state bottom])
  10468. ([pred (in-neighbors trans-G node)])
  10469. (join state (dict-ref mapping pred))))
  10470. (define output (transfer node input))
  10471. (cond [(not (equal? output (dict-ref mapping node)))
  10472. (dict-set! mapping node output)
  10473. (for ([v (in-neighbors G node)])
  10474. (enqueue! worklist v))]))
  10475. mapping)
  10476. \end{lstlisting}
  10477. \fi}
  10478. {\if\edition\pythonEd
  10479. \begin{lstlisting}
  10480. def analyze_dataflow(G, transfer, bottom, join):
  10481. trans_G = transpose(G)
  10482. mapping = dict((v, bottom) for v in G.vertices())
  10483. worklist = deque(G.vertices)
  10484. while worklist:
  10485. node = worklist.pop()
  10486. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10487. input = reduce(join, inputs, bottom)
  10488. output = transfer(node, input)
  10489. if output != mapping[node]:
  10490. mapping[node] = output
  10491. worklist.extend(G.adjacent(node))
  10492. \end{lstlisting}
  10493. \fi}
  10494. \end{tcolorbox}
  10495. \caption{Generic work list algorithm for dataflow analysis}
  10496. \label{fig:generic-dataflow}
  10497. \end{figure}
  10498. {\if\edition\racketEd
  10499. \section{Mutable Variables and Remove Complex Operands}
  10500. There is a subtle interaction between the
  10501. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10502. and the left-to-right order of evaluation of Racket. Consider the
  10503. following example:
  10504. \begin{lstlisting}
  10505. (let ([x 2])
  10506. (+ x (begin (set! x 40) x)))
  10507. \end{lstlisting}
  10508. The result of this program is \code{42} because the first read from
  10509. \code{x} produces \code{2} and the second produces \code{40}. However,
  10510. if we naively apply the \code{remove\_complex\_operands} pass to this
  10511. example we obtain the following program whose result is \code{80}!
  10512. \begin{lstlisting}
  10513. (let ([x 2])
  10514. (let ([tmp (begin (set! x 40) x)])
  10515. (+ x tmp)))
  10516. \end{lstlisting}
  10517. The problem is that with mutable variables, the ordering between
  10518. reads and writes is important, and the
  10519. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10520. before the first read of \code{x}.
  10521. We recommend solving this problem by giving special treatment to reads
  10522. from mutable variables, that is, variables that occur on the left-hand
  10523. side of a \code{set!}. We mark each read from a mutable variable with
  10524. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10525. that the read operation is effectful in that it can produce different
  10526. results at different points in time. Let's apply this idea to the
  10527. following variation that also involves a variable that is not mutated:
  10528. % loop_test_24.rkt
  10529. \begin{lstlisting}
  10530. (let ([x 2])
  10531. (let ([y 0])
  10532. (+ y (+ x (begin (set! x 40) x)))))
  10533. \end{lstlisting}
  10534. We first analyze this program to discover that variable \code{x}
  10535. is mutable but \code{y} is not. We then transform the program as
  10536. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10537. \begin{lstlisting}
  10538. (let ([x 2])
  10539. (let ([y 0])
  10540. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10541. \end{lstlisting}
  10542. Now that we have a clear distinction between reads from mutable and
  10543. immutable variables, we can apply the \code{remove\_complex\_operands}
  10544. pass, where reads from immutable variables are still classified as
  10545. atomic expressions but reads from mutable variables are classified as
  10546. complex. Thus, \code{remove\_complex\_operands} yields the following
  10547. program:\\
  10548. \begin{minipage}{\textwidth}
  10549. \begin{lstlisting}
  10550. (let ([x 2])
  10551. (let ([y 0])
  10552. (+ y (let ([t1 (get! x)])
  10553. (let ([t2 (begin (set! x 40) (get! x))])
  10554. (+ t1 t2))))))
  10555. \end{lstlisting}
  10556. \end{minipage}
  10557. The temporary variable \code{t1} gets the value of \code{x} before the
  10558. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10559. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10560. do not generate a temporary variable for the occurrence of \code{y}
  10561. because it's an immutable variable. We want to avoid such unnecessary
  10562. extra temporaries because they would needless increase the number of
  10563. variables, making it more likely for some of them to be spilled. The
  10564. result of this program is \code{42}, the same as the result prior to
  10565. \code{remove\_complex\_operands}.
  10566. The approach that we've sketched requires only a small
  10567. modification to \code{remove\_complex\_operands} to handle
  10568. \code{get!}. However, it requires a new pass, called
  10569. \code{uncover-get!}, that we discuss in
  10570. section~\ref{sec:uncover-get-bang}.
  10571. As an aside, this problematic interaction between \code{set!} and the
  10572. pass \code{remove\_complex\_operands} is particular to Racket and not
  10573. its predecessor, the Scheme language. The key difference is that
  10574. Scheme does not specify an order of evaluation for the arguments of an
  10575. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10576. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10577. would be correct results for the example program. Interestingly,
  10578. Racket is implemented on top of the Chez Scheme
  10579. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10580. presented in this section (using extra \code{let} bindings to control
  10581. the order of evaluation) is used in the translation from Racket to
  10582. Scheme~\citep{Flatt:2019tb}.
  10583. \fi} % racket
  10584. Having discussed the complications that arise from adding support for
  10585. assignment and loops, we turn to discussing the individual compilation
  10586. passes.
  10587. {\if\edition\racketEd
  10588. \section{Uncover \texttt{get!}}
  10589. \label{sec:uncover-get-bang}
  10590. The goal of this pass is to mark uses of mutable variables so that
  10591. \code{remove\_complex\_operands} can treat them as complex expressions
  10592. and thereby preserve their ordering relative to the side effects in
  10593. other operands. So, the first step is to collect all the mutable
  10594. variables. We recommend creating an auxiliary function for this,
  10595. named \code{collect-set!}, that recursively traverses expressions,
  10596. returning the set of all variables that occur on the left-hand side of a
  10597. \code{set!}. Here's an excerpt of its implementation.
  10598. \begin{center}
  10599. \begin{minipage}{\textwidth}
  10600. \begin{lstlisting}
  10601. (define (collect-set! e)
  10602. (match e
  10603. [(Var x) (set)]
  10604. [(Int n) (set)]
  10605. [(Let x rhs body)
  10606. (set-union (collect-set! rhs) (collect-set! body))]
  10607. [(SetBang var rhs)
  10608. (set-union (set var) (collect-set! rhs))]
  10609. ...))
  10610. \end{lstlisting}
  10611. \end{minipage}
  10612. \end{center}
  10613. By placing this pass after \code{uniquify}, we need not worry about
  10614. variable shadowing, and our logic for \code{Let} can remain simple, as
  10615. in this excerpt.
  10616. The second step is to mark the occurrences of the mutable variables
  10617. with the new \code{GetBang} AST node (\code{get!} in concrete
  10618. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10619. function, which takes two parameters: the set of mutable variables
  10620. \code{set!-vars} and the expression \code{e} to be processed. The
  10621. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10622. mutable variable or leaves it alone if not.
  10623. \begin{center}
  10624. \begin{minipage}{\textwidth}
  10625. \begin{lstlisting}
  10626. (define ((uncover-get!-exp set!-vars) e)
  10627. (match e
  10628. [(Var x)
  10629. (if (set-member? set!-vars x)
  10630. (GetBang x)
  10631. (Var x))]
  10632. ...))
  10633. \end{lstlisting}
  10634. \end{minipage}
  10635. \end{center}
  10636. To wrap things up, define the \code{uncover-get!} function for
  10637. processing a whole program, using \code{collect-set!} to obtain the
  10638. set of mutable variables and then \code{uncover-get!-exp} to replace
  10639. their occurrences with \code{GetBang}.
  10640. \fi}
  10641. \section{Remove Complex Operands}
  10642. \label{sec:rco-loop}
  10643. {\if\edition\racketEd
  10644. %
  10645. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10646. \code{while} are all complex expressions. The subexpressions of
  10647. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10648. %
  10649. \fi}
  10650. {\if\edition\pythonEd
  10651. %
  10652. The change needed for this pass is to add a case for the \code{while}
  10653. statement. The condition of a \code{while} loop is allowed to be a
  10654. complex expression, just like the condition of the \code{if}
  10655. statement.
  10656. %
  10657. \fi}
  10658. %
  10659. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10660. \LangLoopANF{} of this pass.
  10661. \newcommand{\LwhileMonadASTRacket}{
  10662. \begin{array}{rcl}
  10663. \Atm &::=& \VOID{} \\
  10664. \Exp &::=& \GETBANG{\Var}
  10665. \MID \SETBANG{\Var}{\Exp}
  10666. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10667. &\MID& \WHILE{\Exp}{\Exp}
  10668. \end{array}
  10669. }
  10670. \newcommand{\LwhileMonadASTPython}{
  10671. \begin{array}{rcl}
  10672. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10673. \end{array}
  10674. }
  10675. \begin{figure}[tp]
  10676. \centering
  10677. \begin{tcolorbox}[colback=white]
  10678. \small
  10679. {\if\edition\racketEd
  10680. \[
  10681. \begin{array}{l}
  10682. \gray{\LvarMonadASTRacket} \\ \hline
  10683. \gray{\LifMonadASTRacket} \\ \hline
  10684. \LwhileMonadASTRacket \\
  10685. \begin{array}{rcl}
  10686. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10687. \end{array}
  10688. \end{array}
  10689. \]
  10690. \fi}
  10691. {\if\edition\pythonEd
  10692. \[
  10693. \begin{array}{l}
  10694. \gray{\LvarMonadASTPython} \\ \hline
  10695. \gray{\LifMonadASTPython} \\ \hline
  10696. \LwhileMonadASTPython \\
  10697. \begin{array}{rcl}
  10698. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10699. \end{array}
  10700. \end{array}
  10701. %% \begin{array}{rcl}
  10702. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10703. %% \Exp &::=& \Atm \MID \READ{} \\
  10704. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10705. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10706. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10707. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10708. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10709. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10710. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10711. %% \end{array}
  10712. \]
  10713. \fi}
  10714. \end{tcolorbox}
  10715. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10716. \label{fig:Lwhile-anf-syntax}
  10717. \end{figure}
  10718. {\if\edition\racketEd
  10719. %
  10720. As usual, when a complex expression appears in a grammar position that
  10721. needs to be atomic, such as the argument of a primitive operator, we
  10722. must introduce a temporary variable and bind it to the complex
  10723. expression. This approach applies, unchanged, to handle the new
  10724. language forms. For example, in the following code there are two
  10725. \code{begin} expressions appearing as arguments to the \code{+}
  10726. operator. The output of \code{rco\_exp} is then shown, in which the
  10727. \code{begin} expressions have been bound to temporary
  10728. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10729. allowed to have arbitrary expressions in their right-hand side
  10730. expression, so it is fine to place \code{begin} there.
  10731. %
  10732. \begin{center}
  10733. \begin{tabular}{lcl}
  10734. \begin{minipage}{0.4\textwidth}
  10735. \begin{lstlisting}
  10736. (let ([x2 10])
  10737. (let ([y3 0])
  10738. (+ (+ (begin
  10739. (set! y3 (read))
  10740. (get! x2))
  10741. (begin
  10742. (set! x2 (read))
  10743. (get! y3)))
  10744. (get! x2))))
  10745. \end{lstlisting}
  10746. \end{minipage}
  10747. &
  10748. $\Rightarrow$
  10749. &
  10750. \begin{minipage}{0.4\textwidth}
  10751. \begin{lstlisting}
  10752. (let ([x2 10])
  10753. (let ([y3 0])
  10754. (let ([tmp4 (begin
  10755. (set! y3 (read))
  10756. x2)])
  10757. (let ([tmp5 (begin
  10758. (set! x2 (read))
  10759. y3)])
  10760. (let ([tmp6 (+ tmp4 tmp5)])
  10761. (let ([tmp7 x2])
  10762. (+ tmp6 tmp7)))))))
  10763. \end{lstlisting}
  10764. \end{minipage}
  10765. \end{tabular}
  10766. \end{center}
  10767. \fi}
  10768. \section{Explicate Control \racket{and \LangCLoop{}}}
  10769. \label{sec:explicate-loop}
  10770. \newcommand{\CloopASTRacket}{
  10771. \begin{array}{lcl}
  10772. \Atm &::=& \VOID \\
  10773. \Stmt &::=& \READ{}
  10774. \end{array}
  10775. }
  10776. {\if\edition\racketEd
  10777. Recall that in the \code{explicate\_control} pass we define one helper
  10778. function for each kind of position in the program. For the \LangVar{}
  10779. language of integers and variables, we needed assignment and tail
  10780. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10781. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10782. another kind of position: effect position. Except for the last
  10783. subexpression, the subexpressions inside a \code{begin} are evaluated
  10784. only for their effect. Their result values are discarded. We can
  10785. generate better code by taking this fact into account.
  10786. The output language of \code{explicate\_control} is \LangCLoop{}
  10787. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10788. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10789. and that \code{read} may appear as a statement. The most significant
  10790. difference between the programs generated by \code{explicate\_control}
  10791. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10792. chapter is that the control-flow graphs of the latter may contain
  10793. cycles.
  10794. \begin{figure}[tp]
  10795. \begin{tcolorbox}[colback=white]
  10796. \small
  10797. \[
  10798. \begin{array}{l}
  10799. \gray{\CvarASTRacket} \\ \hline
  10800. \gray{\CifASTRacket} \\ \hline
  10801. \CloopASTRacket \\
  10802. \begin{array}{lcl}
  10803. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10804. \end{array}
  10805. \end{array}
  10806. \]
  10807. \end{tcolorbox}
  10808. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10809. \label{fig:c7-syntax}
  10810. \end{figure}
  10811. The new auxiliary function \code{explicate\_effect} takes an
  10812. expression (in an effect position) and the code for its
  10813. continuation. The function returns a $\Tail$ that includes the
  10814. generated code for the input expression followed by the
  10815. continuation. If the expression is obviously pure, that is, never
  10816. causes side effects, then the expression can be removed, so the result
  10817. is just the continuation.
  10818. %
  10819. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10820. interesting; the generated code is depicted in the following diagram:
  10821. \begin{center}
  10822. \begin{minipage}{0.3\textwidth}
  10823. \xymatrix{
  10824. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10825. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10826. & *+[F]{\txt{\itm{cont}}} \\
  10827. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10828. }
  10829. \end{minipage}
  10830. \end{center}
  10831. We start by creating a fresh label $\itm{loop}$ for the top of the
  10832. loop. Next, recursively process the \itm{body} (in effect position)
  10833. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10834. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10835. \itm{body'} as the \emph{then} branch and the continuation block as the
  10836. \emph{else} branch. The result should be added to the dictionary of
  10837. \code{basic-blocks} with the label \itm{loop}. The result for the
  10838. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10839. The auxiliary functions for tail, assignment, and predicate positions
  10840. need to be updated. The three new language forms, \code{while},
  10841. \code{set!}, and \code{begin}, can appear in assignment and tail
  10842. positions. Only \code{begin} may appear in predicate positions; the
  10843. other two have result type \code{Void}.
  10844. \fi}
  10845. %
  10846. {\if\edition\pythonEd
  10847. %
  10848. The output of this pass is the language \LangCIf{}. No new language
  10849. features are needed in the output because a \code{while} loop can be
  10850. expressed in terms of \code{goto} and \code{if} statements, which are
  10851. already in \LangCIf{}.
  10852. %
  10853. Add a case for the \code{while} statement to the
  10854. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10855. the condition expression.
  10856. %
  10857. \fi}
  10858. {\if\edition\racketEd
  10859. \section{Select Instructions}
  10860. \label{sec:select-instructions-loop}
  10861. Only two small additions are needed in the \code{select\_instructions}
  10862. pass to handle the changes to \LangCLoop{}. First, to handle the
  10863. addition of \VOID{} we simply translate it to \code{0}. Second,
  10864. \code{read} may appear as a stand-alone statement instead of
  10865. appearing only on the right-hand side of an assignment statement. The code
  10866. generation is nearly identical to the one for assignment; just leave
  10867. off the instruction for moving the result into the left-hand side.
  10868. \fi}
  10869. \section{Register Allocation}
  10870. \label{sec:register-allocation-loop}
  10871. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10872. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10873. which complicates the liveness analysis needed for register
  10874. allocation.
  10875. %
  10876. We recommend using the generic \code{analyze\_dataflow} function that
  10877. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10878. perform liveness analysis, replacing the code in
  10879. \code{uncover\_live} that processed the basic blocks in topological
  10880. order (section~\ref{sec:liveness-analysis-Lif}).
  10881. The \code{analyze\_dataflow} function has the following four parameters.
  10882. \begin{enumerate}
  10883. \item The first parameter \code{G} should be passed the transpose
  10884. of the control-flow graph.
  10885. \item The second parameter \code{transfer} should be passed a function
  10886. that applies liveness analysis to a basic block. It takes two
  10887. parameters: the label for the block to analyze and the live-after
  10888. set for that block. The transfer function should return the
  10889. live-before set for the block.
  10890. %
  10891. \racket{Also, as a side effect, it should update the block's
  10892. $\itm{info}$ with the liveness information for each instruction.}
  10893. %
  10894. \python{Also, as a side-effect, it should update the live-before and
  10895. live-after sets for each instruction.}
  10896. %
  10897. To implement the \code{transfer} function, you should be able to
  10898. reuse the code you already have for analyzing basic blocks.
  10899. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10900. \code{bottom} and \code{join} for the lattice of abstract states,
  10901. that is, sets of locations. For liveness analysis, the bottom of the
  10902. lattice is the empty set, and the join operator is set union.
  10903. \end{enumerate}
  10904. \begin{figure}[p]
  10905. \begin{tcolorbox}[colback=white]
  10906. {\if\edition\racketEd
  10907. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10908. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10909. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10910. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10911. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10912. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10913. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10914. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10915. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10916. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10917. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10918. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10919. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10920. \path[->,bend left=15] (Lfun) edge [above] node
  10921. {\ttfamily\footnotesize shrink} (Lfun-2);
  10922. \path[->,bend left=15] (Lfun-2) edge [above] node
  10923. {\ttfamily\footnotesize uniquify} (F1-4);
  10924. \path[->,bend left=15] (F1-4) edge [above] node
  10925. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10926. \path[->,bend left=15] (F1-5) edge [left] node
  10927. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10928. \path[->,bend left=10] (F1-6) edge [above] node
  10929. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10930. \path[->,bend left=15] (C3-2) edge [right] node
  10931. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10932. \path[->,bend right=15] (x86-2) edge [right] node
  10933. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10934. \path[->,bend right=15] (x86-2-1) edge [below] node
  10935. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10936. \path[->,bend right=15] (x86-2-2) edge [right] node
  10937. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10938. \path[->,bend left=15] (x86-3) edge [above] node
  10939. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10940. \path[->,bend left=15] (x86-4) edge [right] node
  10941. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10942. \end{tikzpicture}
  10943. \fi}
  10944. {\if\edition\pythonEd
  10945. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10946. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10947. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10948. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10949. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10950. \node (x86-2) at (0,-2) {\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 (12,-2) {\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 remove\_complex\_operands} (F1-6);
  10958. \path[->,bend left=10] (F1-6) edge [right] node
  10959. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10960. \path[->,bend right=15] (C3-2) edge [right] node
  10961. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10962. \path[->,bend right=15] (x86-2) edge [below] node
  10963. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10964. \path[->,bend left=15] (x86-3) edge [above] node
  10965. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10966. \path[->,bend right=15] (x86-4) edge [below] node
  10967. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10968. \end{tikzpicture}
  10969. \fi}
  10970. \end{tcolorbox}
  10971. \caption{Diagram of the passes for \LangLoop{}.}
  10972. \label{fig:Lwhile-passes}
  10973. \end{figure}
  10974. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10975. for the compilation of \LangLoop{}.
  10976. % Further Reading: dataflow analysis
  10977. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10978. \chapter{Tuples and Garbage Collection}
  10979. \label{ch:Lvec}
  10980. \index{subject}{tuple}
  10981. \index{subject}{vector}
  10982. \index{subject}{allocate}
  10983. \index{subject}{heap allocate}
  10984. \setcounter{footnote}{0}
  10985. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10986. %% all the IR grammars are spelled out! \\ --Jeremy}
  10987. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10988. %% the root stack. \\ --Jeremy}
  10989. In this chapter we study the implementation of tuples\racket{, called
  10990. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10991. in which each element may have a different type.
  10992. %
  10993. This language feature is the first to use the computer's
  10994. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  10995. indefinite; that is, a tuple lives forever from the programmer's
  10996. viewpoint. Of course, from an implementer's viewpoint, it is important
  10997. to reclaim the space associated with a tuple when it is no longer
  10998. needed, which is why we also study \emph{garbage collection}
  10999. \index{subject}{garbage collection} techniques in this chapter.
  11000. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11001. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11002. language (chapter~\ref{ch:Lwhile}) with tuples.
  11003. %
  11004. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11005. copying live tuples back and forth between two halves of the heap. The
  11006. garbage collector requires coordination with the compiler so that it
  11007. can find all the live tuples.
  11008. %
  11009. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11010. discuss the necessary changes and additions to the compiler passes,
  11011. including a new compiler pass named \code{expose\_allocation}.
  11012. \section{The \LangVec{} Language}
  11013. \label{sec:r3}
  11014. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11015. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11016. the definition of the abstract syntax.
  11017. %
  11018. \racket{The \LangVec{} language includes the forms: \code{vector} for
  11019. creating a tuple, \code{vector-ref} for reading an element of a
  11020. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11021. \code{vector-length} for obtaining the number of elements of a
  11022. tuple.}
  11023. %
  11024. \python{The \LangVec{} language adds 1) tuple creation via a
  11025. comma-separated list of expressions, 2) accessing an element of a
  11026. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11027. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11028. operator, and 4) obtaining the number of elements (the length) of a
  11029. tuple. In this chapter, we restrict access indices to constant
  11030. integers.}
  11031. %
  11032. The following program shows an example use of tuples. It creates a tuple
  11033. \code{t} containing the elements \code{40},
  11034. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11035. contains just \code{2}. The element at index $1$ of \code{t} is
  11036. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11037. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11038. to which we add \code{2}, the element at index $0$ of the tuple.
  11039. The result of the program is \code{42}.
  11040. %
  11041. {\if\edition\racketEd
  11042. \begin{lstlisting}
  11043. (let ([t (vector 40 #t (vector 2))])
  11044. (if (vector-ref t 1)
  11045. (+ (vector-ref t 0)
  11046. (vector-ref (vector-ref t 2) 0))
  11047. 44))
  11048. \end{lstlisting}
  11049. \fi}
  11050. {\if\edition\pythonEd
  11051. \begin{lstlisting}
  11052. t = 40, True, (2,)
  11053. print( t[0] + t[2][0] if t[1] else 44 )
  11054. \end{lstlisting}
  11055. \fi}
  11056. \newcommand{\LtupGrammarRacket}{
  11057. \begin{array}{lcl}
  11058. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11059. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11060. \MID \LP\key{vector-length}\;\Exp\RP \\
  11061. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11062. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11063. \end{array}
  11064. }
  11065. \newcommand{\LtupASTRacket}{
  11066. \begin{array}{lcl}
  11067. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11068. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11069. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11070. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11071. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11072. \end{array}
  11073. }
  11074. \newcommand{\LtupGrammarPython}{
  11075. \begin{array}{rcl}
  11076. \itm{cmp} &::= & \key{is} \\
  11077. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11078. \end{array}
  11079. }
  11080. \newcommand{\LtupASTPython}{
  11081. \begin{array}{lcl}
  11082. \itm{cmp} &::= & \code{Is()} \\
  11083. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11084. &\MID& \LEN{\Exp}
  11085. \end{array}
  11086. }
  11087. \begin{figure}[tbp]
  11088. \centering
  11089. \begin{tcolorbox}[colback=white]
  11090. \small
  11091. {\if\edition\racketEd
  11092. \[
  11093. \begin{array}{l}
  11094. \gray{\LintGrammarRacket{}} \\ \hline
  11095. \gray{\LvarGrammarRacket{}} \\ \hline
  11096. \gray{\LifGrammarRacket{}} \\ \hline
  11097. \gray{\LwhileGrammarRacket} \\ \hline
  11098. \LtupGrammarRacket \\
  11099. \begin{array}{lcl}
  11100. \LangVecM{} &::=& \Exp
  11101. \end{array}
  11102. \end{array}
  11103. \]
  11104. \fi}
  11105. {\if\edition\pythonEd
  11106. \[
  11107. \begin{array}{l}
  11108. \gray{\LintGrammarPython{}} \\ \hline
  11109. \gray{\LvarGrammarPython{}} \\ \hline
  11110. \gray{\LifGrammarPython{}} \\ \hline
  11111. \gray{\LwhileGrammarPython} \\ \hline
  11112. \LtupGrammarPython \\
  11113. \begin{array}{rcl}
  11114. \LangVecM{} &::=& \Stmt^{*}
  11115. \end{array}
  11116. \end{array}
  11117. \]
  11118. \fi}
  11119. \end{tcolorbox}
  11120. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11121. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11122. \label{fig:Lvec-concrete-syntax}
  11123. \end{figure}
  11124. \begin{figure}[tp]
  11125. \centering
  11126. \begin{tcolorbox}[colback=white]
  11127. \small
  11128. {\if\edition\racketEd
  11129. \[
  11130. \begin{array}{l}
  11131. \gray{\LintOpAST} \\ \hline
  11132. \gray{\LvarASTRacket{}} \\ \hline
  11133. \gray{\LifASTRacket{}} \\ \hline
  11134. \gray{\LwhileASTRacket{}} \\ \hline
  11135. \LtupASTRacket{} \\
  11136. \begin{array}{lcl}
  11137. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11138. \end{array}
  11139. \end{array}
  11140. \]
  11141. \fi}
  11142. {\if\edition\pythonEd
  11143. \[
  11144. \begin{array}{l}
  11145. \gray{\LintASTPython} \\ \hline
  11146. \gray{\LvarASTPython} \\ \hline
  11147. \gray{\LifASTPython} \\ \hline
  11148. \gray{\LwhileASTPython} \\ \hline
  11149. \LtupASTPython \\
  11150. \begin{array}{lcl}
  11151. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11152. \end{array}
  11153. \end{array}
  11154. \]
  11155. \fi}
  11156. \end{tcolorbox}
  11157. \caption{The abstract syntax of \LangVec{}.}
  11158. \label{fig:Lvec-syntax}
  11159. \end{figure}
  11160. Tuples raise several interesting new issues. First, variable binding
  11161. performs a shallow copy in dealing with tuples, which means that
  11162. different variables can refer to the same tuple; that is, two
  11163. variables can be \emph{aliases}\index{subject}{alias} for the same
  11164. entity. Consider the following example, in which \code{t1} and
  11165. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11166. different tuple value with equal elements. The result of the
  11167. program is \code{42}.
  11168. \begin{center}
  11169. \begin{minipage}{0.96\textwidth}
  11170. {\if\edition\racketEd
  11171. \begin{lstlisting}
  11172. (let ([t1 (vector 3 7)])
  11173. (let ([t2 t1])
  11174. (let ([t3 (vector 3 7)])
  11175. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11176. 42
  11177. 0))))
  11178. \end{lstlisting}
  11179. \fi}
  11180. {\if\edition\pythonEd
  11181. \begin{lstlisting}
  11182. t1 = 3, 7
  11183. t2 = t1
  11184. t3 = 3, 7
  11185. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11186. \end{lstlisting}
  11187. \fi}
  11188. \end{minipage}
  11189. \end{center}
  11190. {\if\edition\racketEd
  11191. Whether two variables are aliased or not affects what happens
  11192. when the underlying tuple is mutated\index{subject}{mutation}.
  11193. Consider the following example in which \code{t1} and \code{t2}
  11194. again refer to the same tuple value.
  11195. \begin{center}
  11196. \begin{minipage}{0.96\textwidth}
  11197. \begin{lstlisting}
  11198. (let ([t1 (vector 3 7)])
  11199. (let ([t2 t1])
  11200. (let ([_ (vector-set! t2 0 42)])
  11201. (vector-ref t1 0))))
  11202. \end{lstlisting}
  11203. \end{minipage}
  11204. \end{center}
  11205. The mutation through \code{t2} is visible in referencing the tuple
  11206. from \code{t1}, so the result of this program is \code{42}.
  11207. \fi}
  11208. The next issue concerns the lifetime of tuples. When does a tuple's
  11209. lifetime end? Notice that \LangVec{} does not include an operation
  11210. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11211. to any notion of static scoping.
  11212. %
  11213. {\if\edition\racketEd
  11214. %
  11215. For example, the following program returns \code{42} even though the
  11216. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11217. that reads from the vector to which it was bound.
  11218. \begin{center}
  11219. \begin{minipage}{0.96\textwidth}
  11220. \begin{lstlisting}
  11221. (let ([v (vector (vector 44))])
  11222. (let ([x (let ([w (vector 42)])
  11223. (let ([_ (vector-set! v 0 w)])
  11224. 0))])
  11225. (+ x (vector-ref (vector-ref v 0) 0))))
  11226. \end{lstlisting}
  11227. \end{minipage}
  11228. \end{center}
  11229. \fi}
  11230. %
  11231. {\if\edition\pythonEd
  11232. %
  11233. For example, the following program returns \code{42} even though the
  11234. variable \code{x} goes out of scope when the function returns, prior
  11235. to reading the tuple element at index zero. (We study the compilation
  11236. of functions in chapter~\ref{ch:Lfun}.)
  11237. %
  11238. \begin{center}
  11239. \begin{minipage}{0.96\textwidth}
  11240. \begin{lstlisting}
  11241. def f():
  11242. x = 42, 43
  11243. return x
  11244. t = f()
  11245. print( t[0] )
  11246. \end{lstlisting}
  11247. \end{minipage}
  11248. \end{center}
  11249. \fi}
  11250. %
  11251. From the perspective of programmer-observable behavior, tuples live
  11252. forever. However, if they really lived forever then many long-running
  11253. programs would run out of memory. To solve this problem, the
  11254. language's runtime system performs automatic garbage collection.
  11255. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11256. \LangVec{} language.
  11257. %
  11258. \racket{We define the \code{vector}, \code{vector-ref},
  11259. \code{vector-set!}, and \code{vector-length} operations for
  11260. \LangVec{} in terms of the corresponding operations in Racket. One
  11261. subtle point is that the \code{vector-set!} operation returns the
  11262. \code{\#<void>} value.}
  11263. %
  11264. \python{We represent tuples with Python lists in the interpreter
  11265. because we need to write to them
  11266. (section~\ref{sec:expose-allocation}). (Python tuples are
  11267. immutable.) We define element access, the \code{is} operator, and
  11268. the \code{len} operator for \LangVec{} in terms of the corresponding
  11269. operations in Python.}
  11270. \begin{figure}[tbp]
  11271. \begin{tcolorbox}[colback=white]
  11272. {\if\edition\racketEd
  11273. \begin{lstlisting}
  11274. (define interp-Lvec-class
  11275. (class interp-Lwhile-class
  11276. (super-new)
  11277. (define/override (interp-op op)
  11278. (match op
  11279. ['eq? (lambda (v1 v2)
  11280. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11281. (and (boolean? v1) (boolean? v2))
  11282. (and (vector? v1) (vector? v2))
  11283. (and (void? v1) (void? v2)))
  11284. (eq? v1 v2)]))]
  11285. ['vector vector]
  11286. ['vector-length vector-length]
  11287. ['vector-ref vector-ref]
  11288. ['vector-set! vector-set!]
  11289. [else (super interp-op op)]
  11290. ))
  11291. (define/override ((interp-exp env) e)
  11292. (match e
  11293. [(HasType e t) ((interp-exp env) e)]
  11294. [else ((super interp-exp env) e)]
  11295. ))
  11296. ))
  11297. (define (interp-Lvec p)
  11298. (send (new interp-Lvec-class) interp-program p))
  11299. \end{lstlisting}
  11300. \fi}
  11301. %
  11302. {\if\edition\pythonEd
  11303. \begin{lstlisting}
  11304. class InterpLtup(InterpLwhile):
  11305. def interp_cmp(self, cmp):
  11306. match cmp:
  11307. case Is():
  11308. return lambda x, y: x is y
  11309. case _:
  11310. return super().interp_cmp(cmp)
  11311. def interp_exp(self, e, env):
  11312. match e:
  11313. case Tuple(es, Load()):
  11314. return tuple([self.interp_exp(e, env) for e in es])
  11315. case Subscript(tup, index, Load()):
  11316. t = self.interp_exp(tup, env)
  11317. n = self.interp_exp(index, env)
  11318. return t[n]
  11319. case _:
  11320. return super().interp_exp(e, env)
  11321. \end{lstlisting}
  11322. \fi}
  11323. \end{tcolorbox}
  11324. \caption{Interpreter for the \LangVec{} language.}
  11325. \label{fig:interp-Lvec}
  11326. \end{figure}
  11327. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11328. \LangVec{}.
  11329. %
  11330. The type of a tuple is a
  11331. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11332. type for each of its elements.
  11333. %
  11334. \racket{To create the s-expression for the \code{Vector} type, we use the
  11335. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11336. operator} \code{,@} to insert the list \code{t*} without its usual
  11337. start and end parentheses. \index{subject}{unquote-splicing}}
  11338. %
  11339. The type of accessing the ith element of a tuple is the ith element
  11340. type of the tuple's type, if there is one. If not, an error is
  11341. signaled. Note that the index \code{i} is required to be a constant
  11342. integer (and not, for example, a call to
  11343. \racket{\code{read}}\python{input\_int}) so that the type checker
  11344. can determine the element's type given the tuple type.
  11345. %
  11346. \racket{
  11347. Regarding writing an element to a tuple, the element's type must
  11348. be equal to the ith element type of the tuple's type.
  11349. The result type is \code{Void}.}
  11350. %% When allocating a tuple,
  11351. %% we need to know which elements of the tuple are themselves tuples for
  11352. %% the purposes of garbage collection. We can obtain this information
  11353. %% during type checking. The type checker shown in
  11354. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11355. %% expression; it also
  11356. %% %
  11357. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11358. %% where $T$ is the tuple's type.
  11359. %
  11360. %records the type of each tuple expression in a new field named \code{has\_type}.
  11361. \begin{figure}[tp]
  11362. \begin{tcolorbox}[colback=white]
  11363. {\if\edition\racketEd
  11364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11365. (define type-check-Lvec-class
  11366. (class type-check-Lif-class
  11367. (super-new)
  11368. (inherit check-type-equal?)
  11369. (define/override (type-check-exp env)
  11370. (lambda (e)
  11371. (define recur (type-check-exp env))
  11372. (match e
  11373. [(Prim 'vector es)
  11374. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11375. (define t `(Vector ,@t*))
  11376. (values (Prim 'vector e*) t)]
  11377. [(Prim 'vector-ref (list e1 (Int i)))
  11378. (define-values (e1^ t) (recur e1))
  11379. (match t
  11380. [`(Vector ,ts ...)
  11381. (unless (and (0 . <= . i) (i . < . (length ts)))
  11382. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11383. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11384. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11385. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11386. (define-values (e-vec t-vec) (recur e1))
  11387. (define-values (e-elt^ t-elt) (recur elt))
  11388. (match t-vec
  11389. [`(Vector ,ts ...)
  11390. (unless (and (0 . <= . i) (i . < . (length ts)))
  11391. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11392. (check-type-equal? (list-ref ts i) t-elt e)
  11393. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11394. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11395. [(Prim 'vector-length (list e))
  11396. (define-values (e^ t) (recur e))
  11397. (match t
  11398. [`(Vector ,ts ...)
  11399. (values (Prim 'vector-length (list e^)) 'Integer)]
  11400. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11401. [(Prim 'eq? (list arg1 arg2))
  11402. (define-values (e1 t1) (recur arg1))
  11403. (define-values (e2 t2) (recur arg2))
  11404. (match* (t1 t2)
  11405. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11406. [(other wise) (check-type-equal? t1 t2 e)])
  11407. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11408. [else ((super type-check-exp env) e)]
  11409. )))
  11410. ))
  11411. (define (type-check-Lvec p)
  11412. (send (new type-check-Lvec-class) type-check-program p))
  11413. \end{lstlisting}
  11414. \fi}
  11415. {\if\edition\pythonEd
  11416. \begin{lstlisting}
  11417. class TypeCheckLtup(TypeCheckLwhile):
  11418. def type_check_exp(self, e, env):
  11419. match e:
  11420. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11421. l = self.type_check_exp(left, env)
  11422. r = self.type_check_exp(right, env)
  11423. check_type_equal(l, r, e)
  11424. return bool
  11425. case Tuple(es, Load()):
  11426. ts = [self.type_check_exp(e, env) for e in es]
  11427. e.has_type = TupleType(ts)
  11428. return e.has_type
  11429. case Subscript(tup, Constant(i), Load()):
  11430. tup_ty = self.type_check_exp(tup, env)
  11431. i_ty = self.type_check_exp(Constant(i), env)
  11432. check_type_equal(i_ty, int, i)
  11433. match tup_ty:
  11434. case TupleType(ts):
  11435. return ts[i]
  11436. case _:
  11437. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11438. case _:
  11439. return super().type_check_exp(e, env)
  11440. \end{lstlisting}
  11441. \fi}
  11442. \end{tcolorbox}
  11443. \caption{Type checker for the \LangVec{} language.}
  11444. \label{fig:type-check-Lvec}
  11445. \end{figure}
  11446. \section{Garbage Collection}
  11447. \label{sec:GC}
  11448. Garbage collection is a runtime technique for reclaiming space on the
  11449. heap that will not be used in the future of the running program. We
  11450. use the term \emph{object}\index{subject}{object} to refer to any
  11451. value that is stored in the heap, which for now includes only
  11452. tuples.%
  11453. %
  11454. \footnote{The term \emph{object} as it is used in the context of
  11455. object-oriented programming has a more specific meaning than the
  11456. way in which we use the term here.}
  11457. %
  11458. Unfortunately, it is impossible to know precisely which objects will
  11459. be accessed in the future and which will not. Instead, garbage
  11460. collectors overapproximate the set of objects that will be accessed by
  11461. identifying which objects can possibly be accessed. The running
  11462. program can directly access objects that are in registers and on the
  11463. procedure call stack. It can also transitively access the elements of
  11464. tuples, starting with a tuple whose address is in a register or on the
  11465. procedure call stack. We define the \emph{root
  11466. set}\index{subject}{root set} to be all the tuple addresses that are
  11467. in registers or on the procedure call stack. We define the \emph{live
  11468. objects}\index{subject}{live objects} to be the objects that are
  11469. reachable from the root set. Garbage collectors reclaim the space that
  11470. is allocated to objects that are no longer live. That means that some
  11471. objects may not get reclaimed as soon as they could be, but at least
  11472. garbage collectors do not reclaim the space dedicated to objects that
  11473. will be accessed in the future! The programmer can influence which
  11474. objects get reclaimed by causing them to become unreachable.
  11475. So the goal of the garbage collector is twofold:
  11476. \begin{enumerate}
  11477. \item to preserve all the live objects, and
  11478. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11479. \end{enumerate}
  11480. \subsection{Two-Space Copying Collector}
  11481. Here we study a relatively simple algorithm for garbage collection
  11482. that is the basis of many state-of-the-art garbage
  11483. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11484. particular, we describe a two-space copying
  11485. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11486. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11487. collector} \index{subject}{two-space copying collector}
  11488. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11489. what happens in a two-space collector, showing two time steps, prior
  11490. to garbage collection (on the top) and after garbage collection (on
  11491. the bottom). In a two-space collector, the heap is divided into two
  11492. parts named the FromSpace\index{subject}{FromSpace} and the
  11493. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11494. FromSpace until there is not enough room for the next allocation
  11495. request. At that point, the garbage collector goes to work to make
  11496. room for the next allocation.
  11497. A copying collector makes more room by copying all the live objects
  11498. from the FromSpace into the ToSpace and then performs a sleight of
  11499. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11500. as the new ToSpace. In the example shown in
  11501. figure~\ref{fig:copying-collector}, the root set consists of three
  11502. pointers, one in a register and two on the stack. All the live
  11503. objects have been copied to the ToSpace (the right-hand side of
  11504. figure~\ref{fig:copying-collector}) in a way that preserves the
  11505. pointer relationships. For example, the pointer in the register still
  11506. points to a tuple that in turn points to two other tuples. There are
  11507. four tuples that are not reachable from the root set and therefore do
  11508. not get copied into the ToSpace.
  11509. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11510. created by a well-typed program in \LangVec{} because it contains a
  11511. cycle. However, creating cycles will be possible once we get to
  11512. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11513. to deal with cycles to begin with, so we will not need to revisit this
  11514. issue.
  11515. \begin{figure}[tbp]
  11516. \centering
  11517. \begin{tcolorbox}[colback=white]
  11518. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11519. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11520. \\[5ex]
  11521. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11522. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11523. \end{tcolorbox}
  11524. \caption{A copying collector in action.}
  11525. \label{fig:copying-collector}
  11526. \end{figure}
  11527. \subsection{Graph Copying via Cheney's Algorithm}
  11528. \label{sec:cheney}
  11529. \index{subject}{Cheney's algorithm}
  11530. Let us take a closer look at the copying of the live objects. The
  11531. allocated objects and pointers can be viewed as a graph, and we need to
  11532. copy the part of the graph that is reachable from the root set. To
  11533. make sure that we copy all the reachable vertices in the graph, we need
  11534. an exhaustive graph traversal algorithm, such as depth-first search or
  11535. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  11536. such algorithms take into account the possibility of cycles by marking
  11537. which vertices have already been visited, so to ensure termination
  11538. of the algorithm. These search algorithms also use a data structure
  11539. such as a stack or queue as a to-do list to keep track of the vertices
  11540. that need to be visited. We use breadth-first search and a trick
  11541. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  11542. and copying tuples into the ToSpace.
  11543. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11544. copy progresses. The queue is represented by a chunk of contiguous
  11545. memory at the beginning of the ToSpace, using two pointers to track
  11546. the front and the back of the queue, called the \emph{free pointer}
  11547. and the \emph{scan pointer}, respectively. The algorithm starts by
  11548. copying all tuples that are immediately reachable from the root set
  11549. into the ToSpace to form the initial queue. When we copy a tuple, we
  11550. mark the old tuple to indicate that it has been visited. We discuss
  11551. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11552. that any pointers inside the copied tuples in the queue still point
  11553. back to the FromSpace. Once the initial queue has been created, the
  11554. algorithm enters a loop in which it repeatedly processes the tuple at
  11555. the front of the queue and pops it off the queue. To process a tuple,
  11556. the algorithm copies all the objects that are directly reachable from it
  11557. to the ToSpace, placing them at the back of the queue. The algorithm
  11558. then updates the pointers in the popped tuple so that they point to the
  11559. newly copied objects.
  11560. \begin{figure}[tbp]
  11561. \centering
  11562. \begin{tcolorbox}[colback=white]
  11563. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11564. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11565. \end{tcolorbox}
  11566. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11567. \label{fig:cheney}
  11568. \end{figure}
  11569. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11570. tuple whose second element is $42$ to the back of the queue. The other
  11571. pointer goes to a tuple that has already been copied, so we do not
  11572. need to copy it again, but we do need to update the pointer to the new
  11573. location. This can be accomplished by storing a \emph{forwarding
  11574. pointer}\index{subject}{forwarding pointer} to the new location in the
  11575. old tuple, when we initially copied the tuple into the
  11576. ToSpace. This completes one step of the algorithm. The algorithm
  11577. continues in this way until the queue is empty; that is, when the scan
  11578. pointer catches up with the free pointer.
  11579. \subsection{Data Representation}
  11580. \label{sec:data-rep-gc}
  11581. The garbage collector places some requirements on the data
  11582. representations used by our compiler. First, the garbage collector
  11583. needs to distinguish between pointers and other kinds of data such as
  11584. integers. The following are several ways to accomplish this:
  11585. \begin{enumerate}
  11586. \item Attach a tag to each object that identifies what type of
  11587. object it is~\citep{McCarthy:1960dz}.
  11588. \item Store different types of objects in different
  11589. regions~\citep{Steele:1977ab}.
  11590. \item Use type information from the program to either (a) generate
  11591. type-specific code for collecting, or (b) generate tables that
  11592. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11593. \end{enumerate}
  11594. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11595. need to tag objects in any case, so option 1 is a natural choice for those
  11596. languages. However, \LangVec{} is a statically typed language, so it
  11597. would be unfortunate to require tags on every object, especially small
  11598. and pervasive objects like integers and Booleans. Option 3 is the
  11599. best-performing choice for statically typed languages, but it comes with
  11600. a relatively high implementation complexity. To keep this chapter
  11601. within a reasonable scope of complexity, we recommend a combination of options
  11602. 1 and 2, using separate strategies for the stack and the heap.
  11603. Regarding the stack, we recommend using a separate stack for pointers,
  11604. which we call the \emph{root stack}\index{subject}{root stack}
  11605. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11606. That is, when a local variable needs to be spilled and is of type
  11607. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11608. root stack instead of putting it on the procedure call
  11609. stack. Furthermore, we always spill tuple-typed variables if they are
  11610. live during a call to the collector, thereby ensuring that no pointers
  11611. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11612. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11613. contrasts it with the data layout using a root stack. The root stack
  11614. contains the two pointers from the regular stack and also the pointer
  11615. in the second register.
  11616. \begin{figure}[tbp]
  11617. \centering
  11618. \begin{tcolorbox}[colback=white]
  11619. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11620. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11621. \end{tcolorbox}
  11622. \caption{Maintaining a root stack to facilitate garbage collection.}
  11623. \label{fig:shadow-stack}
  11624. \end{figure}
  11625. The problem of distinguishing between pointers and other kinds of data
  11626. also arises inside each tuple on the heap. We solve this problem by
  11627. attaching a tag, an extra 64 bits, to each
  11628. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11629. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11630. Note that we have drawn the bits in a big-endian way, from right to left,
  11631. with bit location 0 (the least significant bit) on the far right,
  11632. which corresponds to the direction of the x86 shifting instructions
  11633. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11634. is dedicated to specifying which elements of the tuple are pointers,
  11635. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11636. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11637. data. The pointer mask starts at bit location 7. We limit tuples to a
  11638. maximum size of fifty elements, so we need 50 bits for the pointer
  11639. mask.%
  11640. %
  11641. \footnote{A production-quality compiler would handle
  11642. arbitrarily sized tuples and use a more complex approach.}
  11643. %
  11644. The tag also contains two other pieces of information. The length of
  11645. the tuple (number of elements) is stored in bits at locations 1 through
  11646. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11647. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11648. has not yet been copied. If the bit has value 0, then the entire tag
  11649. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11650. zero in any case, because our tuples are 8-byte aligned.)
  11651. \begin{figure}[tbp]
  11652. \centering
  11653. \begin{tcolorbox}[colback=white]
  11654. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11655. \end{tcolorbox}
  11656. \caption{Representation of tuples in the heap.}
  11657. \label{fig:tuple-rep}
  11658. \end{figure}
  11659. \subsection{Implementation of the Garbage Collector}
  11660. \label{sec:organize-gz}
  11661. \index{subject}{prelude}
  11662. An implementation of the copying collector is provided in the
  11663. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11664. interface to the garbage collector that is used by the compiler. The
  11665. \code{initialize} function creates the FromSpace, ToSpace, and root
  11666. stack and should be called in the prelude of the \code{main}
  11667. function. The arguments of \code{initialize} are the root stack size
  11668. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11669. good choice for both. The \code{initialize} function puts the address
  11670. of the beginning of the FromSpace into the global variable
  11671. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11672. the address that is one past the last element of the FromSpace. We use
  11673. half-open intervals to represent chunks of
  11674. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11675. points to the first element of the root stack.
  11676. As long as there is room left in the FromSpace, your generated code
  11677. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11678. %
  11679. The amount of room left in the FromSpace is the difference between the
  11680. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11681. function should be called when there is not enough room left in the
  11682. FromSpace for the next allocation. The \code{collect} function takes
  11683. a pointer to the current top of the root stack (one past the last item
  11684. that was pushed) and the number of bytes that need to be
  11685. allocated. The \code{collect} function performs the copying collection
  11686. and leaves the heap in a state such that there is enough room for the
  11687. next allocation.
  11688. \begin{figure}[tbp]
  11689. \begin{tcolorbox}[colback=white]
  11690. \begin{lstlisting}
  11691. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11692. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11693. int64_t* free_ptr;
  11694. int64_t* fromspace_begin;
  11695. int64_t* fromspace_end;
  11696. int64_t** rootstack_begin;
  11697. \end{lstlisting}
  11698. \end{tcolorbox}
  11699. \caption{The compiler's interface to the garbage collector.}
  11700. \label{fig:gc-header}
  11701. \end{figure}
  11702. %% \begin{exercise}
  11703. %% In the file \code{runtime.c} you will find the implementation of
  11704. %% \code{initialize} and a partial implementation of \code{collect}.
  11705. %% The \code{collect} function calls another function, \code{cheney},
  11706. %% to perform the actual copy, and that function is left to the reader
  11707. %% to implement. The following is the prototype for \code{cheney}.
  11708. %% \begin{lstlisting}
  11709. %% static void cheney(int64_t** rootstack_ptr);
  11710. %% \end{lstlisting}
  11711. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11712. %% rootstack (which is an array of pointers). The \code{cheney} function
  11713. %% also communicates with \code{collect} through the global
  11714. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11715. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11716. %% the ToSpace:
  11717. %% \begin{lstlisting}
  11718. %% static int64_t* tospace_begin;
  11719. %% static int64_t* tospace_end;
  11720. %% \end{lstlisting}
  11721. %% The job of the \code{cheney} function is to copy all the live
  11722. %% objects (reachable from the root stack) into the ToSpace, update
  11723. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11724. %% update the root stack so that it points to the objects in the
  11725. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11726. %% and ToSpace.
  11727. %% \end{exercise}
  11728. The introduction of garbage collection has a nontrivial impact on our
  11729. compiler passes. We introduce a new compiler pass named
  11730. \code{expose\_allocation} that elaborates the code for allocating
  11731. tuples. We also make significant changes to
  11732. \code{select\_instructions}, \code{build\_interference},
  11733. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11734. make minor changes in several more passes.
  11735. The following program serves as our running example. It creates
  11736. two tuples, one nested inside the other. Both tuples have length
  11737. one. The program accesses the element in the inner tuple.
  11738. % tests/vectors_test_17.rkt
  11739. {\if\edition\racketEd
  11740. \begin{lstlisting}
  11741. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11742. \end{lstlisting}
  11743. \fi}
  11744. {\if\edition\pythonEd
  11745. \begin{lstlisting}
  11746. print( ((42,),)[0][0] )
  11747. \end{lstlisting}
  11748. \fi}
  11749. %% {\if\edition\racketEd
  11750. %% \section{Shrink}
  11751. %% \label{sec:shrink-Lvec}
  11752. %% Recall that the \code{shrink} pass translates the primitives operators
  11753. %% into a smaller set of primitives.
  11754. %% %
  11755. %% This pass comes after type checking, and the type checker adds a
  11756. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11757. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11758. %% \fi}
  11759. \section{Expose Allocation}
  11760. \label{sec:expose-allocation}
  11761. The pass \code{expose\_allocation} lowers tuple creation into making a
  11762. conditional call to the collector followed by allocating the
  11763. appropriate amount of memory and initializing it. We choose to place
  11764. the \code{expose\_allocation} pass before
  11765. \code{remove\_complex\_operands} because it generates
  11766. code that contains complex operands.
  11767. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11768. that replaces tuple creation with new lower-level forms that we use in the
  11769. translation of tuple creation.
  11770. %
  11771. {\if\edition\racketEd
  11772. \[
  11773. \begin{array}{lcl}
  11774. \Exp &::=& \cdots
  11775. \MID (\key{collect} \,\itm{int})
  11776. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11777. \MID (\key{global-value} \,\itm{name})
  11778. \end{array}
  11779. \]
  11780. \fi}
  11781. {\if\edition\pythonEd
  11782. \[
  11783. \begin{array}{lcl}
  11784. \Exp &::=& \cdots\\
  11785. &\MID& \key{collect}(\itm{int})
  11786. \MID \key{allocate}(\itm{int},\itm{type})
  11787. \MID \key{global\_value}(\itm{name}) \\
  11788. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11789. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11790. \end{array}
  11791. \]
  11792. \fi}
  11793. %
  11794. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11795. make sure that there are $n$ bytes ready to be allocated. During
  11796. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11797. the \code{collect} function in \code{runtime.c}.
  11798. %
  11799. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11800. space at the front for the 64-bit tag), but the elements are not
  11801. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11802. of the tuple:
  11803. %
  11804. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11805. %
  11806. where $\Type_i$ is the type of the $i$th element.
  11807. %
  11808. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11809. variable, such as \code{free\_ptr}.
  11810. %
  11811. \python{The \code{begin} form is an expression that executes a
  11812. sequence of statements and then produces the value of the expression
  11813. at the end.}
  11814. \racket{
  11815. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11816. can be obtained by running the
  11817. \code{type-check-Lvec-has-type} type checker immediately before the
  11818. \code{expose\_allocation} pass. This version of the type checker
  11819. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11820. around each tuple creation. The concrete syntax
  11821. for \code{HasType} is \code{has-type}.}
  11822. The following shows the transformation of tuple creation into (1) a
  11823. sequence of temporary variable bindings for the initializing
  11824. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11825. \code{allocate}, and (4) the initialization of the tuple. The
  11826. \itm{len} placeholder refers to the length of the tuple, and
  11827. \itm{bytes} is the total number of bytes that need to be allocated for
  11828. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11829. %
  11830. \python{The \itm{type} needed for the second argument of the
  11831. \code{allocate} form can be obtained from the \code{has\_type} field
  11832. of the tuple AST node, which is stored there by running the type
  11833. checker for \LangVec{} immediately before this pass.}
  11834. %
  11835. \begin{center}
  11836. \begin{minipage}{\textwidth}
  11837. {\if\edition\racketEd
  11838. \begin{lstlisting}
  11839. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11840. |$\Longrightarrow$|
  11841. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11842. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11843. (global-value fromspace_end))
  11844. (void)
  11845. (collect |\itm{bytes}|))])
  11846. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11847. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11848. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11849. |$v$|) ... )))) ...)
  11850. \end{lstlisting}
  11851. \fi}
  11852. {\if\edition\pythonEd
  11853. \begin{lstlisting}
  11854. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11855. |$\Longrightarrow$|
  11856. begin:
  11857. |$x_0$| = |$e_0$|
  11858. |$\vdots$|
  11859. |$x_{n-1}$| = |$e_{n-1}$|
  11860. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11861. 0
  11862. else:
  11863. collect(|\itm{bytes}|)
  11864. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11865. |$v$|[0] = |$x_0$|
  11866. |$\vdots$|
  11867. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11868. |$v$|
  11869. \end{lstlisting}
  11870. \fi}
  11871. \end{minipage}
  11872. \end{center}
  11873. %
  11874. \noindent The sequencing of the initializing expressions
  11875. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11876. they may trigger garbage collection and we cannot have an allocated
  11877. but uninitialized tuple on the heap during a collection.
  11878. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11879. \code{expose\_allocation} pass on our running example.
  11880. \begin{figure}[tbp]
  11881. \begin{tcolorbox}[colback=white]
  11882. % tests/s2_17.rkt
  11883. {\if\edition\racketEd
  11884. \begin{lstlisting}
  11885. (vector-ref
  11886. (vector-ref
  11887. (let ([vecinit6
  11888. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11889. (global-value fromspace_end))
  11890. (void)
  11891. (collect 16))])
  11892. (let ([alloc2 (allocate 1 (Vector Integer))])
  11893. (let ([_3 (vector-set! alloc2 0 42)])
  11894. alloc2)))])
  11895. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11896. (global-value fromspace_end))
  11897. (void)
  11898. (collect 16))])
  11899. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11900. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11901. alloc5))))
  11902. 0)
  11903. 0)
  11904. \end{lstlisting}
  11905. \fi}
  11906. {\if\edition\pythonEd
  11907. \begin{lstlisting}
  11908. print( |$T_1$|[0][0] )
  11909. \end{lstlisting}
  11910. where $T_1$ is
  11911. \begin{lstlisting}
  11912. begin:
  11913. tmp.1 = |$T_2$|
  11914. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11915. 0
  11916. else:
  11917. collect(16)
  11918. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11919. tmp.2[0] = tmp.1
  11920. tmp.2
  11921. \end{lstlisting}
  11922. and $T_2$ is
  11923. \begin{lstlisting}
  11924. begin:
  11925. tmp.3 = 42
  11926. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11927. 0
  11928. else:
  11929. collect(16)
  11930. tmp.4 = allocate(1, TupleType([int]))
  11931. tmp.4[0] = tmp.3
  11932. tmp.4
  11933. \end{lstlisting}
  11934. \fi}
  11935. \end{tcolorbox}
  11936. \caption{Output of the \code{expose\_allocation} pass.}
  11937. \label{fig:expose-alloc-output}
  11938. \end{figure}
  11939. \section{Remove Complex Operands}
  11940. \label{sec:remove-complex-opera-Lvec}
  11941. {\if\edition\racketEd
  11942. %
  11943. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11944. should be treated as complex operands.
  11945. %
  11946. \fi}
  11947. %
  11948. {\if\edition\pythonEd
  11949. %
  11950. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11951. and tuple access should be treated as complex operands. The
  11952. sub-expressions of tuple access must be atomic.
  11953. %
  11954. \fi}
  11955. %% A new case for
  11956. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11957. %% handled carefully to prevent the \code{Prim} node from being separated
  11958. %% from its enclosing \code{HasType}.
  11959. Figure~\ref{fig:Lvec-anf-syntax}
  11960. shows the grammar for the output language \LangAllocANF{} of this
  11961. pass, which is \LangAlloc{} in monadic normal form.
  11962. \newcommand{\LtupMonadASTRacket}{
  11963. \begin{array}{rcl}
  11964. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11965. \MID \GLOBALVALUE{\Var}
  11966. \end{array}
  11967. }
  11968. \newcommand{\LtupMonadASTPython}{
  11969. \begin{array}{rcl}
  11970. \Exp &::=& \GET{\Atm}{\Atm} \\
  11971. &\MID& \LEN{\Atm}\\
  11972. &\MID& \ALLOCATE{\Int}{\Type}
  11973. \MID \GLOBALVALUE{\Var} \\
  11974. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11975. &\MID& \COLLECT{\Int}
  11976. \end{array}
  11977. }
  11978. \begin{figure}[tp]
  11979. \centering
  11980. \begin{tcolorbox}[colback=white]
  11981. \small
  11982. {\if\edition\racketEd
  11983. \[
  11984. \begin{array}{l}
  11985. \gray{\LvarMonadASTRacket} \\ \hline
  11986. \gray{\LifMonadASTRacket} \\ \hline
  11987. \gray{\LwhileMonadASTRacket} \\ \hline
  11988. \LtupMonadASTRacket \\
  11989. \begin{array}{rcl}
  11990. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11991. \end{array}
  11992. \end{array}
  11993. \]
  11994. \fi}
  11995. {\if\edition\pythonEd
  11996. \[
  11997. \begin{array}{l}
  11998. \gray{\LvarMonadASTPython} \\ \hline
  11999. \gray{\LifMonadASTPython} \\ \hline
  12000. \gray{\LwhileMonadASTPython} \\ \hline
  12001. \LtupMonadASTPython \\
  12002. \begin{array}{rcl}
  12003. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12004. \end{array}
  12005. \end{array}
  12006. \]
  12007. \fi}
  12008. \end{tcolorbox}
  12009. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12010. \label{fig:Lvec-anf-syntax}
  12011. \end{figure}
  12012. \section{Explicate Control and the \LangCVec{} language}
  12013. \label{sec:explicate-control-r3}
  12014. \newcommand{\CtupASTRacket}{
  12015. \begin{array}{lcl}
  12016. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12017. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12018. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12019. &\MID& \VECLEN{\Atm} \\
  12020. &\MID& \GLOBALVALUE{\Var} \\
  12021. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12022. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12023. \end{array}
  12024. }
  12025. \newcommand{\CtupASTPython}{
  12026. \begin{array}{lcl}
  12027. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12028. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12029. \Stmt &::=& \COLLECT{\Int} \\
  12030. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12031. \end{array}
  12032. }
  12033. \begin{figure}[tp]
  12034. \begin{tcolorbox}[colback=white]
  12035. \small
  12036. {\if\edition\racketEd
  12037. \[
  12038. \begin{array}{l}
  12039. \gray{\CvarASTRacket} \\ \hline
  12040. \gray{\CifASTRacket} \\ \hline
  12041. \gray{\CloopASTRacket} \\ \hline
  12042. \CtupASTRacket \\
  12043. \begin{array}{lcl}
  12044. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12045. \end{array}
  12046. \end{array}
  12047. \]
  12048. \fi}
  12049. {\if\edition\pythonEd
  12050. \[
  12051. \begin{array}{l}
  12052. \gray{\CifASTPython} \\ \hline
  12053. \CtupASTPython \\
  12054. \begin{array}{lcl}
  12055. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12056. \end{array}
  12057. \end{array}
  12058. \]
  12059. \fi}
  12060. \end{tcolorbox}
  12061. \caption{The abstract syntax of \LangCVec{}, extending
  12062. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12063. (figure~\ref{fig:c1-syntax})}.}
  12064. \label{fig:c2-syntax}
  12065. \end{figure}
  12066. The output of \code{explicate\_control} is a program in the
  12067. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12068. shows the definition of the abstract syntax.
  12069. %
  12070. %% \racket{(The concrete syntax is defined in
  12071. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12072. %
  12073. The new expressions of \LangCVec{} include \key{allocate},
  12074. %
  12075. \racket{\key{vector-ref}, and \key{vector-set!},}
  12076. %
  12077. \python{accessing tuple elements,}
  12078. %
  12079. and \key{global\_value}.
  12080. %
  12081. \python{\LangCVec{} also includes the \code{collect} statement and
  12082. assignment to a tuple element.}
  12083. %
  12084. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12085. %
  12086. The \code{explicate\_control} pass can treat these new forms much like
  12087. the other forms that we've already encountered. The output of the
  12088. \code{explicate\_control} pass on the running example is shown on the
  12089. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12090. section.
  12091. \section{Select Instructions and the \LangXGlobal{} Language}
  12092. \label{sec:select-instructions-gc}
  12093. \index{subject}{instruction selection}
  12094. %% void (rep as zero)
  12095. %% allocate
  12096. %% collect (callq collect)
  12097. %% vector-ref
  12098. %% vector-set!
  12099. %% vector-length
  12100. %% global (postpone)
  12101. In this pass we generate x86 code for most of the new operations that
  12102. were needed to compile tuples, including \code{Allocate},
  12103. \code{Collect}, and accessing tuple elements.
  12104. %
  12105. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12106. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12107. \ref{fig:x86-2}). \index{subject}{x86}
  12108. The tuple read and write forms translate into \code{movq}
  12109. instructions. (The $+1$ in the offset serves to move past the tag at the
  12110. beginning of the tuple representation.)
  12111. %
  12112. \begin{center}
  12113. \begin{minipage}{\textwidth}
  12114. {\if\edition\racketEd
  12115. \begin{lstlisting}
  12116. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12117. |$\Longrightarrow$|
  12118. movq |$\itm{tup}'$|, %r11
  12119. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12120. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12121. |$\Longrightarrow$|
  12122. movq |$\itm{tup}'$|, %r11
  12123. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12124. movq $0, |$\itm{lhs'}$|
  12125. \end{lstlisting}
  12126. \fi}
  12127. {\if\edition\pythonEd
  12128. \begin{lstlisting}
  12129. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12130. |$\Longrightarrow$|
  12131. movq |$\itm{tup}'$|, %r11
  12132. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12133. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12134. |$\Longrightarrow$|
  12135. movq |$\itm{tup}'$|, %r11
  12136. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12137. \end{lstlisting}
  12138. \fi}
  12139. \end{minipage}
  12140. \end{center}
  12141. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12142. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12143. are obtained by translating from \LangCVec{} to x86.
  12144. %
  12145. The move of $\itm{tup}'$ to
  12146. register \code{r11} ensures that offset expression
  12147. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12148. removing \code{r11} from consideration by the register allocating.
  12149. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12150. \code{rax}. Then the generated code for tuple assignment would be
  12151. \begin{lstlisting}
  12152. movq |$\itm{tup}'$|, %rax
  12153. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12154. \end{lstlisting}
  12155. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12156. \code{patch\_instructions} would insert a move through \code{rax}
  12157. as follows:
  12158. \begin{lstlisting}
  12159. movq |$\itm{tup}'$|, %rax
  12160. movq |$\itm{rhs}'$|, %rax
  12161. movq %rax, |$8(n+1)$|(%rax)
  12162. \end{lstlisting}
  12163. However, this sequence of instructions does not work, because we're
  12164. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12165. $\itm{rhs}'$) at the same time!
  12166. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12167. be translated into a sequence of instructions that read the tag of the
  12168. tuple and extract the 6 bits that represent the tuple length, which
  12169. are the bits starting at index 1 and going up to and including bit 6.
  12170. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12171. (shift right) can be used to accomplish this.
  12172. We compile the \code{allocate} form to operations on the
  12173. \code{free\_ptr}, as shown next. This approach is called
  12174. \emph{inline allocation} because it implements allocation without a
  12175. function call by simply incrementing the allocation pointer. It is much
  12176. more efficient than calling a function for each allocation. The
  12177. address in the \code{free\_ptr} is the next free address in the
  12178. FromSpace, so we copy it into \code{r11} and then move it forward by
  12179. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12180. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12181. the tag. We then initialize the \itm{tag} and finally copy the
  12182. address in \code{r11} to the left-hand side. Refer to
  12183. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12184. %
  12185. \racket{We recommend using the Racket operations
  12186. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12187. during compilation.}
  12188. %
  12189. \python{We recommend using the bitwise-or operator \code{|} and the
  12190. shift-left operator \code{<<} to compute the tag during
  12191. compilation.}
  12192. %
  12193. The type annotation in the \code{allocate} form is used to determine
  12194. the pointer mask region of the tag.
  12195. %
  12196. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12197. address of the \code{free\_ptr} global variable using a special
  12198. instruction-pointer-relative addressing mode of the x86-64 processor.
  12199. In particular, the assembler computes the distance $d$ between the
  12200. address of \code{free\_ptr} and where the \code{rip} would be at that
  12201. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12202. \code{$d$(\%rip)}, which at runtime will compute the address of
  12203. \code{free\_ptr}.
  12204. %
  12205. {\if\edition\racketEd
  12206. \begin{lstlisting}
  12207. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12208. |$\Longrightarrow$|
  12209. movq free_ptr(%rip), %r11
  12210. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12211. movq $|$\itm{tag}$|, 0(%r11)
  12212. movq %r11, |$\itm{lhs}'$|
  12213. \end{lstlisting}
  12214. \fi}
  12215. {\if\edition\pythonEd
  12216. \begin{lstlisting}
  12217. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12218. |$\Longrightarrow$|
  12219. movq free_ptr(%rip), %r11
  12220. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12221. movq $|$\itm{tag}$|, 0(%r11)
  12222. movq %r11, |$\itm{lhs}'$|
  12223. \end{lstlisting}
  12224. \fi}
  12225. %
  12226. The \code{collect} form is compiled to a call to the \code{collect}
  12227. function in the runtime. The arguments to \code{collect} are (1) the
  12228. top of the root stack, and (2) the number of bytes that need to be
  12229. allocated. We use another dedicated register, \code{r15}, to store
  12230. the pointer to the top of the root stack. Therefore \code{r15} is not
  12231. available for use by the register allocator.
  12232. %
  12233. {\if\edition\racketEd
  12234. \begin{lstlisting}
  12235. (collect |$\itm{bytes}$|)
  12236. |$\Longrightarrow$|
  12237. movq %r15, %rdi
  12238. movq $|\itm{bytes}|, %rsi
  12239. callq collect
  12240. \end{lstlisting}
  12241. \fi}
  12242. {\if\edition\pythonEd
  12243. \begin{lstlisting}
  12244. collect(|$\itm{bytes}$|)
  12245. |$\Longrightarrow$|
  12246. movq %r15, %rdi
  12247. movq $|\itm{bytes}|, %rsi
  12248. callq collect
  12249. \end{lstlisting}
  12250. \fi}
  12251. \newcommand{\GrammarXGlobal}{
  12252. \begin{array}{lcl}
  12253. \Arg &::=& \itm{label} \key{(\%rip)}
  12254. \end{array}
  12255. }
  12256. \newcommand{\ASTXGlobalRacket}{
  12257. \begin{array}{lcl}
  12258. \Arg &::=& \GLOBAL{\itm{label}}
  12259. \end{array}
  12260. }
  12261. \begin{figure}[tp]
  12262. \begin{tcolorbox}[colback=white]
  12263. \[
  12264. \begin{array}{l}
  12265. \gray{\GrammarXInt} \\ \hline
  12266. \gray{\GrammarXIf} \\ \hline
  12267. \GrammarXGlobal \\
  12268. \begin{array}{lcl}
  12269. \LangXGlobalM{} &::= & \key{.globl main} \\
  12270. & & \key{main:} \; \Instr^{*}
  12271. \end{array}
  12272. \end{array}
  12273. \]
  12274. \end{tcolorbox}
  12275. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12276. \label{fig:x86-2-concrete}
  12277. \end{figure}
  12278. \begin{figure}[tp]
  12279. \begin{tcolorbox}[colback=white]
  12280. \small
  12281. \[
  12282. \begin{array}{l}
  12283. \gray{\ASTXIntRacket} \\ \hline
  12284. \gray{\ASTXIfRacket} \\ \hline
  12285. \ASTXGlobalRacket \\
  12286. \begin{array}{lcl}
  12287. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12288. \end{array}
  12289. \end{array}
  12290. \]
  12291. \end{tcolorbox}
  12292. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12293. \label{fig:x86-2}
  12294. \end{figure}
  12295. The definitions of the concrete and abstract syntax of the
  12296. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12297. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12298. of global variables.
  12299. %
  12300. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12301. \code{select\_instructions} pass on the running example.
  12302. \begin{figure}[tbp]
  12303. \centering
  12304. \begin{tcolorbox}[colback=white]
  12305. % tests/s2_17.rkt
  12306. \begin{tabular}{lll}
  12307. \begin{minipage}{0.5\textwidth}
  12308. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12309. start:
  12310. tmp9 = (global-value free_ptr);
  12311. tmp0 = (+ tmp9 16);
  12312. tmp1 = (global-value fromspace_end);
  12313. if (< tmp0 tmp1)
  12314. goto block0;
  12315. else
  12316. goto block1;
  12317. block0:
  12318. _4 = (void);
  12319. goto block9;
  12320. block1:
  12321. (collect 16)
  12322. goto block9;
  12323. block9:
  12324. alloc2 = (allocate 1 (Vector Integer));
  12325. _3 = (vector-set! alloc2 0 42);
  12326. vecinit6 = alloc2;
  12327. tmp2 = (global-value free_ptr);
  12328. tmp3 = (+ tmp2 16);
  12329. tmp4 = (global-value fromspace_end);
  12330. if (< tmp3 tmp4)
  12331. goto block7;
  12332. else
  12333. goto block8;
  12334. block7:
  12335. _8 = (void);
  12336. goto block6;
  12337. block8:
  12338. (collect 16)
  12339. goto block6;
  12340. block6:
  12341. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12342. _7 = (vector-set! alloc5 0 vecinit6);
  12343. tmp5 = (vector-ref alloc5 0);
  12344. return (vector-ref tmp5 0);
  12345. \end{lstlisting}
  12346. \end{minipage}
  12347. &$\Rightarrow$&
  12348. \begin{minipage}{0.4\textwidth}
  12349. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12350. start:
  12351. movq free_ptr(%rip), tmp9
  12352. movq tmp9, tmp0
  12353. addq $16, tmp0
  12354. movq fromspace_end(%rip), tmp1
  12355. cmpq tmp1, tmp0
  12356. jl block0
  12357. jmp block1
  12358. block0:
  12359. movq $0, _4
  12360. jmp block9
  12361. block1:
  12362. movq %r15, %rdi
  12363. movq $16, %rsi
  12364. callq collect
  12365. jmp block9
  12366. block9:
  12367. movq free_ptr(%rip), %r11
  12368. addq $16, free_ptr(%rip)
  12369. movq $3, 0(%r11)
  12370. movq %r11, alloc2
  12371. movq alloc2, %r11
  12372. movq $42, 8(%r11)
  12373. movq $0, _3
  12374. movq alloc2, vecinit6
  12375. movq free_ptr(%rip), tmp2
  12376. movq tmp2, tmp3
  12377. addq $16, tmp3
  12378. movq fromspace_end(%rip), tmp4
  12379. cmpq tmp4, tmp3
  12380. jl block7
  12381. jmp block8
  12382. block7:
  12383. movq $0, _8
  12384. jmp block6
  12385. block8:
  12386. movq %r15, %rdi
  12387. movq $16, %rsi
  12388. callq collect
  12389. jmp block6
  12390. block6:
  12391. movq free_ptr(%rip), %r11
  12392. addq $16, free_ptr(%rip)
  12393. movq $131, 0(%r11)
  12394. movq %r11, alloc5
  12395. movq alloc5, %r11
  12396. movq vecinit6, 8(%r11)
  12397. movq $0, _7
  12398. movq alloc5, %r11
  12399. movq 8(%r11), tmp5
  12400. movq tmp5, %r11
  12401. movq 8(%r11), %rax
  12402. jmp conclusion
  12403. \end{lstlisting}
  12404. \end{minipage}
  12405. \end{tabular}
  12406. \end{tcolorbox}
  12407. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12408. \code{select\_instructions} (\emph{right}) passes on the running
  12409. example.}
  12410. \label{fig:select-instr-output-gc}
  12411. \end{figure}
  12412. \clearpage
  12413. \section{Register Allocation}
  12414. \label{sec:reg-alloc-gc}
  12415. \index{subject}{register allocation}
  12416. As discussed previously in this chapter, the garbage collector needs to
  12417. access all the pointers in the root set, that is, all variables that
  12418. are tuples. It will be the responsibility of the register allocator
  12419. to make sure that
  12420. \begin{enumerate}
  12421. \item the root stack is used for spilling tuple-typed variables, and
  12422. \item if a tuple-typed variable is live during a call to the
  12423. collector, it must be spilled to ensure that it is visible to the
  12424. collector.
  12425. \end{enumerate}
  12426. The latter responsibility can be handled during construction of the
  12427. interference graph, by adding interference edges between the call-live
  12428. tuple-typed variables and all the callee-saved registers. (They
  12429. already interfere with the caller-saved registers.)
  12430. %
  12431. \racket{The type information for variables is in the \code{Program}
  12432. form, so we recommend adding another parameter to the
  12433. \code{build\_interference} function to communicate this alist.}
  12434. %
  12435. \python{The type information for variables is generated by the type
  12436. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12437. the \code{CProgram} AST mode. You'll need to propagate that
  12438. information so that it is available in this pass.}
  12439. The spilling of tuple-typed variables to the root stack can be handled
  12440. after graph coloring, in choosing how to assign the colors
  12441. (integers) to registers and stack locations. The
  12442. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12443. changes to also record the number of spills to the root stack.
  12444. % build-interference
  12445. %
  12446. % callq
  12447. % extra parameter for var->type assoc. list
  12448. % update 'program' and 'if'
  12449. % allocate-registers
  12450. % allocate spilled vectors to the rootstack
  12451. % don't change color-graph
  12452. % TODO:
  12453. %\section{Patch Instructions}
  12454. %[mention that global variables are memory references]
  12455. \section{Prelude and Conclusion}
  12456. \label{sec:print-x86-gc}
  12457. \label{sec:prelude-conclusion-x86-gc}
  12458. \index{subject}{prelude}\index{subject}{conclusion}
  12459. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12460. \code{prelude\_and\_conclusion} pass on the running example. In the
  12461. prelude of the \code{main} function, we allocate space
  12462. on the root stack to make room for the spills of tuple-typed
  12463. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12464. taking care that the root stack grows up instead of down. For the
  12465. running example, there was just one spill, so we increment \code{r15}
  12466. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12467. One issue that deserves special care is that there may be a call to
  12468. \code{collect} prior to the initializing assignments for all the
  12469. variables in the root stack. We do not want the garbage collector to
  12470. mistakenly determine that some uninitialized variable is a pointer that
  12471. needs to be followed. Thus, we zero out all locations on the root
  12472. stack in the prelude of \code{main}. In
  12473. figure~\ref{fig:print-x86-output-gc}, the instruction
  12474. %
  12475. \lstinline{movq $0, 0(%r15)}
  12476. %
  12477. is sufficient to accomplish this task because there is only one spill.
  12478. In general, we have to clear as many words as there are spills of
  12479. tuple-typed variables. The garbage collector tests each root to see
  12480. if it is null prior to dereferencing it.
  12481. \begin{figure}[htbp]
  12482. % TODO: Python Version -Jeremy
  12483. \begin{tcolorbox}[colback=white]
  12484. \begin{minipage}[t]{0.5\textwidth}
  12485. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12486. .globl main
  12487. main:
  12488. pushq %rbp
  12489. movq %rsp, %rbp
  12490. subq $0, %rsp
  12491. movq $65536, %rdi
  12492. movq $65536, %rsi
  12493. callq initialize
  12494. movq rootstack_begin(%rip), %r15
  12495. movq $0, 0(%r15)
  12496. addq $8, %r15
  12497. jmp start
  12498. conclusion:
  12499. subq $8, %r15
  12500. addq $0, %rsp
  12501. popq %rbp
  12502. retq
  12503. \end{lstlisting}
  12504. \end{minipage}
  12505. \end{tcolorbox}
  12506. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12507. \label{fig:print-x86-output-gc}
  12508. \end{figure}
  12509. \begin{figure}[tbp]
  12510. \begin{tcolorbox}[colback=white]
  12511. {\if\edition\racketEd
  12512. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12513. \node (Lvec) at (0,2) {\large \LangVec{}};
  12514. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12515. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12516. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12517. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12518. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12519. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12520. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12521. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12522. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12523. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12524. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12525. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12526. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12527. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12528. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12529. \path[->,bend left=15] (Lvec-4) edge [right] node
  12530. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12531. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12532. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12533. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12534. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12535. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12536. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12537. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12538. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12539. \end{tikzpicture}
  12540. \fi}
  12541. {\if\edition\pythonEd
  12542. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12543. \node (Lvec) at (0,2) {\large \LangVec{}};
  12544. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12545. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12546. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12547. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12548. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12549. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12550. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12551. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12552. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12553. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12554. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12555. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12556. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12557. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12558. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12559. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12560. \end{tikzpicture}
  12561. \fi}
  12562. \end{tcolorbox}
  12563. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12564. \label{fig:Lvec-passes}
  12565. \end{figure}
  12566. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12567. for the compilation of \LangVec{}.
  12568. \clearpage
  12569. {\if\edition\racketEd
  12570. \section{Challenge: Simple Structures}
  12571. \label{sec:simple-structures}
  12572. \index{subject}{struct}
  12573. \index{subject}{structure}
  12574. The language \LangStruct{} extends \LangVec{} with support for simple
  12575. structures. The definition of its concrete syntax is shown in
  12576. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12577. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12578. in Typed Racket is a user-defined data type that contains named fields
  12579. and that is heap allocated, similarly to a vector. The following is an
  12580. example of a structure definition, in this case the definition of a
  12581. \code{point} type:
  12582. \begin{lstlisting}
  12583. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12584. \end{lstlisting}
  12585. \newcommand{\LstructGrammarRacket}{
  12586. \begin{array}{lcl}
  12587. \Type &::=& \Var \\
  12588. \Exp &::=& (\Var\;\Exp \ldots)\\
  12589. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12590. \end{array}
  12591. }
  12592. \newcommand{\LstructASTRacket}{
  12593. \begin{array}{lcl}
  12594. \Type &::=& \VAR{\Var} \\
  12595. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12596. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12597. \end{array}
  12598. }
  12599. \begin{figure}[tbp]
  12600. \centering
  12601. \begin{tcolorbox}[colback=white]
  12602. \[
  12603. \begin{array}{l}
  12604. \gray{\LintGrammarRacket{}} \\ \hline
  12605. \gray{\LvarGrammarRacket{}} \\ \hline
  12606. \gray{\LifGrammarRacket{}} \\ \hline
  12607. \gray{\LwhileGrammarRacket} \\ \hline
  12608. \gray{\LtupGrammarRacket} \\ \hline
  12609. \LstructGrammarRacket \\
  12610. \begin{array}{lcl}
  12611. \LangStruct{} &::=& \Def \ldots \; \Exp
  12612. \end{array}
  12613. \end{array}
  12614. \]
  12615. \end{tcolorbox}
  12616. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12617. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12618. \label{fig:Lstruct-concrete-syntax}
  12619. \end{figure}
  12620. \begin{figure}[tbp]
  12621. \centering
  12622. \begin{tcolorbox}[colback=white]
  12623. \small
  12624. \[
  12625. \begin{array}{l}
  12626. \gray{\LintASTRacket{}} \\ \hline
  12627. \gray{\LvarASTRacket{}} \\ \hline
  12628. \gray{\LifASTRacket{}} \\ \hline
  12629. \gray{\LwhileASTRacket} \\ \hline
  12630. \gray{\LtupASTRacket} \\ \hline
  12631. \LstructASTRacket \\
  12632. \begin{array}{lcl}
  12633. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12634. \end{array}
  12635. \end{array}
  12636. \]
  12637. \end{tcolorbox}
  12638. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12639. (figure~\ref{fig:Lvec-syntax}).}
  12640. \label{fig:Lstruct-syntax}
  12641. \end{figure}
  12642. An instance of a structure is created using function-call syntax, with
  12643. the name of the structure in the function position, as follows:
  12644. \begin{lstlisting}
  12645. (point 7 12)
  12646. \end{lstlisting}
  12647. Function-call syntax is also used to read a field of a structure. The
  12648. function name is formed by the structure name, a dash, and the field
  12649. name. The following example uses \code{point-x} and \code{point-y} to
  12650. access the \code{x} and \code{y} fields of two point instances:
  12651. \begin{center}
  12652. \begin{lstlisting}
  12653. (let ([pt1 (point 7 12)])
  12654. (let ([pt2 (point 4 3)])
  12655. (+ (- (point-x pt1) (point-x pt2))
  12656. (- (point-y pt1) (point-y pt2)))))
  12657. \end{lstlisting}
  12658. \end{center}
  12659. Similarly, to write to a field of a structure, use its set function,
  12660. whose name starts with \code{set-}, followed by the structure name,
  12661. then a dash, then the field name, and finally with an exclamation
  12662. mark. The following example uses \code{set-point-x!} to change the
  12663. \code{x} field from \code{7} to \code{42}:
  12664. \begin{center}
  12665. \begin{lstlisting}
  12666. (let ([pt (point 7 12)])
  12667. (let ([_ (set-point-x! pt 42)])
  12668. (point-x pt)))
  12669. \end{lstlisting}
  12670. \end{center}
  12671. \begin{exercise}\normalfont\normalsize
  12672. Create a type checker for \LangStruct{} by extending the type
  12673. checker for \LangVec{}. Extend your compiler with support for simple
  12674. structures, compiling \LangStruct{} to x86 assembly code. Create
  12675. five new test cases that use structures and, test your compiler.
  12676. \end{exercise}
  12677. % TODO: create an interpreter for L_struct
  12678. \clearpage
  12679. \fi}
  12680. \section{Challenge: Arrays}
  12681. \label{sec:arrays}
  12682. % TODO mention trapped-error
  12683. In this chapter we have studied tuples, that is, heterogeneous
  12684. sequences of elements whose length is determined at compile time. This
  12685. challenge is also about sequences, but this time the length is
  12686. determined at runtime and all the elements have the same type (they
  12687. are homogeneous). We use the term \emph{array} for this latter kind of
  12688. sequence.
  12689. %
  12690. \racket{
  12691. The Racket language does not distinguish between tuples and arrays;
  12692. they are both represented by vectors. However, Typed Racket
  12693. distinguishes between tuples and arrays: the \code{Vector} type is for
  12694. tuples, and the \code{Vectorof} type is for arrays.}
  12695. \python{
  12696. Arrays correspond to the \code{list} type in Python language.
  12697. }
  12698. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12699. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12700. presents the definition of the abstract syntax, extending \LangVec{}
  12701. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12702. %
  12703. \racket{\code{make-vector} primitive operator for creating an array,
  12704. whose arguments are the length of the array and an initial value for
  12705. all the elements in the array.}
  12706. \python{bracket notation for creating an array literal.}
  12707. \racket{
  12708. The \code{vector-length},
  12709. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12710. for tuples become overloaded for use with arrays.}
  12711. \python{
  12712. The subscript operator becomes overloaded for use with arrays and tuples
  12713. and now may appear on the left-hand side of an assignment.
  12714. Note that the index of the subscript, when applied to an array, may be an
  12715. arbitrary expression and not just a constant integer.
  12716. The \code{len} function is also applicable to arrays.
  12717. }
  12718. %
  12719. We include integer multiplication in \LangArray{}, because it is
  12720. useful in many examples involving arrays such as computing the
  12721. inner product of two arrays (figure~\ref{fig:inner_product}).
  12722. \newcommand{\LarrayGrammarRacket}{
  12723. \begin{array}{lcl}
  12724. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12725. \Exp &::=& \CMUL{\Exp}{\Exp}
  12726. \MID \CMAKEVEC{\Exp}{\Exp}
  12727. \end{array}
  12728. }
  12729. \newcommand{\LarrayASTRacket}{
  12730. \begin{array}{lcl}
  12731. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12732. \Exp &::=& \MUL{\Exp}{\Exp}
  12733. \MID \MAKEVEC{\Exp}{\Exp}
  12734. \end{array}
  12735. }
  12736. \newcommand{\LarrayGrammarPython}{
  12737. \begin{array}{lcl}
  12738. \Type &::=& \key{list}\LS\Type\RS \\
  12739. \Exp &::=& \CMUL{\Exp}{\Exp}
  12740. \MID \CGET{\Exp}{\Exp}
  12741. \MID \LS \Exp \code{,} \ldots \RS \\
  12742. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12743. \end{array}
  12744. }
  12745. \newcommand{\LarrayASTPython}{
  12746. \begin{array}{lcl}
  12747. \Type &::=& \key{ListType}\LP\Type\RP \\
  12748. \Exp &::=& \MUL{\Exp}{\Exp}
  12749. \MID \GET{\Exp}{\Exp} \\
  12750. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12751. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12752. \end{array}
  12753. }
  12754. \begin{figure}[tp]
  12755. \centering
  12756. \begin{tcolorbox}[colback=white]
  12757. \small
  12758. {\if\edition\racketEd
  12759. \[
  12760. \begin{array}{l}
  12761. \gray{\LintGrammarRacket{}} \\ \hline
  12762. \gray{\LvarGrammarRacket{}} \\ \hline
  12763. \gray{\LifGrammarRacket{}} \\ \hline
  12764. \gray{\LwhileGrammarRacket} \\ \hline
  12765. \gray{\LtupGrammarRacket} \\ \hline
  12766. \LarrayGrammarRacket \\
  12767. \begin{array}{lcl}
  12768. \LangArray{} &::=& \Exp
  12769. \end{array}
  12770. \end{array}
  12771. \]
  12772. \fi}
  12773. {\if\edition\pythonEd
  12774. \[
  12775. \begin{array}{l}
  12776. \gray{\LintGrammarPython{}} \\ \hline
  12777. \gray{\LvarGrammarPython{}} \\ \hline
  12778. \gray{\LifGrammarPython{}} \\ \hline
  12779. \gray{\LwhileGrammarPython} \\ \hline
  12780. \gray{\LtupGrammarPython} \\ \hline
  12781. \LarrayGrammarPython \\
  12782. \begin{array}{rcl}
  12783. \LangArrayM{} &::=& \Stmt^{*}
  12784. \end{array}
  12785. \end{array}
  12786. \]
  12787. \fi}
  12788. \end{tcolorbox}
  12789. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12790. \label{fig:Lvecof-concrete-syntax}
  12791. \end{figure}
  12792. \begin{figure}[tp]
  12793. \centering
  12794. \begin{tcolorbox}[colback=white]
  12795. \small
  12796. {\if\edition\racketEd
  12797. \[
  12798. \begin{array}{l}
  12799. \gray{\LintASTRacket{}} \\ \hline
  12800. \gray{\LvarASTRacket{}} \\ \hline
  12801. \gray{\LifASTRacket{}} \\ \hline
  12802. \gray{\LwhileASTRacket} \\ \hline
  12803. \gray{\LtupASTRacket} \\ \hline
  12804. \LarrayASTRacket \\
  12805. \begin{array}{lcl}
  12806. \LangArray{} &::=& \Exp
  12807. \end{array}
  12808. \end{array}
  12809. \]
  12810. \fi}
  12811. {\if\edition\pythonEd
  12812. \[
  12813. \begin{array}{l}
  12814. \gray{\LintASTPython{}} \\ \hline
  12815. \gray{\LvarASTPython{}} \\ \hline
  12816. \gray{\LifASTPython{}} \\ \hline
  12817. \gray{\LwhileASTPython} \\ \hline
  12818. \gray{\LtupASTPython} \\ \hline
  12819. \LarrayASTPython \\
  12820. \begin{array}{rcl}
  12821. \LangArrayM{} &::=& \Stmt^{*}
  12822. \end{array}
  12823. \end{array}
  12824. \]
  12825. \fi}
  12826. \end{tcolorbox}
  12827. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12828. \label{fig:Lvecof-syntax}
  12829. \end{figure}
  12830. \begin{figure}[tp]
  12831. \begin{tcolorbox}[colback=white]
  12832. {\if\edition\racketEd
  12833. % TODO: remove the function from the following example, like the python version -Jeremy
  12834. \begin{lstlisting}
  12835. (let ([A (make-vector 2 2)])
  12836. (let ([B (make-vector 2 3)])
  12837. (let ([i 0])
  12838. (let ([prod 0])
  12839. (begin
  12840. (while (< i n)
  12841. (begin
  12842. (set! prod (+ prod (* (vector-ref A i)
  12843. (vector-ref B i))))
  12844. (set! i (+ i 1))))
  12845. prod)))))
  12846. \end{lstlisting}
  12847. \fi}
  12848. {\if\edition\pythonEd
  12849. \begin{lstlisting}
  12850. A = [2, 2]
  12851. B = [3, 3]
  12852. i = 0
  12853. prod = 0
  12854. while i != len(A):
  12855. prod = prod + A[i] * B[i]
  12856. i = i + 1
  12857. print( prod )
  12858. \end{lstlisting}
  12859. \fi}
  12860. \end{tcolorbox}
  12861. \caption{Example program that computes the inner product.}
  12862. \label{fig:inner_product}
  12863. \end{figure}
  12864. {\if\edition\racketEd
  12865. %
  12866. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12867. checker for \LangArray{}. The result type of
  12868. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12869. of the initializing expression. The length expression is required to
  12870. have type \code{Integer}. The type checking of the operators
  12871. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12872. updated to handle the situation in which the vector has type
  12873. \code{Vectorof}. In these cases we translate the operators to their
  12874. \code{vectorof} form so that later passes can easily distinguish
  12875. between operations on tuples versus arrays. We override the
  12876. \code{operator-types} method to provide the type signature for
  12877. multiplication: it takes two integers and returns an integer. \fi}
  12878. {\if\edition\pythonEd
  12879. %
  12880. The type checker for \LangArray{} is defined in
  12881. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12882. is \code{list[T]} where \code{T} is the type of the initializing
  12883. expressions. The type checking of the \code{len} function and the
  12884. subscript operator is updated to handle lists. The type checker now
  12885. also handles a subscript on the left-hand side of an assignment.
  12886. Regarding multiplication, it takes two integers and returns an
  12887. integer.
  12888. %
  12889. \fi}
  12890. \begin{figure}[tbp]
  12891. \begin{tcolorbox}[colback=white]
  12892. {\if\edition\racketEd
  12893. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12894. (define type-check-Lvecof-class
  12895. (class type-check-Lvec-class
  12896. (super-new)
  12897. (inherit check-type-equal?)
  12898. (define/override (operator-types)
  12899. (append '((* . ((Integer Integer) . Integer)))
  12900. (super operator-types)))
  12901. (define/override (type-check-exp env)
  12902. (lambda (e)
  12903. (define recur (type-check-exp env))
  12904. (match e
  12905. [(Prim 'make-vector (list e1 e2))
  12906. (define-values (e1^ t1) (recur e1))
  12907. (define-values (e2^ elt-type) (recur e2))
  12908. (define vec-type `(Vectorof ,elt-type))
  12909. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12910. [(Prim 'vector-ref (list e1 e2))
  12911. (define-values (e1^ t1) (recur e1))
  12912. (define-values (e2^ t2) (recur e2))
  12913. (match* (t1 t2)
  12914. [(`(Vectorof ,elt-type) 'Integer)
  12915. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12916. [(other wise) ((super type-check-exp env) e)])]
  12917. [(Prim 'vector-set! (list e1 e2 e3) )
  12918. (define-values (e-vec t-vec) (recur e1))
  12919. (define-values (e2^ t2) (recur e2))
  12920. (define-values (e-arg^ t-arg) (recur e3))
  12921. (match t-vec
  12922. [`(Vectorof ,elt-type)
  12923. (check-type-equal? elt-type t-arg e)
  12924. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12925. [else ((super type-check-exp env) e)])]
  12926. [(Prim 'vector-length (list e1))
  12927. (define-values (e1^ t1) (recur e1))
  12928. (match t1
  12929. [`(Vectorof ,t)
  12930. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12931. [else ((super type-check-exp env) e)])]
  12932. [else ((super type-check-exp env) e)])))
  12933. ))
  12934. (define (type-check-Lvecof p)
  12935. (send (new type-check-Lvecof-class) type-check-program p))
  12936. \end{lstlisting}
  12937. \fi}
  12938. {\if\edition\pythonEd
  12939. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12940. class TypeCheckLarray(TypeCheckLtup):
  12941. def type_check_exp(self, e, env):
  12942. match e:
  12943. case ast.List(es, Load()):
  12944. ts = [self.type_check_exp(e, env) for e in es]
  12945. elt_ty = ts[0]
  12946. for (ty, elt) in zip(ts, es):
  12947. self.check_type_equal(elt_ty, ty, elt)
  12948. e.has_type = ListType(elt_ty)
  12949. return e.has_type
  12950. case Call(Name('len'), [tup]):
  12951. tup_t = self.type_check_exp(tup, env)
  12952. tup.has_type = tup_t
  12953. match tup_t:
  12954. case TupleType(ts):
  12955. return IntType()
  12956. case ListType(ty):
  12957. return IntType()
  12958. case _:
  12959. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12960. case Subscript(tup, index, Load()):
  12961. tup_ty = self.type_check_exp(tup, env)
  12962. index_ty = self.type_check_exp(index, env)
  12963. self.check_type_equal(index_ty, IntType(), index)
  12964. match tup_ty:
  12965. case TupleType(ts):
  12966. match index:
  12967. case Constant(i):
  12968. return ts[i]
  12969. case _:
  12970. raise Exception('subscript required constant integer index')
  12971. case ListType(ty):
  12972. return ty
  12973. case _:
  12974. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12975. case BinOp(left, Mult(), right):
  12976. l = self.type_check_exp(left, env)
  12977. self.check_type_equal(l, IntType(), left)
  12978. r = self.type_check_exp(right, env)
  12979. self.check_type_equal(r, IntType(), right)
  12980. return IntType()
  12981. case _:
  12982. return super().type_check_exp(e, env)
  12983. def type_check_stmts(self, ss, env):
  12984. if len(ss) == 0:
  12985. return VoidType()
  12986. match ss[0]:
  12987. case Assign([Subscript(tup, index, Store())], value):
  12988. tup_t = self.type_check_exp(tup, env)
  12989. value_t = self.type_check_exp(value, env)
  12990. index_ty = self.type_check_exp(index, env)
  12991. self.check_type_equal(index_ty, IntType(), index)
  12992. match tup_t:
  12993. case ListType(ty):
  12994. self.check_type_equal(ty, value_t, ss[0])
  12995. case TupleType(ts):
  12996. return self.type_check_stmts(ss, env)
  12997. case _:
  12998. raise Exception('type_check_stmts: '
  12999. 'expected tuple or list, not ' + repr(tup_t))
  13000. return self.type_check_stmts(ss[1:], env)
  13001. case _:
  13002. return super().type_check_stmts(ss, env)
  13003. \end{lstlisting}
  13004. \fi}
  13005. \end{tcolorbox}
  13006. \caption{Type checker for the \LangArray{} language.}
  13007. \label{fig:type-check-Lvecof}
  13008. \end{figure}
  13009. The definition of the interpreter for \LangArray{} is shown in
  13010. figure~\ref{fig:interp-Lvecof}.
  13011. \racket{The \code{make-vector} operator is
  13012. interpreted using Racket's \code{make-vector} function,
  13013. and multiplication is interpreted using \code{fx*},
  13014. which is multiplication for \code{fixnum} integers.
  13015. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  13016. we translate array access operations
  13017. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13018. which we interpret using \code{vector} operations with additional
  13019. bounds checks that signal a \code{trapped-error}.
  13020. }
  13021. %
  13022. \python{We implement list creation with a Python list comprehension
  13023. and multiplication is implemented with Python multiplication. We
  13024. add a case to handle a subscript on the left-hand side of
  13025. assignment. Other uses of subscript can be handled by the existing
  13026. code for tuples.}
  13027. \begin{figure}[tbp]
  13028. \begin{tcolorbox}[colback=white]
  13029. {\if\edition\racketEd
  13030. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13031. (define interp-Lvecof-class
  13032. (class interp-Lvec-class
  13033. (super-new)
  13034. (define/override (interp-op op)
  13035. (match op
  13036. ['make-vector make-vector]
  13037. ['vectorof-length vector-length]
  13038. ['vectorof-ref
  13039. (lambda (v i)
  13040. (if (< i (vector-length v))
  13041. (vector-ref v i)
  13042. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13043. ['vectorof-set!
  13044. (lambda (v i e)
  13045. (if (< i (vector-length v))
  13046. (vector-set! v i e)
  13047. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13048. [else (super interp-op op)]))
  13049. ))
  13050. (define (interp-Lvecof p)
  13051. (send (new interp-Lvecof-class) interp-program p))
  13052. \end{lstlisting}
  13053. \fi}
  13054. {\if\edition\pythonEd
  13055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13056. class InterpLarray(InterpLtup):
  13057. def interp_exp(self, e, env):
  13058. match e:
  13059. case ast.List(es, Load()):
  13060. return [self.interp_exp(e, env) for e in es]
  13061. case BinOp(left, Mult(), right):
  13062. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13063. return l * r
  13064. case _:
  13065. return super().interp_exp(e, env)
  13066. def interp_stmts(self, ss, env):
  13067. if len(ss) == 0:
  13068. return
  13069. match ss[0]:
  13070. case Assign([Subscript(lst, index)], value):
  13071. lst = self.interp_exp(lst, env)
  13072. index = self.interp_exp(index, env)
  13073. lst[index] = self.interp_exp(value, env)
  13074. return self.interp_stmts(ss[1:], env)
  13075. case _:
  13076. return super().interp_stmts(ss, env)
  13077. \end{lstlisting}
  13078. \fi}
  13079. \end{tcolorbox}
  13080. \caption{Interpreter for \LangArray{}.}
  13081. \label{fig:interp-Lvecof}
  13082. \end{figure}
  13083. \subsection{Data Representation}
  13084. \label{sec:array-rep}
  13085. Just as with tuples, we store arrays on the heap, which means that the
  13086. garbage collector will need to inspect arrays. An immediate thought is
  13087. to use the same representation for arrays that we use for tuples.
  13088. However, we limit tuples to a length of fifty so that their length and
  13089. pointer mask can fit into the 64-bit tag at the beginning of each
  13090. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13091. millions of elements, so we need more bits to store the length.
  13092. However, because arrays are homogeneous, we need only 1 bit for the
  13093. pointer mask instead of 1 bit per array element. Finally, the
  13094. garbage collector must be able to distinguish between tuples
  13095. and arrays, so we need to reserve one bit for that purpose. We
  13096. arrive at the following layout for the 64-bit tag at the beginning of
  13097. an array:
  13098. \begin{itemize}
  13099. \item The right-most bit is the forwarding bit, just as in a tuple.
  13100. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13101. that it is not.
  13102. \item The next bit to the left is the pointer mask. A $0$ indicates
  13103. that none of the elements are pointers to the heap, and a $1$
  13104. indicates that all the elements are pointers.
  13105. \item The next $60$ bits store the length of the array.
  13106. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13107. and an array ($1$).
  13108. \item The left-most bit is reserved as explained in
  13109. chapter~\ref{ch:Lgrad}.
  13110. \end{itemize}
  13111. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13112. %% differentiate the kinds of values that have been injected into the
  13113. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13114. %% to indicate that the value is an array.
  13115. In the following subsections we provide hints regarding how to update
  13116. the passes to handle arrays.
  13117. \subsection{Overload Resolution}
  13118. \label{sec:array-resolution}
  13119. As noted previously, with the addition of arrays, several operators
  13120. have become \emph{overloaded}; that is, they can be applied to values
  13121. of more than one type. In this case, the element access and length
  13122. operators can be applied to both tuples and arrays. This kind of
  13123. overloading is quite common in programming languages, so many
  13124. compilers perform \emph{overload resolution}\index{subject}{overload
  13125. resolution} to handle it. The idea is to translate each overloaded
  13126. operator into different operators for the different types.
  13127. Implement a new pass named \code{resolve}.
  13128. Translate the reading of an array element
  13129. into a call to
  13130. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13131. and the writing of an array element to
  13132. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13133. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13134. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13135. When these operators are applied to tuples, leave them as is.
  13136. %
  13137. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13138. field which can be inspected to determine whether the operator
  13139. is applied to a tuple or an array.}
  13140. \subsection{Bounds Checking}
  13141. Recall that the interpreter for \LangArray{} signals a
  13142. \code{trapped-error} when there is an array access that is out of
  13143. bounds. Therefore your compiler is obliged to also catch these errors
  13144. during execution and halt, signaling an error. We recommend inserting
  13145. a new pass named \code{check\_bounds} that inserts code around each
  13146. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13147. \python{subscript} operation to ensure that the index is greater than
  13148. or equal to zero and less than the array's length. If not, the program
  13149. should halt, for which we recommend using a new primitive operation
  13150. named \code{exit}.
  13151. %% \subsection{Reveal Casts}
  13152. %% The array-access operators \code{vectorof-ref} and
  13153. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13154. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13155. %% that the type checker cannot tell whether the index will be in bounds,
  13156. %% so the bounds check must be performed at run time. Recall that the
  13157. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13158. %% an \code{If} around a vector reference for update to check whether
  13159. %% the index is less than the length. You should do the same for
  13160. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13161. %% In addition, the handling of the \code{any-vector} operators in
  13162. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13163. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13164. %% generated code should test whether the tag is for tuples (\code{010})
  13165. %% or arrays (\code{110}) and then dispatch to either
  13166. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13167. %% we add a case in \code{select\_instructions} to generate the
  13168. %% appropriate instructions for accessing the array length from the
  13169. %% header of an array.
  13170. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13171. %% the generated code needs to check that the index is less than the
  13172. %% vector length, so like the code for \code{any-vector-length}, check
  13173. %% the tag to determine whether to use \code{any-vector-length} or
  13174. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13175. %% is complete, the generated code can use \code{any-vector-ref} and
  13176. %% \code{any-vector-set!} for both tuples and arrays because the
  13177. %% instructions used for those operators do not look at the tag at the
  13178. %% front of the tuple or array.
  13179. \subsection{Expose Allocation}
  13180. This pass should translate array creation into lower-level
  13181. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13182. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13183. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13184. array. The \code{AllocateArray} AST node allocates an array of the
  13185. length specified by the $\Exp$ (of type \INTTY), but does not
  13186. initialize the elements of the array. Generate code in this pass to
  13187. initialize the elements analogous to the case for tuples.
  13188. {\if\edition\racketEd
  13189. \section{Uncover \texttt{get!}}
  13190. \label{sec:uncover-get-bang-vecof}
  13191. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13192. \code{uncover-get!-exp}.
  13193. \fi}
  13194. \subsection{Remove Complex Operands}
  13195. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13196. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13197. complex, and its subexpression must be atomic.
  13198. \subsection{Explicate Control}
  13199. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13200. \code{explicate\_assign}.
  13201. \subsection{Select Instructions}
  13202. Generate instructions for \code{AllocateArray} similar to those for
  13203. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13204. except that the tag at the front of the array should instead use the
  13205. representation discussed in section~\ref{sec:array-rep}.
  13206. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13207. extract the length from the tag.
  13208. The instructions generated for accessing an element of an array differ
  13209. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13210. that the index is not a constant so you need to generate instructions
  13211. that compute the offset at runtime.
  13212. Compile the \code{exit} primitive into a call to the \code{exit}
  13213. function of the C standard library, with an argument of $255$.
  13214. %% Also, note that assignment to an array element may appear in
  13215. %% as a stand-alone statement, so make sure to handle that situation in
  13216. %% this pass.
  13217. %% Finally, the instructions for \code{any-vectorof-length} should be
  13218. %% similar to those for \code{vectorof-length}, except that one must
  13219. %% first project the array by writing zeroes into the $3$-bit tag
  13220. \begin{exercise}\normalfont\normalsize
  13221. Implement a compiler for the \LangArray{} language by extending your
  13222. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13223. programs, including the one shown in figure~\ref{fig:inner_product}
  13224. and also a program that multiplies two matrices. Note that although
  13225. matrices are two-dimensional arrays, they can be encoded into
  13226. one-dimensional arrays by laying out each row in the array, one after
  13227. the next.
  13228. \end{exercise}
  13229. {\if\edition\racketEd
  13230. \section{Challenge: Generational Collection}
  13231. The copying collector described in section~\ref{sec:GC} can incur
  13232. significant runtime overhead because the call to \code{collect} takes
  13233. time proportional to all the live data. One way to reduce this
  13234. overhead is to reduce how much data is inspected in each call to
  13235. \code{collect}. In particular, researchers have observed that recently
  13236. allocated data is more likely to become garbage then data that has
  13237. survived one or more previous calls to \code{collect}. This insight
  13238. motivated the creation of \emph{generational garbage collectors}
  13239. \index{subject}{generational garbage collector} that
  13240. (1) segregate data according to its age into two or more generations;
  13241. (2) allocate less space for younger generations, so collecting them is
  13242. faster, and more space for the older generations; and (3) perform
  13243. collection on the younger generations more frequently than on older
  13244. generations~\citep{Wilson:1992fk}.
  13245. For this challenge assignment, the goal is to adapt the copying
  13246. collector implemented in \code{runtime.c} to use two generations, one
  13247. for young data and one for old data. Each generation consists of a
  13248. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13249. \code{collect} function to use the two generations:
  13250. \begin{enumerate}
  13251. \item Copy the young generation's FromSpace to its ToSpace and then
  13252. switch the role of the ToSpace and FromSpace
  13253. \item If there is enough space for the requested number of bytes in
  13254. the young FromSpace, then return from \code{collect}.
  13255. \item If there is not enough space in the young FromSpace for the
  13256. requested bytes, then move the data from the young generation to the
  13257. old one with the following steps:
  13258. \begin{enumerate}
  13259. \item[a.] If there is enough room in the old FromSpace, copy the young
  13260. FromSpace to the old FromSpace and then return.
  13261. \item[b.] If there is not enough room in the old FromSpace, then collect
  13262. the old generation by copying the old FromSpace to the old ToSpace
  13263. and swap the roles of the old FromSpace and ToSpace.
  13264. \item[c.] If there is enough room now, copy the young FromSpace to the
  13265. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13266. and ToSpace for the old generation. Copy the young FromSpace and
  13267. the old FromSpace into the larger FromSpace for the old
  13268. generation and then return.
  13269. \end{enumerate}
  13270. \end{enumerate}
  13271. We recommend that you generalize the \code{cheney} function so that it
  13272. can be used for all the copies mentioned: between the young FromSpace
  13273. and ToSpace, between the old FromSpace and ToSpace, and between the
  13274. young FromSpace and old FromSpace. This can be accomplished by adding
  13275. parameters to \code{cheney} that replace its use of the global
  13276. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13277. \code{tospace\_begin}, and \code{tospace\_end}.
  13278. Note that the collection of the young generation does not traverse the
  13279. old generation. This introduces a potential problem: there may be
  13280. young data that is reachable only through pointers in the old
  13281. generation. If these pointers are not taken into account, the
  13282. collector could throw away young data that is live! One solution,
  13283. called \emph{pointer recording}, is to maintain a set of all the
  13284. pointers from the old generation into the new generation and consider
  13285. this set as part of the root set. To maintain this set, the compiler
  13286. must insert extra instructions around every \code{vector-set!}. If the
  13287. vector being modified is in the old generation, and if the value being
  13288. written is a pointer into the new generation, then that pointer must
  13289. be added to the set. Also, if the value being overwritten was a
  13290. pointer into the new generation, then that pointer should be removed
  13291. from the set.
  13292. \begin{exercise}\normalfont\normalsize
  13293. Adapt the \code{collect} function in \code{runtime.c} to implement
  13294. generational garbage collection, as outlined in this section.
  13295. Update the code generation for \code{vector-set!} to implement
  13296. pointer recording. Make sure that your new compiler and runtime
  13297. execute without error on your test suite.
  13298. \end{exercise}
  13299. \fi}
  13300. \section{Further Reading}
  13301. \citet{Appel90} describes many data representation approaches,
  13302. including the ones used in the compilation of Standard ML.
  13303. There are many alternatives to copying collectors (and their bigger
  13304. siblings, the generational collectors) with regard to garbage
  13305. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13306. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13307. collectors are that allocation is fast (just a comparison and pointer
  13308. increment), there is no fragmentation, cyclic garbage is collected,
  13309. and the time complexity of collection depends only on the amount of
  13310. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13311. main disadvantages of a two-space copying collector is that it uses a
  13312. lot of extra space and takes a long time to perform the copy, though
  13313. these problems are ameliorated in generational collectors.
  13314. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13315. small objects and generate a lot of garbage, so copying and
  13316. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13317. Garbage collection is an active research topic, especially concurrent
  13318. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13319. developing new techniques and revisiting old
  13320. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13321. meet every year at the International Symposium on Memory Management to
  13322. present these findings.
  13323. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13324. \chapter{Functions}
  13325. \label{ch:Lfun}
  13326. \index{subject}{function}
  13327. \setcounter{footnote}{0}
  13328. This chapter studies the compilation of a subset of \racket{Typed
  13329. Racket}\python{Python} in which only top-level function definitions
  13330. are allowed. This kind of function appears in the C programming
  13331. language, and it serves as an important stepping-stone to implementing
  13332. lexically scoped functions in the form of \key{lambda} abstractions,
  13333. which is the topic of chapter~\ref{ch:Llambda}.
  13334. \section{The \LangFun{} Language}
  13335. The concrete syntax and abstract syntax for function definitions and
  13336. function application are shown in
  13337. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13338. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13339. with zero or more function definitions. The function names from these
  13340. definitions are in scope for the entire program, including all the
  13341. function definitions, and therefore the ordering of function
  13342. definitions does not matter.
  13343. %
  13344. \python{The abstract syntax for function parameters in
  13345. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13346. consists of a parameter name and its type. This design differs from
  13347. Python's \code{ast} module, which has a more complex structure for
  13348. function parameters to handle keyword parameters,
  13349. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13350. complex Python abstract syntax into the simpler syntax of
  13351. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13352. \code{FunctionDef} constructor are for decorators and a type
  13353. comment, neither of which are used by our compiler. We recommend
  13354. replacing them with \code{None} in the \code{shrink} pass.
  13355. }
  13356. %
  13357. The concrete syntax for function application
  13358. \index{subject}{function application}
  13359. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13360. where the first expression
  13361. must evaluate to a function and the remaining expressions are the arguments. The
  13362. abstract syntax for function application is
  13363. $\APPLY{\Exp}{\Exp^*}$.
  13364. %% The syntax for function application does not include an explicit
  13365. %% keyword, which is error prone when using \code{match}. To alleviate
  13366. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13367. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13368. Functions are first-class in the sense that a function pointer
  13369. \index{subject}{function pointer} is data and can be stored in memory or passed
  13370. as a parameter to another function. Thus, there is a function
  13371. type, written
  13372. {\if\edition\racketEd
  13373. \begin{lstlisting}
  13374. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13375. \end{lstlisting}
  13376. \fi}
  13377. {\if\edition\pythonEd
  13378. \begin{lstlisting}
  13379. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13380. \end{lstlisting}
  13381. \fi}
  13382. %
  13383. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13384. through $\Type_n$ and whose return type is $\Type_R$. The main
  13385. limitation of these functions (with respect to
  13386. \racket{Racket}\python{Python} functions) is that they are not
  13387. lexically scoped. That is, the only external entities that can be
  13388. referenced from inside a function body are other globally defined
  13389. functions. The syntax of \LangFun{} prevents function definitions from
  13390. being nested inside each other.
  13391. \newcommand{\LfunGrammarRacket}{
  13392. \begin{array}{lcl}
  13393. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13394. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13395. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13396. \end{array}
  13397. }
  13398. \newcommand{\LfunASTRacket}{
  13399. \begin{array}{lcl}
  13400. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13401. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13402. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13403. \end{array}
  13404. }
  13405. \newcommand{\LfunGrammarPython}{
  13406. \begin{array}{lcl}
  13407. \Type &::=& \key{int}
  13408. \MID \key{bool} \MID \key{void}
  13409. \MID \key{tuple}\LS \Type^+ \RS
  13410. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13411. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13412. \Stmt &::=& \CRETURN{\Exp} \\
  13413. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13414. \end{array}
  13415. }
  13416. \newcommand{\LfunASTPython}{
  13417. \begin{array}{lcl}
  13418. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13419. \MID \key{TupleType}\LS\Type^+\RS\\
  13420. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13421. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13422. \Stmt &::=& \RETURN{\Exp} \\
  13423. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13424. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13425. \end{array}
  13426. }
  13427. \begin{figure}[tp]
  13428. \centering
  13429. \begin{tcolorbox}[colback=white]
  13430. \small
  13431. {\if\edition\racketEd
  13432. \[
  13433. \begin{array}{l}
  13434. \gray{\LintGrammarRacket{}} \\ \hline
  13435. \gray{\LvarGrammarRacket{}} \\ \hline
  13436. \gray{\LifGrammarRacket{}} \\ \hline
  13437. \gray{\LwhileGrammarRacket} \\ \hline
  13438. \gray{\LtupGrammarRacket} \\ \hline
  13439. \LfunGrammarRacket \\
  13440. \begin{array}{lcl}
  13441. \LangFunM{} &::=& \Def \ldots \; \Exp
  13442. \end{array}
  13443. \end{array}
  13444. \]
  13445. \fi}
  13446. {\if\edition\pythonEd
  13447. \[
  13448. \begin{array}{l}
  13449. \gray{\LintGrammarPython{}} \\ \hline
  13450. \gray{\LvarGrammarPython{}} \\ \hline
  13451. \gray{\LifGrammarPython{}} \\ \hline
  13452. \gray{\LwhileGrammarPython} \\ \hline
  13453. \gray{\LtupGrammarPython} \\ \hline
  13454. \LfunGrammarPython \\
  13455. \begin{array}{rcl}
  13456. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13457. \end{array}
  13458. \end{array}
  13459. \]
  13460. \fi}
  13461. \end{tcolorbox}
  13462. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13463. \label{fig:Lfun-concrete-syntax}
  13464. \end{figure}
  13465. \begin{figure}[tp]
  13466. \centering
  13467. \begin{tcolorbox}[colback=white]
  13468. \small
  13469. {\if\edition\racketEd
  13470. \[
  13471. \begin{array}{l}
  13472. \gray{\LintOpAST} \\ \hline
  13473. \gray{\LvarASTRacket{}} \\ \hline
  13474. \gray{\LifASTRacket{}} \\ \hline
  13475. \gray{\LwhileASTRacket{}} \\ \hline
  13476. \gray{\LtupASTRacket{}} \\ \hline
  13477. \LfunASTRacket \\
  13478. \begin{array}{lcl}
  13479. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13480. \end{array}
  13481. \end{array}
  13482. \]
  13483. \fi}
  13484. {\if\edition\pythonEd
  13485. \[
  13486. \begin{array}{l}
  13487. \gray{\LintASTPython{}} \\ \hline
  13488. \gray{\LvarASTPython{}} \\ \hline
  13489. \gray{\LifASTPython{}} \\ \hline
  13490. \gray{\LwhileASTPython} \\ \hline
  13491. \gray{\LtupASTPython} \\ \hline
  13492. \LfunASTPython \\
  13493. \begin{array}{rcl}
  13494. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13495. \end{array}
  13496. \end{array}
  13497. \]
  13498. \fi}
  13499. \end{tcolorbox}
  13500. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13501. \label{fig:Lfun-syntax}
  13502. \end{figure}
  13503. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13504. representative example of defining and using functions in \LangFun{}.
  13505. We define a function \code{map} that applies some other function
  13506. \code{f} to both elements of a tuple and returns a new tuple
  13507. containing the results. We also define a function \code{inc}. The
  13508. program applies \code{map} to \code{inc} and
  13509. %
  13510. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13511. %
  13512. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13513. %
  13514. from which we return \code{42}.
  13515. \begin{figure}[tbp]
  13516. \begin{tcolorbox}[colback=white]
  13517. {\if\edition\racketEd
  13518. \begin{lstlisting}
  13519. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13520. : (Vector Integer Integer)
  13521. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13522. (define (inc [x : Integer]) : Integer
  13523. (+ x 1))
  13524. (vector-ref (map inc (vector 0 41)) 1)
  13525. \end{lstlisting}
  13526. \fi}
  13527. {\if\edition\pythonEd
  13528. \begin{lstlisting}
  13529. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13530. return f(v[0]), f(v[1])
  13531. def inc(x : int) -> int:
  13532. return x + 1
  13533. print( map(inc, (0, 41))[1] )
  13534. \end{lstlisting}
  13535. \fi}
  13536. \end{tcolorbox}
  13537. \caption{Example of using functions in \LangFun{}.}
  13538. \label{fig:Lfun-function-example}
  13539. \end{figure}
  13540. The definitional interpreter for \LangFun{} is shown in
  13541. figure~\ref{fig:interp-Lfun}. The case for the
  13542. %
  13543. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13544. %
  13545. AST is responsible for setting up the mutual recursion between the
  13546. top-level function definitions.
  13547. %
  13548. \racket{We use the classic back-patching
  13549. \index{subject}{back-patching} approach that uses mutable variables
  13550. and makes two passes over the function
  13551. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13552. top-level environment using a mutable cons cell for each function
  13553. definition. Note that the \code{lambda} value for each function is
  13554. incomplete; it does not yet include the environment. Once the
  13555. top-level environment has been constructed, we iterate over it and
  13556. update the \code{lambda} values to use the top-level environment.}
  13557. %
  13558. \python{We create a dictionary named \code{env} and fill it in
  13559. by mapping each function name to a new \code{Function} value,
  13560. each of which stores a reference to the \code{env}.
  13561. (We define the class \code{Function} for this purpose.)}
  13562. %
  13563. To interpret a function \racket{application}\python{call}, we match
  13564. the result of the function expression to obtain a function value. We
  13565. then extend the function's environment with the mapping of parameters to
  13566. argument values. Finally, we interpret the body of the function in
  13567. this extended environment.
  13568. \begin{figure}[tp]
  13569. \begin{tcolorbox}[colback=white]
  13570. {\if\edition\racketEd
  13571. \begin{lstlisting}
  13572. (define interp-Lfun-class
  13573. (class interp-Lvec-class
  13574. (super-new)
  13575. (define/override ((interp-exp env) e)
  13576. (define recur (interp-exp env))
  13577. (match e
  13578. [(Apply fun args)
  13579. (define fun-val (recur fun))
  13580. (define arg-vals (for/list ([e args]) (recur e)))
  13581. (match fun-val
  13582. [`(function (,xs ...) ,body ,fun-env)
  13583. (define params-args (for/list ([x xs] [arg arg-vals])
  13584. (cons x (box arg))))
  13585. (define new-env (append params-args fun-env))
  13586. ((interp-exp new-env) body)]
  13587. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  13588. [else ((super interp-exp env) e)]
  13589. ))
  13590. (define/public (interp-def d)
  13591. (match d
  13592. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13593. (cons f (box `(function ,xs ,body ())))]))
  13594. (define/override (interp-program p)
  13595. (match p
  13596. [(ProgramDefsExp info ds body)
  13597. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13598. (for/list ([f (in-dict-values top-level)])
  13599. (set-box! f (match (unbox f)
  13600. [`(function ,xs ,body ())
  13601. `(function ,xs ,body ,top-level)])))
  13602. ((interp-exp top-level) body))]))
  13603. ))
  13604. (define (interp-Lfun p)
  13605. (send (new interp-Lfun-class) interp-program p))
  13606. \end{lstlisting}
  13607. \fi}
  13608. {\if\edition\pythonEd
  13609. \begin{lstlisting}
  13610. class InterpLfun(InterpLtup):
  13611. def apply_fun(self, fun, args, e):
  13612. match fun:
  13613. case Function(name, xs, body, env):
  13614. new_env = env.copy().update(zip(xs, args))
  13615. return self.interp_stmts(body, new_env)
  13616. case _:
  13617. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13618. def interp_exp(self, e, env):
  13619. match e:
  13620. case Call(Name('input_int'), []):
  13621. return super().interp_exp(e, env)
  13622. case Call(func, args):
  13623. f = self.interp_exp(func, env)
  13624. vs = [self.interp_exp(arg, env) for arg in args]
  13625. return self.apply_fun(f, vs, e)
  13626. case _:
  13627. return super().interp_exp(e, env)
  13628. def interp_stmts(self, ss, env):
  13629. if len(ss) == 0:
  13630. return
  13631. match ss[0]:
  13632. case Return(value):
  13633. return self.interp_exp(value, env)
  13634. case FunctionDef(name, params, bod, dl, returns, comment):
  13635. ps = [x for (x,t) in params]
  13636. env[name] = Function(name, ps, bod, env)
  13637. return self.interp_stmts(ss[1:], env)
  13638. case _:
  13639. return super().interp_stmts(ss, env)
  13640. def interp(self, p):
  13641. match p:
  13642. case Module(ss):
  13643. env = {}
  13644. self.interp_stmts(ss, env)
  13645. if 'main' in env.keys():
  13646. self.apply_fun(env['main'], [], None)
  13647. case _:
  13648. raise Exception('interp: unexpected ' + repr(p))
  13649. \end{lstlisting}
  13650. \fi}
  13651. \end{tcolorbox}
  13652. \caption{Interpreter for the \LangFun{} language.}
  13653. \label{fig:interp-Lfun}
  13654. \end{figure}
  13655. %\margincomment{TODO: explain type checker}
  13656. The type checker for \LangFun{} is shown in
  13657. figure~\ref{fig:type-check-Lfun}.
  13658. %
  13659. \python{(We omit the code that parses function parameters into the
  13660. simpler abstract syntax.)}
  13661. %
  13662. Similarly to the interpreter, the case for the
  13663. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13664. %
  13665. AST is responsible for setting up the mutual recursion between the
  13666. top-level function definitions. We begin by create a mapping
  13667. \code{env} from every function name to its type. We then type check
  13668. the program using this mapping.
  13669. %
  13670. In the case for function \racket{application}\python{call}, we match
  13671. the type of the function expression to a function type and check that
  13672. the types of the argument expressions are equal to the function's
  13673. parameter types. The type of the \racket{application}\python{call} as
  13674. a whole is the return type from the function type.
  13675. \begin{figure}[tp]
  13676. \begin{tcolorbox}[colback=white]
  13677. {\if\edition\racketEd
  13678. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13679. (define type-check-Lfun-class
  13680. (class type-check-Lvec-class
  13681. (super-new)
  13682. (inherit check-type-equal?)
  13683. (define/public (type-check-apply env e es)
  13684. (define-values (e^ ty) ((type-check-exp env) e))
  13685. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13686. ((type-check-exp env) e)))
  13687. (match ty
  13688. [`(,ty^* ... -> ,rt)
  13689. (for ([arg-ty ty*] [param-ty ty^*])
  13690. (check-type-equal? arg-ty param-ty (Apply e es)))
  13691. (values e^ e* rt)]))
  13692. (define/override (type-check-exp env)
  13693. (lambda (e)
  13694. (match e
  13695. [(FunRef f n)
  13696. (values (FunRef f n) (dict-ref env f))]
  13697. [(Apply e es)
  13698. (define-values (e^ es^ rt) (type-check-apply env e es))
  13699. (values (Apply e^ es^) rt)]
  13700. [(Call e es)
  13701. (define-values (e^ es^ rt) (type-check-apply env e es))
  13702. (values (Call e^ es^) rt)]
  13703. [else ((super type-check-exp env) e)])))
  13704. (define/public (type-check-def env)
  13705. (lambda (e)
  13706. (match e
  13707. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13708. (define new-env (append (map cons xs ps) env))
  13709. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13710. (check-type-equal? ty^ rt body)
  13711. (Def f p:t* rt info body^)])))
  13712. (define/public (fun-def-type d)
  13713. (match d
  13714. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13715. (define/override (type-check-program e)
  13716. (match e
  13717. [(ProgramDefsExp info ds body)
  13718. (define env (for/list ([d ds])
  13719. (cons (Def-name d) (fun-def-type d))))
  13720. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13721. (define-values (body^ ty) ((type-check-exp env) body))
  13722. (check-type-equal? ty 'Integer body)
  13723. (ProgramDefsExp info ds^ body^)]))))
  13724. (define (type-check-Lfun p)
  13725. (send (new type-check-Lfun-class) type-check-program p))
  13726. \end{lstlisting}
  13727. \fi}
  13728. {\if\edition\pythonEd
  13729. \begin{lstlisting}
  13730. class TypeCheckLfun(TypeCheckLtup):
  13731. def type_check_exp(self, e, env):
  13732. match e:
  13733. case Call(Name('input_int'), []):
  13734. return super().type_check_exp(e, env)
  13735. case Call(func, args):
  13736. func_t = self.type_check_exp(func, env)
  13737. args_t = [self.type_check_exp(arg, env) for arg in args]
  13738. match func_t:
  13739. case FunctionType(params_t, return_t):
  13740. for (arg_t, param_t) in zip(args_t, params_t):
  13741. check_type_equal(param_t, arg_t, e)
  13742. return return_t
  13743. case _:
  13744. raise Exception('type_check_exp: in call, unexpected ' +
  13745. repr(func_t))
  13746. case _:
  13747. return super().type_check_exp(e, env)
  13748. def type_check_stmts(self, ss, env):
  13749. if len(ss) == 0:
  13750. return
  13751. match ss[0]:
  13752. case FunctionDef(name, params, body, dl, returns, comment):
  13753. new_env = env.copy().update(params)
  13754. rt = self.type_check_stmts(body, new_env)
  13755. check_type_equal(returns, rt, ss[0])
  13756. return self.type_check_stmts(ss[1:], env)
  13757. case Return(value):
  13758. return self.type_check_exp(value, env)
  13759. case _:
  13760. return super().type_check_stmts(ss, env)
  13761. def type_check(self, p):
  13762. match p:
  13763. case Module(body):
  13764. env = {}
  13765. for s in body:
  13766. match s:
  13767. case FunctionDef(name, params, bod, dl, returns, comment):
  13768. if name in env:
  13769. raise Exception('type_check: function ' +
  13770. repr(name) + ' defined twice')
  13771. params_t = [t for (x,t) in params]
  13772. env[name] = FunctionType(params_t, returns)
  13773. self.type_check_stmts(body, env)
  13774. case _:
  13775. raise Exception('type_check: unexpected ' + repr(p))
  13776. \end{lstlisting}
  13777. \fi}
  13778. \end{tcolorbox}
  13779. \caption{Type checker for the \LangFun{} language.}
  13780. \label{fig:type-check-Lfun}
  13781. \end{figure}
  13782. \clearpage
  13783. \section{Functions in x86}
  13784. \label{sec:fun-x86}
  13785. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13786. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13787. %% \margincomment{\tiny Talk about the return address on the
  13788. %% stack and what callq and retq does.\\ --Jeremy }
  13789. The x86 architecture provides a few features to support the
  13790. implementation of functions. We have already seen that there are
  13791. labels in x86 so that one can refer to the location of an instruction,
  13792. as is needed for jump instructions. Labels can also be used to mark
  13793. the beginning of the instructions for a function. Going further, we
  13794. can obtain the address of a label by using the \key{leaq}
  13795. instruction. For example, the following puts the address of the
  13796. \code{inc} label into the \code{rbx} register:
  13797. \begin{lstlisting}
  13798. leaq inc(%rip), %rbx
  13799. \end{lstlisting}
  13800. Recall from section~\ref{sec:select-instructions-gc} that
  13801. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13802. addressing.
  13803. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13804. to functions whose locations were given by a label, such as
  13805. \code{read\_int}. To support function calls in this chapter we instead
  13806. jump to functions whose location are given by an address in
  13807. a register; that is, we use \emph{indirect function calls}. The
  13808. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13809. before the register name.\index{subject}{indirect function call}
  13810. \begin{lstlisting}
  13811. callq *%rbx
  13812. \end{lstlisting}
  13813. \subsection{Calling Conventions}
  13814. \label{sec:calling-conventions-fun}
  13815. \index{subject}{calling conventions}
  13816. The \code{callq} instruction provides partial support for implementing
  13817. functions: it pushes the return address on the stack and it jumps to
  13818. the target. However, \code{callq} does not handle
  13819. \begin{enumerate}
  13820. \item parameter passing,
  13821. \item pushing frames on the procedure call stack and popping them off,
  13822. or
  13823. \item determining how registers are shared by different functions.
  13824. \end{enumerate}
  13825. Regarding parameter passing, recall that the x86-64 calling
  13826. convention for Unix-based system uses the following six registers to
  13827. pass arguments to a function, in the given order.
  13828. \begin{lstlisting}
  13829. rdi rsi rdx rcx r8 r9
  13830. \end{lstlisting}
  13831. If there are more than six arguments, then the calling convention
  13832. mandates using space on the frame of the caller for the rest of the
  13833. arguments. However, to ease the implementation of efficient tail calls
  13834. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13835. arguments.
  13836. %
  13837. The return value of the function is stored in register \code{rax}.
  13838. \index{subject}{prelude}\index{subject}{conclusion}
  13839. Regarding frames \index{subject}{frame} and the procedure call stack,
  13840. \index{subject}{procedure call stack} recall from
  13841. section~\ref{sec:x86} that the stack grows down and each function call
  13842. uses a chunk of space on the stack called a frame. The caller sets the
  13843. stack pointer, register \code{rsp}, to the last data item in its
  13844. frame. The callee must not change anything in the caller's frame, that
  13845. is, anything that is at or above the stack pointer. The callee is free
  13846. to use locations that are below the stack pointer.
  13847. Recall that we store variables of tuple type on the root stack. So,
  13848. the prelude of a function needs to move the root stack pointer
  13849. \code{r15} up according to the number of variables of tuple type and
  13850. the conclusion needs to move the root stack pointer back down. Also,
  13851. the prelude must initialize to \code{0} this frame's slots in the root
  13852. stack to signal to the garbage collector that those slots do not yet
  13853. contain a valid pointer. Otherwise the garbage collector will
  13854. interpret the garbage bits in those slots as memory addresses and try
  13855. to traverse them, causing serious mayhem!
  13856. Regarding the sharing of registers between different functions, recall
  13857. from section~\ref{sec:calling-conventions} that the registers are
  13858. divided into two groups, the caller-saved registers and the
  13859. callee-saved registers. The caller should assume that all the
  13860. caller-saved registers are overwritten with arbitrary values by the
  13861. callee. For that reason we recommend in
  13862. section~\ref{sec:calling-conventions} that variables that are live
  13863. during a function call should not be assigned to caller-saved
  13864. registers.
  13865. On the flip side, if the callee wants to use a callee-saved register,
  13866. the callee must save the contents of those registers on their stack
  13867. frame and then put them back prior to returning to the caller. For
  13868. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13869. the register allocator assigns a variable to a callee-saved register,
  13870. then the prelude of the \code{main} function must save that register
  13871. to the stack and the conclusion of \code{main} must restore it. This
  13872. recommendation now generalizes to all functions.
  13873. Recall that the base pointer, register \code{rbp}, is used as a
  13874. point of reference within a frame, so that each local variable can be
  13875. accessed at a fixed offset from the base pointer
  13876. (section~\ref{sec:x86}).
  13877. %
  13878. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13879. and callee frames.
  13880. \begin{figure}[tbp]
  13881. \centering
  13882. \begin{tcolorbox}[colback=white]
  13883. \begin{tabular}{r|r|l|l} \hline
  13884. Caller View & Callee View & Contents & Frame \\ \hline
  13885. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13886. 0(\key{\%rbp}) & & old \key{rbp} \\
  13887. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13888. \ldots & & \ldots \\
  13889. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13890. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13891. \ldots & & \ldots \\
  13892. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13893. %% & & \\
  13894. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13895. %% & \ldots & \ldots \\
  13896. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13897. \hline
  13898. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13899. & 0(\key{\%rbp}) & old \key{rbp} \\
  13900. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13901. & \ldots & \ldots \\
  13902. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13903. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13904. & \ldots & \ldots \\
  13905. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13906. \end{tabular}
  13907. \end{tcolorbox}
  13908. \caption{Memory layout of caller and callee frames.}
  13909. \label{fig:call-frames}
  13910. \end{figure}
  13911. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13912. %% local variables and for storing the values of callee-saved registers
  13913. %% (we shall refer to all of these collectively as ``locals''), and that
  13914. %% at the beginning of a function we move the stack pointer \code{rsp}
  13915. %% down to make room for them.
  13916. %% We recommend storing the local variables
  13917. %% first and then the callee-saved registers, so that the local variables
  13918. %% can be accessed using \code{rbp} the same as before the addition of
  13919. %% functions.
  13920. %% To make additional room for passing arguments, we shall
  13921. %% move the stack pointer even further down. We count how many stack
  13922. %% arguments are needed for each function call that occurs inside the
  13923. %% body of the function and find their maximum. Adding this number to the
  13924. %% number of locals gives us how much the \code{rsp} should be moved at
  13925. %% the beginning of the function. In preparation for a function call, we
  13926. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13927. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13928. %% so on.
  13929. %% Upon calling the function, the stack arguments are retrieved by the
  13930. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13931. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13932. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13933. %% the layout of the caller and callee frames. Notice how important it is
  13934. %% that we correctly compute the maximum number of arguments needed for
  13935. %% function calls; if that number is too small then the arguments and
  13936. %% local variables will smash into each other!
  13937. \subsection{Efficient Tail Calls}
  13938. \label{sec:tail-call}
  13939. In general, the amount of stack space used by a program is determined
  13940. by the longest chain of nested function calls. That is, if function
  13941. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13942. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13943. large if functions are recursive. However, in some cases we can
  13944. arrange to use only a constant amount of space for a long chain of
  13945. nested function calls.
  13946. A \emph{tail call}\index{subject}{tail call} is a function call that
  13947. happens as the last action in a function body. For example, in the
  13948. following program, the recursive call to \code{tail\_sum} is a tail
  13949. call:
  13950. \begin{center}
  13951. {\if\edition\racketEd
  13952. \begin{lstlisting}
  13953. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13954. (if (eq? n 0)
  13955. r
  13956. (tail_sum (- n 1) (+ n r))))
  13957. (+ (tail_sum 3 0) 36)
  13958. \end{lstlisting}
  13959. \fi}
  13960. {\if\edition\pythonEd
  13961. \begin{lstlisting}
  13962. def tail_sum(n : int, r : int) -> int:
  13963. if n == 0:
  13964. return r
  13965. else:
  13966. return tail_sum(n - 1, n + r)
  13967. print( tail_sum(3, 0) + 36)
  13968. \end{lstlisting}
  13969. \fi}
  13970. \end{center}
  13971. At a tail call, the frame of the caller is no longer needed, so we can
  13972. pop the caller's frame before making the tail call. With this
  13973. approach, a recursive function that makes only tail calls ends up
  13974. using a constant amount of stack space. Functional languages like
  13975. Racket rely heavily on recursive functions, so the definition of
  13976. Racket \emph{requires} that all tail calls be optimized in this way.
  13977. \index{subject}{frame}
  13978. Some care is needed with regard to argument passing in tail calls. As
  13979. mentioned, for arguments beyond the sixth, the convention is to use
  13980. space in the caller's frame for passing arguments. However, for a
  13981. tail call we pop the caller's frame and can no longer use it. An
  13982. alternative is to use space in the callee's frame for passing
  13983. arguments. However, this option is also problematic because the caller
  13984. and callee's frames overlap in memory. As we begin to copy the
  13985. arguments from their sources in the caller's frame, the target
  13986. locations in the callee's frame might collide with the sources for
  13987. later arguments! We solve this problem by using the heap instead of
  13988. the stack for passing more than six arguments
  13989. (section~\ref{sec:limit-functions-r4}).
  13990. As mentioned, for a tail call we pop the caller's frame prior to
  13991. making the tail call. The instructions for popping a frame are the
  13992. instructions that we usually place in the conclusion of a
  13993. function. Thus, we also need to place such code immediately before
  13994. each tail call. These instructions include restoring the callee-saved
  13995. registers, so it is fortunate that the argument passing registers are
  13996. all caller-saved registers.
  13997. One note remains regarding which instruction to use to make the tail
  13998. call. When the callee is finished, it should not return to the current
  13999. function but instead return to the function that called the current
  14000. one. Thus, the return address that is already on the stack is the
  14001. right one, and we should not use \key{callq} to make the tail call
  14002. because that would overwrite the return address. Instead we simply use
  14003. the \key{jmp} instruction. As with the indirect function call, we write
  14004. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14005. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14006. jump target because the conclusion can overwrite just about everything
  14007. else.
  14008. \begin{lstlisting}
  14009. jmp *%rax
  14010. \end{lstlisting}
  14011. \section{Shrink \LangFun{}}
  14012. \label{sec:shrink-r4}
  14013. The \code{shrink} pass performs a minor modification to ease the
  14014. later passes. This pass introduces an explicit \code{main} function
  14015. that gobbles up all the top-level statements of the module.
  14016. %
  14017. \racket{It also changes the top \code{ProgramDefsExp} form to
  14018. \code{ProgramDefs}.}
  14019. {\if\edition\racketEd
  14020. \begin{lstlisting}
  14021. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14022. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14023. \end{lstlisting}
  14024. where $\itm{mainDef}$ is
  14025. \begin{lstlisting}
  14026. (Def 'main '() 'Integer '() |$\Exp'$|)
  14027. \end{lstlisting}
  14028. \fi}
  14029. {\if\edition\pythonEd
  14030. \begin{lstlisting}
  14031. Module(|$\Def\ldots\Stmt\ldots$|)
  14032. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14033. \end{lstlisting}
  14034. where $\itm{mainDef}$ is
  14035. \begin{lstlisting}
  14036. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14037. \end{lstlisting}
  14038. \fi}
  14039. \section{Reveal Functions and the \LangFunRef{} language}
  14040. \label{sec:reveal-functions-r4}
  14041. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14042. in that it conflates the use of function names and local
  14043. variables. This is a problem because we need to compile the use of a
  14044. function name differently from the use of a local variable. In
  14045. particular, we use \code{leaq} to convert the function name (a label
  14046. in x86) to an address in a register. Thus, we create a new pass that
  14047. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14048. $n$ is the arity of the function.\python{\footnote{The arity is not
  14049. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14050. This pass is named \code{reveal\_functions} and the output language
  14051. is \LangFunRef{}.
  14052. %is defined in figure~\ref{fig:f1-syntax}.
  14053. %% The concrete syntax for a
  14054. %% function reference is $\CFUNREF{f}$.
  14055. %% \begin{figure}[tp]
  14056. %% \centering
  14057. %% \fbox{
  14058. %% \begin{minipage}{0.96\textwidth}
  14059. %% {\if\edition\racketEd
  14060. %% \[
  14061. %% \begin{array}{lcl}
  14062. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14063. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14064. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14065. %% \end{array}
  14066. %% \]
  14067. %% \fi}
  14068. %% {\if\edition\pythonEd
  14069. %% \[
  14070. %% \begin{array}{lcl}
  14071. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14072. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14073. %% \end{array}
  14074. %% \]
  14075. %% \fi}
  14076. %% \end{minipage}
  14077. %% }
  14078. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14079. %% (figure~\ref{fig:Lfun-syntax}).}
  14080. %% \label{fig:f1-syntax}
  14081. %% \end{figure}
  14082. %% Distinguishing between calls in tail position and non-tail position
  14083. %% requires the pass to have some notion of context. We recommend using
  14084. %% two mutually recursive functions, one for processing expressions in
  14085. %% tail position and another for the rest.
  14086. \racket{Placing this pass after \code{uniquify} will make sure that
  14087. there are no local variables and functions that share the same
  14088. name.}
  14089. %
  14090. The \code{reveal\_functions} pass should come before the
  14091. \code{remove\_complex\_operands} pass because function references
  14092. should be categorized as complex expressions.
  14093. \section{Limit Functions}
  14094. \label{sec:limit-functions-r4}
  14095. Recall that we wish to limit the number of function parameters to six
  14096. so that we do not need to use the stack for argument passing, which
  14097. makes it easier to implement efficient tail calls. However, because
  14098. the input language \LangFun{} supports arbitrary numbers of function
  14099. arguments, we have some work to do! The \code{limit\_functions} pass
  14100. transforms functions and function calls that involve more than six
  14101. arguments to pass the first five arguments as usual, but it packs the
  14102. rest of the arguments into a tuple and passes it as the sixth
  14103. argument.\footnote{The implementation this pass can be postponed to
  14104. last because you can test the rest of the passes on functions with
  14105. six or fewer parameters.}
  14106. Each function definition with seven or more parameters is transformed as
  14107. follows.
  14108. {\if\edition\racketEd
  14109. \begin{lstlisting}
  14110. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14111. |$\Rightarrow$|
  14112. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14113. \end{lstlisting}
  14114. \fi}
  14115. {\if\edition\pythonEd
  14116. \begin{lstlisting}
  14117. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14118. |$\Rightarrow$|
  14119. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14120. |$T_r$|, None, |$\itm{body}'$|, None)
  14121. \end{lstlisting}
  14122. \fi}
  14123. %
  14124. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14125. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14126. the $k$th element of the tuple, where $k = i - 6$.
  14127. %
  14128. {\if\edition\racketEd
  14129. \begin{lstlisting}
  14130. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14131. \end{lstlisting}
  14132. \fi}
  14133. {\if\edition\pythonEd
  14134. \begin{lstlisting}
  14135. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14136. \end{lstlisting}
  14137. \fi}
  14138. For function calls with too many arguments, the \code{limit\_functions}
  14139. pass transforms them in the following way:
  14140. \begin{tabular}{lll}
  14141. \begin{minipage}{0.3\textwidth}
  14142. {\if\edition\racketEd
  14143. \begin{lstlisting}
  14144. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14145. \end{lstlisting}
  14146. \fi}
  14147. {\if\edition\pythonEd
  14148. \begin{lstlisting}
  14149. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14150. \end{lstlisting}
  14151. \fi}
  14152. \end{minipage}
  14153. &
  14154. $\Rightarrow$
  14155. &
  14156. \begin{minipage}{0.5\textwidth}
  14157. {\if\edition\racketEd
  14158. \begin{lstlisting}
  14159. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14160. \end{lstlisting}
  14161. \fi}
  14162. {\if\edition\pythonEd
  14163. \begin{lstlisting}
  14164. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14165. \end{lstlisting}
  14166. \fi}
  14167. \end{minipage}
  14168. \end{tabular}
  14169. \section{Remove Complex Operands}
  14170. \label{sec:rco-r4}
  14171. The primary decisions to make for this pass are whether to classify
  14172. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14173. atomic or complex expressions. Recall that an atomic expression will
  14174. end up as an immediate argument of an x86 instruction. Function
  14175. application will be translated to a sequence of instructions, so
  14176. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14177. complex expression. On the other hand, the arguments of
  14178. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14179. expressions.
  14180. %
  14181. Regarding \code{FunRef}, as discussed previously, the function label
  14182. needs to be converted to an address using the \code{leaq}
  14183. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14184. needs to be classified as a complex expression so that we generate an
  14185. assignment statement with a left-hand side that can serve as the
  14186. target of the \code{leaq}.
  14187. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14188. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14189. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14190. and augments programs to include a list of function definitions.
  14191. %
  14192. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14193. \newcommand{\LfunMonadASTRacket}{
  14194. \begin{array}{lcl}
  14195. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14196. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14197. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14198. \end{array}
  14199. }
  14200. \newcommand{\LfunMonadASTPython}{
  14201. \begin{array}{lcl}
  14202. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14203. \MID \key{TupleType}\LS\Type^+\RS\\
  14204. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14205. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14206. \Stmt &::=& \RETURN{\Exp} \\
  14207. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14208. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14209. \end{array}
  14210. }
  14211. \begin{figure}[tp]
  14212. \centering
  14213. \begin{tcolorbox}[colback=white]
  14214. \small
  14215. {\if\edition\racketEd
  14216. \[
  14217. \begin{array}{l}
  14218. \gray{\LvarMonadASTRacket} \\ \hline
  14219. \gray{\LifMonadASTRacket} \\ \hline
  14220. \gray{\LwhileMonadASTRacket} \\ \hline
  14221. \gray{\LtupMonadASTRacket} \\ \hline
  14222. \LfunMonadASTRacket \\
  14223. \begin{array}{rcl}
  14224. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14225. \end{array}
  14226. \end{array}
  14227. \]
  14228. \fi}
  14229. {\if\edition\pythonEd
  14230. \[
  14231. \begin{array}{l}
  14232. \gray{\LvarMonadASTPython} \\ \hline
  14233. \gray{\LifMonadASTPython} \\ \hline
  14234. \gray{\LwhileMonadASTPython} \\ \hline
  14235. \gray{\LtupMonadASTPython} \\ \hline
  14236. \LfunMonadASTPython \\
  14237. \begin{array}{rcl}
  14238. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14239. \end{array}
  14240. \end{array}
  14241. \]
  14242. \fi}
  14243. \end{tcolorbox}
  14244. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14245. \label{fig:Lfun-anf-syntax}
  14246. \end{figure}
  14247. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14248. %% \LangFunANF{} of this pass.
  14249. %% \begin{figure}[tp]
  14250. %% \centering
  14251. %% \fbox{
  14252. %% \begin{minipage}{0.96\textwidth}
  14253. %% \small
  14254. %% \[
  14255. %% \begin{array}{rcl}
  14256. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14257. %% \MID \VOID{} } \\
  14258. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14259. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14260. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14261. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14262. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14263. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14264. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14265. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14266. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14267. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14268. %% \end{array}
  14269. %% \]
  14270. %% \end{minipage}
  14271. %% }
  14272. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14273. %% \label{fig:Lfun-anf-syntax}
  14274. %% \end{figure}
  14275. \section{Explicate Control and the \LangCFun{} language}
  14276. \label{sec:explicate-control-r4}
  14277. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14278. output of \code{explicate\_control}.
  14279. %
  14280. %% \racket{(The concrete syntax is given in
  14281. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14282. %
  14283. The auxiliary functions for assignment\racket{ and tail contexts} should
  14284. be updated with cases for
  14285. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14286. function for predicate context should be updated for
  14287. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14288. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14289. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14290. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14291. auxiliary function for processing function definitions. This code is
  14292. similar to the case for \code{Program} in \LangVec{}. The top-level
  14293. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14294. form of \LangFun{} can then apply this new function to all the
  14295. function definitions.
  14296. {\if\edition\pythonEd
  14297. The translation of \code{Return} statements requires a new auxiliary
  14298. function to handle expressions in tail context, called
  14299. \code{explicate\_tail}. The function should take an expression and the
  14300. dictionary of basic blocks and produce a list of statements in the
  14301. \LangCFun{} language. The \code{explicate\_tail} function should
  14302. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14303. and a default case for other kinds of expressions. The default case
  14304. should produce a \code{Return} statement. The case for \code{Call}
  14305. should change it into \code{TailCall}. The other cases should
  14306. recursively process their subexpressions and statements, choosing the
  14307. appropriate explicate functions for the various contexts.
  14308. \fi}
  14309. \newcommand{\CfunASTRacket}{
  14310. \begin{array}{lcl}
  14311. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14312. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14313. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14314. \end{array}
  14315. }
  14316. \newcommand{\CfunASTPython}{
  14317. \begin{array}{lcl}
  14318. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14319. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14320. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14321. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14322. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14323. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14324. \end{array}
  14325. }
  14326. \begin{figure}[tp]
  14327. \begin{tcolorbox}[colback=white]
  14328. \small
  14329. {\if\edition\racketEd
  14330. \[
  14331. \begin{array}{l}
  14332. \gray{\CvarASTRacket} \\ \hline
  14333. \gray{\CifASTRacket} \\ \hline
  14334. \gray{\CloopASTRacket} \\ \hline
  14335. \gray{\CtupASTRacket} \\ \hline
  14336. \CfunASTRacket \\
  14337. \begin{array}{lcl}
  14338. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14339. \end{array}
  14340. \end{array}
  14341. \]
  14342. \fi}
  14343. {\if\edition\pythonEd
  14344. \[
  14345. \begin{array}{l}
  14346. \gray{\CifASTPython} \\ \hline
  14347. \gray{\CtupASTPython} \\ \hline
  14348. \CfunASTPython \\
  14349. \begin{array}{lcl}
  14350. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14351. \end{array}
  14352. \end{array}
  14353. \]
  14354. \fi}
  14355. \end{tcolorbox}
  14356. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14357. \label{fig:c3-syntax}
  14358. \end{figure}
  14359. \clearpage
  14360. \section{Select Instructions and the \LangXIndCall{} Language}
  14361. \label{sec:select-r4}
  14362. \index{subject}{instruction selection}
  14363. The output of select instructions is a program in the \LangXIndCall{}
  14364. language; the definition of its concrete syntax is shown in
  14365. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14366. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14367. directive on the labels of function definitions to make sure the
  14368. bottom three bits are zero, which we put to use in
  14369. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14370. this section. \index{subject}{x86}
  14371. \newcommand{\GrammarXIndCall}{
  14372. \begin{array}{lcl}
  14373. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14374. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14375. \Block &::= & \Instr^{+} \\
  14376. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14377. \end{array}
  14378. }
  14379. \newcommand{\ASTXIndCallRacket}{
  14380. \begin{array}{lcl}
  14381. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14382. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14383. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14384. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14385. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14386. \end{array}
  14387. }
  14388. \begin{figure}[tp]
  14389. \begin{tcolorbox}[colback=white]
  14390. \small
  14391. \[
  14392. \begin{array}{l}
  14393. \gray{\GrammarXInt} \\ \hline
  14394. \gray{\GrammarXIf} \\ \hline
  14395. \gray{\GrammarXGlobal} \\ \hline
  14396. \GrammarXIndCall \\
  14397. \begin{array}{lcl}
  14398. \LangXIndCallM{} &::= & \Def^{*}
  14399. \end{array}
  14400. \end{array}
  14401. \]
  14402. \end{tcolorbox}
  14403. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14404. \label{fig:x86-3-concrete}
  14405. \end{figure}
  14406. \begin{figure}[tp]
  14407. \begin{tcolorbox}[colback=white]
  14408. \small
  14409. {\if\edition\racketEd
  14410. \[\arraycolsep=3pt
  14411. \begin{array}{l}
  14412. \gray{\ASTXIntRacket} \\ \hline
  14413. \gray{\ASTXIfRacket} \\ \hline
  14414. \gray{\ASTXGlobalRacket} \\ \hline
  14415. \ASTXIndCallRacket \\
  14416. \begin{array}{lcl}
  14417. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14418. \end{array}
  14419. \end{array}
  14420. \]
  14421. \fi}
  14422. {\if\edition\pythonEd
  14423. \[
  14424. \begin{array}{lcl}
  14425. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14426. \MID \BYTEREG{\Reg} } \\
  14427. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14428. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14429. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14430. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14431. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14432. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14433. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14434. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14435. \end{array}
  14436. \]
  14437. \fi}
  14438. \end{tcolorbox}
  14439. \caption{The abstract syntax of \LangXIndCall{} (extends
  14440. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14441. \label{fig:x86-3}
  14442. \end{figure}
  14443. An assignment of a function reference to a variable becomes a
  14444. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14445. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14446. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14447. node, whose concrete syntax is instruction-pointer-relative
  14448. addressing.
  14449. \begin{center}
  14450. \begin{tabular}{lcl}
  14451. \begin{minipage}{0.35\textwidth}
  14452. {\if\edition\racketEd
  14453. \begin{lstlisting}
  14454. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14455. \end{lstlisting}
  14456. \fi}
  14457. {\if\edition\pythonEd
  14458. \begin{lstlisting}
  14459. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14460. \end{lstlisting}
  14461. \fi}
  14462. \end{minipage}
  14463. &
  14464. $\Rightarrow$\qquad\qquad
  14465. &
  14466. \begin{minipage}{0.3\textwidth}
  14467. \begin{lstlisting}
  14468. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14469. \end{lstlisting}
  14470. \end{minipage}
  14471. \end{tabular}
  14472. \end{center}
  14473. Regarding function definitions, we need to remove the parameters and
  14474. instead perform parameter passing using the conventions discussed in
  14475. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14476. registers. We recommend turning the parameters into local variables
  14477. and generating instructions at the beginning of the function to move
  14478. from the argument-passing registers
  14479. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14480. {\if\edition\racketEd
  14481. \begin{lstlisting}
  14482. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14483. |$\Rightarrow$|
  14484. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14485. \end{lstlisting}
  14486. \fi}
  14487. {\if\edition\pythonEd
  14488. \begin{lstlisting}
  14489. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14490. |$\Rightarrow$|
  14491. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14492. \end{lstlisting}
  14493. \fi}
  14494. The basic blocks $B'$ are the same as $B$ except that the
  14495. \code{start} block is modified to add the instructions for moving from
  14496. the argument registers to the parameter variables. So the \code{start}
  14497. block of $B$ shown on the left of the following is changed to the code
  14498. on the right:
  14499. \begin{center}
  14500. \begin{minipage}{0.3\textwidth}
  14501. \begin{lstlisting}
  14502. start:
  14503. |$\itm{instr}_1$|
  14504. |$\cdots$|
  14505. |$\itm{instr}_n$|
  14506. \end{lstlisting}
  14507. \end{minipage}
  14508. $\Rightarrow$
  14509. \begin{minipage}{0.3\textwidth}
  14510. \begin{lstlisting}
  14511. |$f$|start:
  14512. movq %rdi, |$x_1$|
  14513. movq %rsi, |$x_2$|
  14514. |$\cdots$|
  14515. |$\itm{instr}_1$|
  14516. |$\cdots$|
  14517. |$\itm{instr}_n$|
  14518. \end{lstlisting}
  14519. \end{minipage}
  14520. \end{center}
  14521. Recall that we use the label \code{start} for the initial block of a
  14522. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14523. the conclusion of the program with \code{conclusion}, so that
  14524. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14525. by a jump to \code{conclusion}. With the addition of function
  14526. definitions, there is a start block and conclusion for each function,
  14527. but their labels need to be unique. We recommend prepending the
  14528. function's name to \code{start} and \code{conclusion}, respectively,
  14529. to obtain unique labels.
  14530. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14531. number of parameters the function expects, but the parameters are no
  14532. longer in the syntax of function definitions. Instead, add an entry
  14533. to $\itm{info}$ that maps \code{num-params} to the number of
  14534. parameters to construct $\itm{info}'$.}
  14535. By changing the parameters to local variables, we are giving the
  14536. register allocator control over which registers or stack locations to
  14537. use for them. If you implement the move-biasing challenge
  14538. (section~\ref{sec:move-biasing}), the register allocator will try to
  14539. assign the parameter variables to the corresponding argument register,
  14540. in which case the \code{patch\_instructions} pass will remove the
  14541. \code{movq} instruction. This happens in the example translation given
  14542. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14543. the \code{add} function.
  14544. %
  14545. Also, note that the register allocator will perform liveness analysis
  14546. on this sequence of move instructions and build the interference
  14547. graph. So, for example, $x_1$ will be marked as interfering with
  14548. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14549. which is good because otherwise the first \code{movq} would overwrite
  14550. the argument in \code{rsi} that is needed for $x_2$.
  14551. Next, consider the compilation of function calls. In the mirror image
  14552. of the handling of parameters in function definitions, the arguments
  14553. are moved to the argument-passing registers. Note that the function
  14554. is not given as a label, but its address is produced by the argument
  14555. $\itm{arg}_0$. So, we translate the call into an indirect function
  14556. call. The return value from the function is stored in \code{rax}, so
  14557. it needs to be moved into the \itm{lhs}.
  14558. \begin{lstlisting}
  14559. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14560. |$\Rightarrow$|
  14561. movq |$\itm{arg}_1$|, %rdi
  14562. movq |$\itm{arg}_2$|, %rsi
  14563. |$\vdots$|
  14564. callq *|$\itm{arg}_0$|
  14565. movq %rax, |$\itm{lhs}$|
  14566. \end{lstlisting}
  14567. The \code{IndirectCallq} AST node includes an integer for the arity of
  14568. the function, that is, the number of parameters. That information is
  14569. useful in the \code{uncover\_live} pass for determining which
  14570. argument-passing registers are potentially read during the call.
  14571. For tail calls, the parameter passing is the same as non-tail calls:
  14572. generate instructions to move the arguments into the argument-passing
  14573. registers. After that we need to pop the frame from the procedure
  14574. call stack. However, we do not yet know how big the frame is; that
  14575. gets determined during register allocation. So, instead of generating
  14576. those instructions here, we invent a new instruction that means ``pop
  14577. the frame and then do an indirect jump,'' which we name
  14578. \code{TailJmp}. The abstract syntax for this instruction includes an
  14579. argument that specifies where to jump and an integer that represents
  14580. the arity of the function being called.
  14581. \section{Register Allocation}
  14582. \label{sec:register-allocation-r4}
  14583. The addition of functions requires some changes to all three aspects
  14584. of register allocation, which we discuss in the following subsections.
  14585. \subsection{Liveness Analysis}
  14586. \label{sec:liveness-analysis-r4}
  14587. \index{subject}{liveness analysis}
  14588. %% The rest of the passes need only minor modifications to handle the new
  14589. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14590. %% \code{leaq}.
  14591. The \code{IndirectCallq} instruction should be treated like
  14592. \code{Callq} regarding its written locations $W$, in that they should
  14593. include all the caller-saved registers. Recall that the reason for
  14594. that is to force variables that are live across a function call to be assigned to callee-saved
  14595. registers or to be spilled to the stack.
  14596. Regarding the set of read locations $R$, the arity field of
  14597. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14598. argument-passing registers should be considered as read by those
  14599. instructions. Also, the target field of \code{TailJmp} and
  14600. \code{IndirectCallq} should be included in the set of read locations
  14601. $R$.
  14602. \subsection{Build Interference Graph}
  14603. \label{sec:build-interference-r4}
  14604. With the addition of function definitions, we compute a separate interference
  14605. graph for each function (not just one for the whole program).
  14606. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14607. spill tuple-typed variables that are live during a call to
  14608. \code{collect}, the garbage collector. With the addition of functions
  14609. to our language, we need to revisit this issue. Functions that perform
  14610. allocation contain calls to the collector. Thus, we should not only
  14611. spill a tuple-typed variable when it is live during a call to
  14612. \code{collect}, but we should spill the variable if it is live during
  14613. call to any user-defined function. Thus, in the
  14614. \code{build\_interference} pass, we recommend adding interference
  14615. edges between call-live tuple-typed variables and the callee-saved
  14616. registers (in addition to the usual addition of edges between
  14617. call-live variables and the caller-saved registers).
  14618. \subsection{Allocate Registers}
  14619. The primary change to the \code{allocate\_registers} pass is adding an
  14620. auxiliary function for handling definitions (the \Def{} nonterminal
  14621. shown in figure~\ref{fig:x86-3}) with one case for function
  14622. definitions. The logic is the same as described in
  14623. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14624. allocation is performed many times, once for each function definition,
  14625. instead of just once for the whole program.
  14626. \section{Patch Instructions}
  14627. In \code{patch\_instructions}, you should deal with the x86
  14628. idiosyncrasy that the destination argument of \code{leaq} must be a
  14629. register. Additionally, you should ensure that the argument of
  14630. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14631. trample many other registers before the tail call, as explained in the
  14632. next section.
  14633. \section{Prelude and Conclusion}
  14634. Now that register allocation is complete, we can translate the
  14635. \code{TailJmp} into a sequence of instructions. A naive translation of
  14636. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14637. before the jump we need to pop the current frame to achieve efficient
  14638. tail calls. This sequence of instructions is the same as the code for
  14639. the conclusion of a function, except that the \code{retq} is replaced with
  14640. \code{jmp *$\itm{arg}$}.
  14641. Regarding function definitions, we generate a prelude and conclusion
  14642. for each one. This code is similar to the prelude and conclusion
  14643. generated for the \code{main} function presented in
  14644. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14645. carry out the following steps:
  14646. % TODO: .align the functions!
  14647. \begin{enumerate}
  14648. %% \item Start with \code{.global} and \code{.align} directives followed
  14649. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14650. %% example.)
  14651. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14652. pointer.
  14653. \item Push to the stack all the callee-saved registers that were
  14654. used for register allocation.
  14655. \item Move the stack pointer \code{rsp} down to make room for the
  14656. regular spills (aligned to 16 bytes).
  14657. \item Move the root stack pointer \code{r15} up by the size of the
  14658. root-stack frame for this function, which depends on the number of
  14659. spilled tuple-typed variables. \label{root-stack-init}
  14660. \item Initialize to zero all new entries in the root-stack frame.
  14661. \item Jump to the start block.
  14662. \end{enumerate}
  14663. The prelude of the \code{main} function has an additional task: call
  14664. the \code{initialize} function to set up the garbage collector, and
  14665. then move the value of the global \code{rootstack\_begin} in
  14666. \code{r15}. This initialization should happen before step
  14667. \ref{root-stack-init}, which depends on \code{r15}.
  14668. The conclusion of every function should do the following:
  14669. \begin{enumerate}
  14670. \item Move the stack pointer back up past the regular spills.
  14671. \item Restore the callee-saved registers by popping them from the
  14672. stack.
  14673. \item Move the root stack pointer back down by the size of the
  14674. root-stack frame for this function.
  14675. \item Restore \code{rbp} by popping it from the stack.
  14676. \item Return to the caller with the \code{retq} instruction.
  14677. \end{enumerate}
  14678. The output of this pass is \LangXIndCallFlat{}, which differs from
  14679. \LangXIndCall{} in that there is no longer an AST node for function
  14680. definitions. Instead, a program is just an association list of basic
  14681. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14682. \[
  14683. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14684. \]
  14685. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14686. compiling \LangFun{} to x86.
  14687. \begin{exercise}\normalfont\normalsize
  14688. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14689. Create eight new programs that use functions, including examples that
  14690. pass functions and return functions from other functions, recursive
  14691. functions, functions that create vectors, and functions that make tail
  14692. calls. Test your compiler on these new programs and all your
  14693. previously created test programs.
  14694. \end{exercise}
  14695. \begin{figure}[tbp]
  14696. \begin{tcolorbox}[colback=white]
  14697. {\if\edition\racketEd
  14698. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14699. \node (Lfun) at (0,2) {\large \LangFun{}};
  14700. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14701. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14702. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14703. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14704. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14705. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14706. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14707. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14708. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14709. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14710. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14711. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14712. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14713. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14714. \path[->,bend left=15] (Lfun) edge [above] node
  14715. {\ttfamily\footnotesize shrink} (Lfun-1);
  14716. \path[->,bend left=15] (Lfun-1) edge [above] node
  14717. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14718. \path[->,bend left=15] (Lfun-2) edge [above] node
  14719. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14720. \path[->,bend left=15] (F1-1) edge [left] node
  14721. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14722. \path[->,bend left=15] (F1-2) edge [below] node
  14723. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14724. \path[->,bend left=15] (F1-3) edge [below] node
  14725. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14726. \path[->,bend right=15] (F1-4) edge [above] node
  14727. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14728. \path[->,bend right=15] (F1-5) edge [right] node
  14729. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14730. \path[->,bend right=15] (C3-2) edge [right] node
  14731. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14732. \path[->,bend left=15] (x86-2) edge [right] node
  14733. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14734. \path[->,bend right=15] (x86-2-1) edge [below] node
  14735. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14736. \path[->,bend right=15] (x86-2-2) edge [right] node
  14737. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14738. \path[->,bend left=15] (x86-3) edge [above] node
  14739. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14740. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14741. \end{tikzpicture}
  14742. \fi}
  14743. {\if\edition\pythonEd
  14744. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14745. \node (Lfun) at (0,2) {\large \LangFun{}};
  14746. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14747. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14748. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14749. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14750. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14751. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14752. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14753. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14754. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14755. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14756. \path[->,bend left=15] (Lfun) edge [above] node
  14757. {\ttfamily\footnotesize shrink} (Lfun-2);
  14758. \path[->,bend left=15] (Lfun-2) edge [above] node
  14759. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14760. \path[->,bend left=15] (F1-1) edge [above] node
  14761. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14762. \path[->,bend left=15] (F1-2) edge [right] node
  14763. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14764. \path[->,bend right=15] (F1-4) edge [above] node
  14765. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14766. \path[->,bend right=15] (F1-5) edge [right] node
  14767. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14768. \path[->,bend left=15] (C3-2) edge [right] node
  14769. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14770. \path[->,bend right=15] (x86-2) edge [below] node
  14771. {\ttfamily\footnotesize assign\_homes} (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 [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14775. \end{tikzpicture}
  14776. \fi}
  14777. \end{tcolorbox}
  14778. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14779. \label{fig:Lfun-passes}
  14780. \end{figure}
  14781. \section{An Example Translation}
  14782. \label{sec:functions-example}
  14783. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14784. function in \LangFun{} to x86. The figure also includes the results of the
  14785. \code{explicate\_control} and \code{select\_instructions} passes.
  14786. \begin{figure}[htbp]
  14787. \begin{tcolorbox}[colback=white]
  14788. \begin{tabular}{ll}
  14789. \begin{minipage}{0.4\textwidth}
  14790. % s3_2.rkt
  14791. {\if\edition\racketEd
  14792. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14793. (define (add [x : Integer]
  14794. [y : Integer])
  14795. : Integer
  14796. (+ x y))
  14797. (add 40 2)
  14798. \end{lstlisting}
  14799. \fi}
  14800. {\if\edition\pythonEd
  14801. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14802. def add(x:int, y:int) -> int:
  14803. return x + y
  14804. print(add(40, 2))
  14805. \end{lstlisting}
  14806. \fi}
  14807. $\Downarrow$
  14808. {\if\edition\racketEd
  14809. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14810. (define (add86 [x87 : Integer]
  14811. [y88 : Integer])
  14812. : Integer
  14813. add86start:
  14814. return (+ x87 y88);
  14815. )
  14816. (define (main) : Integer ()
  14817. mainstart:
  14818. tmp89 = (fun-ref add86 2);
  14819. (tail-call tmp89 40 2)
  14820. )
  14821. \end{lstlisting}
  14822. \fi}
  14823. {\if\edition\pythonEd
  14824. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14825. def add(x:int, y:int) -> int:
  14826. addstart:
  14827. return x + y
  14828. def main() -> int:
  14829. mainstart:
  14830. fun.0 = add
  14831. tmp.1 = fun.0(40, 2)
  14832. print(tmp.1)
  14833. return 0
  14834. \end{lstlisting}
  14835. \fi}
  14836. \end{minipage}
  14837. &
  14838. $\Rightarrow$
  14839. \begin{minipage}{0.5\textwidth}
  14840. {\if\edition\racketEd
  14841. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14842. (define (add86) : Integer
  14843. add86start:
  14844. movq %rdi, x87
  14845. movq %rsi, y88
  14846. movq x87, %rax
  14847. addq y88, %rax
  14848. jmp inc1389conclusion
  14849. )
  14850. (define (main) : Integer
  14851. mainstart:
  14852. leaq (fun-ref add86 2), tmp89
  14853. movq $40, %rdi
  14854. movq $2, %rsi
  14855. tail-jmp tmp89
  14856. )
  14857. \end{lstlisting}
  14858. \fi}
  14859. {\if\edition\pythonEd
  14860. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14861. def add() -> int:
  14862. addstart:
  14863. movq %rdi, x
  14864. movq %rsi, y
  14865. movq x, %rax
  14866. addq y, %rax
  14867. jmp addconclusion
  14868. def main() -> int:
  14869. mainstart:
  14870. leaq add, fun.0
  14871. movq $40, %rdi
  14872. movq $2, %rsi
  14873. callq *fun.0
  14874. movq %rax, tmp.1
  14875. movq tmp.1, %rdi
  14876. callq print_int
  14877. movq $0, %rax
  14878. jmp mainconclusion
  14879. \end{lstlisting}
  14880. \fi}
  14881. $\Downarrow$
  14882. \end{minipage}
  14883. \end{tabular}
  14884. \begin{tabular}{ll}
  14885. \begin{minipage}{0.3\textwidth}
  14886. {\if\edition\racketEd
  14887. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14888. .globl add86
  14889. .align 8
  14890. add86:
  14891. pushq %rbp
  14892. movq %rsp, %rbp
  14893. jmp add86start
  14894. add86start:
  14895. movq %rdi, %rax
  14896. addq %rsi, %rax
  14897. jmp add86conclusion
  14898. add86conclusion:
  14899. popq %rbp
  14900. retq
  14901. \end{lstlisting}
  14902. \fi}
  14903. {\if\edition\pythonEd
  14904. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14905. .align 8
  14906. add:
  14907. pushq %rbp
  14908. movq %rsp, %rbp
  14909. subq $0, %rsp
  14910. jmp addstart
  14911. addstart:
  14912. movq %rdi, %rdx
  14913. movq %rsi, %rcx
  14914. movq %rdx, %rax
  14915. addq %rcx, %rax
  14916. jmp addconclusion
  14917. addconclusion:
  14918. subq $0, %r15
  14919. addq $0, %rsp
  14920. popq %rbp
  14921. retq
  14922. \end{lstlisting}
  14923. \fi}
  14924. \end{minipage}
  14925. &
  14926. \begin{minipage}{0.5\textwidth}
  14927. {\if\edition\racketEd
  14928. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14929. .globl main
  14930. .align 8
  14931. main:
  14932. pushq %rbp
  14933. movq %rsp, %rbp
  14934. movq $16384, %rdi
  14935. movq $16384, %rsi
  14936. callq initialize
  14937. movq rootstack_begin(%rip), %r15
  14938. jmp mainstart
  14939. mainstart:
  14940. leaq add86(%rip), %rcx
  14941. movq $40, %rdi
  14942. movq $2, %rsi
  14943. movq %rcx, %rax
  14944. popq %rbp
  14945. jmp *%rax
  14946. mainconclusion:
  14947. popq %rbp
  14948. retq
  14949. \end{lstlisting}
  14950. \fi}
  14951. {\if\edition\pythonEd
  14952. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14953. .globl main
  14954. .align 8
  14955. main:
  14956. pushq %rbp
  14957. movq %rsp, %rbp
  14958. subq $0, %rsp
  14959. movq $65536, %rdi
  14960. movq $65536, %rsi
  14961. callq initialize
  14962. movq rootstack_begin(%rip), %r15
  14963. jmp mainstart
  14964. mainstart:
  14965. leaq add(%rip), %rcx
  14966. movq $40, %rdi
  14967. movq $2, %rsi
  14968. callq *%rcx
  14969. movq %rax, %rcx
  14970. movq %rcx, %rdi
  14971. callq print_int
  14972. movq $0, %rax
  14973. jmp mainconclusion
  14974. mainconclusion:
  14975. subq $0, %r15
  14976. addq $0, %rsp
  14977. popq %rbp
  14978. retq
  14979. \end{lstlisting}
  14980. \fi}
  14981. \end{minipage}
  14982. \end{tabular}
  14983. \end{tcolorbox}
  14984. \caption{Example compilation of a simple function to x86.}
  14985. \label{fig:add-fun}
  14986. \end{figure}
  14987. % Challenge idea: inlining! (simple version)
  14988. % Further Reading
  14989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14990. \chapter{Lexically Scoped Functions}
  14991. \label{ch:Llambda}
  14992. \index{subject}{lambda}
  14993. \index{subject}{lexical scoping}
  14994. \setcounter{footnote}{0}
  14995. This chapter studies lexically scoped functions. Lexical scoping means
  14996. that a function's body may refer to variables whose binding site is
  14997. outside of the function, in an enclosing scope.
  14998. %
  14999. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15000. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  15001. creating lexically scoped functions. The body of the \key{lambda}
  15002. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  15003. binding sites for \code{x} and \code{y} are outside of the
  15004. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  15005. \key{let}}\python{a local variable of function \code{f}}, and
  15006. \code{x} is a parameter of function \code{f}. Note that function
  15007. \code{f} returns the \key{lambda} as its result value. The main
  15008. expression of the program includes two calls to \code{f} with
  15009. different arguments for \code{x}: first \code{5} and then \code{3}. The
  15010. functions returned from \code{f} are bound to variables \code{g} and
  15011. \code{h}. Even though these two functions were created by the same
  15012. \code{lambda}, they are really different functions because they use
  15013. different values for \code{x}. Applying \code{g} to \code{11} produces
  15014. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  15015. so the result of the program is \code{42}.
  15016. \begin{figure}[btp]
  15017. \begin{tcolorbox}[colback=white]
  15018. {\if\edition\racketEd
  15019. % lambda_test_21.rkt
  15020. \begin{lstlisting}
  15021. (define (f [x : Integer]) : (Integer -> Integer)
  15022. (let ([y 4])
  15023. (lambda: ([z : Integer]) : Integer
  15024. (+ x (+ y z)))))
  15025. (let ([g (f 5)])
  15026. (let ([h (f 3)])
  15027. (+ (g 11) (h 15))))
  15028. \end{lstlisting}
  15029. \fi}
  15030. {\if\edition\pythonEd
  15031. \begin{lstlisting}
  15032. def f(x : int) -> Callable[[int], int]:
  15033. y = 4
  15034. return lambda z: x + y + z
  15035. g = f(5)
  15036. h = f(3)
  15037. print( g(11) + h(15) )
  15038. \end{lstlisting}
  15039. \fi}
  15040. \end{tcolorbox}
  15041. \caption{Example of a lexically scoped function.}
  15042. \label{fig:lexical-scoping}
  15043. \end{figure}
  15044. The approach that we take for implementing lexically scoped functions
  15045. is to compile them into top-level function definitions, translating
  15046. from \LangLam{} into \LangFun{}. However, the compiler must give
  15047. special treatment to variable occurrences such as \code{x} and
  15048. \code{y} in the body of the \code{lambda} shown in
  15049. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15050. may not refer to variables defined outside of it. To identify such
  15051. variable occurrences, we review the standard notion of free variable.
  15052. \begin{definition}\normalfont
  15053. A variable is \emph{free in expression} $e$ if the variable occurs
  15054. inside $e$ but does not have an enclosing definition that is also in
  15055. $e$.\index{subject}{free variable}
  15056. \end{definition}
  15057. For example, in the expression
  15058. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15059. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15060. only \code{x} and \code{y} are free in the following expression,
  15061. because \code{z} is defined by the \code{lambda}
  15062. {\if\edition\racketEd
  15063. \begin{lstlisting}
  15064. (lambda: ([z : Integer]) : Integer
  15065. (+ x (+ y z)))
  15066. \end{lstlisting}
  15067. \fi}
  15068. {\if\edition\pythonEd
  15069. \begin{lstlisting}
  15070. lambda z: x + y + z
  15071. \end{lstlisting}
  15072. \fi}
  15073. %
  15074. \noindent Thus the free variables of a \code{lambda} are the ones that
  15075. need special treatment. We need to transport at runtime the values
  15076. of those variables from the point where the \code{lambda} was created
  15077. to the point where the \code{lambda} is applied. An efficient solution
  15078. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15079. values of the free variables together with a function pointer into a
  15080. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15081. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15082. closure}
  15083. %
  15084. By design, we have all the ingredients to make closures:
  15085. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15086. function pointers. The function pointer resides at index $0$, and the
  15087. values for the free variables fill in the rest of the tuple.
  15088. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15089. to see how closures work. It is a three-step dance. The program calls
  15090. function \code{f}, which creates a closure for the \code{lambda}. The
  15091. closure is a tuple whose first element is a pointer to the top-level
  15092. function that we will generate for the \code{lambda}; the second
  15093. element is the value of \code{x}, which is \code{5}; and the third
  15094. element is \code{4}, the value of \code{y}. The closure does not
  15095. contain an element for \code{z} because \code{z} is not a free
  15096. variable of the \code{lambda}. Creating the closure is step 1 of the
  15097. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15098. shown in figure~\ref{fig:closures}.
  15099. %
  15100. The second call to \code{f} creates another closure, this time with
  15101. \code{3} in the second slot (for \code{x}). This closure is also
  15102. returned from \code{f} but bound to \code{h}, which is also shown in
  15103. figure~\ref{fig:closures}.
  15104. \begin{figure}[tbp]
  15105. \centering
  15106. \begin{minipage}{0.65\textwidth}
  15107. \begin{tcolorbox}[colback=white]
  15108. \includegraphics[width=\textwidth]{figs/closures}
  15109. \end{tcolorbox}
  15110. \end{minipage}
  15111. \caption{Flat closure representations for the two functions
  15112. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15113. \label{fig:closures}
  15114. \end{figure}
  15115. Continuing with the example, consider the application of \code{g} to
  15116. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15117. closure, we obtain the function pointer from the first element of the
  15118. closure and call it, passing in the closure itself and then the
  15119. regular arguments, in this case \code{11}. This technique for applying
  15120. a closure is step 2 of the dance.
  15121. %
  15122. But doesn't this \code{lambda} take only one argument, for parameter
  15123. \code{z}? The third and final step of the dance is generating a
  15124. top-level function for a \code{lambda}. We add an additional
  15125. parameter for the closure and insert an initialization at the beginning
  15126. of the function for each free variable, to bind those variables to the
  15127. appropriate elements from the closure parameter.
  15128. %
  15129. This three-step dance is known as \emph{closure conversion}. We
  15130. discuss the details of closure conversion in
  15131. section~\ref{sec:closure-conversion} and show the code generated from
  15132. the example in section~\ref{sec:example-lambda}. First, we define
  15133. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  15134. \section{The \LangLam{} Language}
  15135. \label{sec:r5}
  15136. The definitions of the concrete syntax and abstract syntax for
  15137. \LangLam{}, a language with anonymous functions and lexical scoping,
  15138. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15139. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15140. for \LangFun{}, which already has syntax for function application.
  15141. %
  15142. \python{The syntax also includes an assignment statement that includes
  15143. a type annotation for the variable on the left-hand side, which
  15144. facilitates the type checking of \code{lambda} expressions that we
  15145. discuss later in this section.}
  15146. %
  15147. \racket{The \code{procedure-arity} operation returns the number of parameters
  15148. of a given function, an operation that we need for the translation
  15149. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15150. %
  15151. \python{The \code{arity} operation returns the number of parameters of
  15152. a given function, an operation that we need for the translation
  15153. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15154. The \code{arity} operation is not in Python, but the same functionality
  15155. is available in a more complex form. We include \code{arity} in the
  15156. \LangLam{} source language to enable testing.}
  15157. \newcommand{\LlambdaGrammarRacket}{
  15158. \begin{array}{lcl}
  15159. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15160. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15161. \end{array}
  15162. }
  15163. \newcommand{\LlambdaASTRacket}{
  15164. \begin{array}{lcl}
  15165. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15166. \itm{op} &::=& \code{procedure-arity}
  15167. \end{array}
  15168. }
  15169. \newcommand{\LlambdaGrammarPython}{
  15170. \begin{array}{lcl}
  15171. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15172. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15173. \end{array}
  15174. }
  15175. \newcommand{\LlambdaASTPython}{
  15176. \begin{array}{lcl}
  15177. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15178. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15179. \end{array}
  15180. }
  15181. % include AnnAssign in ASTPython
  15182. \begin{figure}[tp]
  15183. \centering
  15184. \begin{tcolorbox}[colback=white]
  15185. \small
  15186. {\if\edition\racketEd
  15187. \[
  15188. \begin{array}{l}
  15189. \gray{\LintGrammarRacket{}} \\ \hline
  15190. \gray{\LvarGrammarRacket{}} \\ \hline
  15191. \gray{\LifGrammarRacket{}} \\ \hline
  15192. \gray{\LwhileGrammarRacket} \\ \hline
  15193. \gray{\LtupGrammarRacket} \\ \hline
  15194. \gray{\LfunGrammarRacket} \\ \hline
  15195. \LlambdaGrammarRacket \\
  15196. \begin{array}{lcl}
  15197. \LangLamM{} &::=& \Def\ldots \; \Exp
  15198. \end{array}
  15199. \end{array}
  15200. \]
  15201. \fi}
  15202. {\if\edition\pythonEd
  15203. \[
  15204. \begin{array}{l}
  15205. \gray{\LintGrammarPython{}} \\ \hline
  15206. \gray{\LvarGrammarPython{}} \\ \hline
  15207. \gray{\LifGrammarPython{}} \\ \hline
  15208. \gray{\LwhileGrammarPython} \\ \hline
  15209. \gray{\LtupGrammarPython} \\ \hline
  15210. \gray{\LfunGrammarPython} \\ \hline
  15211. \LlambdaGrammarPython \\
  15212. \begin{array}{lcl}
  15213. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15214. \end{array}
  15215. \end{array}
  15216. \]
  15217. \fi}
  15218. \end{tcolorbox}
  15219. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15220. with \key{lambda}.}
  15221. \label{fig:Llam-concrete-syntax}
  15222. \end{figure}
  15223. \begin{figure}[tp]
  15224. \centering
  15225. \begin{tcolorbox}[colback=white]
  15226. \small
  15227. {\if\edition\racketEd
  15228. \[\arraycolsep=3pt
  15229. \begin{array}{l}
  15230. \gray{\LintOpAST} \\ \hline
  15231. \gray{\LvarASTRacket{}} \\ \hline
  15232. \gray{\LifASTRacket{}} \\ \hline
  15233. \gray{\LwhileASTRacket{}} \\ \hline
  15234. \gray{\LtupASTRacket{}} \\ \hline
  15235. \gray{\LfunASTRacket} \\ \hline
  15236. \LlambdaASTRacket \\
  15237. \begin{array}{lcl}
  15238. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15239. \end{array}
  15240. \end{array}
  15241. \]
  15242. \fi}
  15243. {\if\edition\pythonEd
  15244. \[
  15245. \begin{array}{l}
  15246. \gray{\LintASTPython} \\ \hline
  15247. \gray{\LvarASTPython{}} \\ \hline
  15248. \gray{\LifASTPython{}} \\ \hline
  15249. \gray{\LwhileASTPython{}} \\ \hline
  15250. \gray{\LtupASTPython{}} \\ \hline
  15251. \gray{\LfunASTPython} \\ \hline
  15252. \LlambdaASTPython \\
  15253. \begin{array}{lcl}
  15254. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15255. \end{array}
  15256. \end{array}
  15257. \]
  15258. \fi}
  15259. \end{tcolorbox}
  15260. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15261. \label{fig:Llam-syntax}
  15262. \end{figure}
  15263. \index{subject}{interpreter}
  15264. \label{sec:interp-Llambda}
  15265. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  15266. \LangLam{}. The case for \key{Lambda} saves the current environment
  15267. inside the returned function value. Recall that during function
  15268. application, the environment stored in the function value, extended
  15269. with the mapping of parameters to argument values, is used to
  15270. interpret the body of the function.
  15271. \begin{figure}[tbp]
  15272. \begin{tcolorbox}[colback=white]
  15273. {\if\edition\racketEd
  15274. \begin{lstlisting}
  15275. (define interp-Llambda-class
  15276. (class interp-Lfun-class
  15277. (super-new)
  15278. (define/override (interp-op op)
  15279. (match op
  15280. ['procedure-arity
  15281. (lambda (v)
  15282. (match v
  15283. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15284. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15285. [else (super interp-op op)]))
  15286. (define/override ((interp-exp env) e)
  15287. (define recur (interp-exp env))
  15288. (match e
  15289. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15290. `(function ,xs ,body ,env)]
  15291. [else ((super interp-exp env) e)]))
  15292. ))
  15293. (define (interp-Llambda p)
  15294. (send (new interp-Llambda-class) interp-program p))
  15295. \end{lstlisting}
  15296. \fi}
  15297. {\if\edition\pythonEd
  15298. \begin{lstlisting}
  15299. class InterpLlambda(InterpLfun):
  15300. def arity(self, v):
  15301. match v:
  15302. case Function(name, params, body, env):
  15303. return len(params)
  15304. case _:
  15305. raise Exception('Llambda arity unexpected ' + repr(v))
  15306. def interp_exp(self, e, env):
  15307. match e:
  15308. case Call(Name('arity'), [fun]):
  15309. f = self.interp_exp(fun, env)
  15310. return self.arity(f)
  15311. case Lambda(params, body):
  15312. return Function('lambda', params, [Return(body)], env)
  15313. case _:
  15314. return super().interp_exp(e, env)
  15315. def interp_stmts(self, ss, env):
  15316. if len(ss) == 0:
  15317. return
  15318. match ss[0]:
  15319. case AnnAssign(lhs, typ, value, simple):
  15320. env[lhs.id] = self.interp_exp(value, env)
  15321. return self.interp_stmts(ss[1:], env)
  15322. case _:
  15323. return super().interp_stmts(ss, env)
  15324. \end{lstlisting}
  15325. \fi}
  15326. \end{tcolorbox}
  15327. \caption{Interpreter for \LangLam{}.}
  15328. \label{fig:interp-Llambda}
  15329. \end{figure}
  15330. \label{sec:type-check-r5}
  15331. \index{subject}{type checking}
  15332. {\if\edition\racketEd
  15333. %
  15334. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15335. \key{lambda} form. The body of the \key{lambda} is checked in an
  15336. environment that includes the current environment (because it is
  15337. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15338. require the body's type to match the declared return type.
  15339. %
  15340. \fi}
  15341. {\if\edition\pythonEd
  15342. %
  15343. Figures~\ref{fig:type-check-Llambda} and
  15344. \ref{fig:type-check-Llambda-part2} define the type checker for
  15345. \LangLam{}, which is more complex than one might expect. The reason
  15346. for the added complexity is that the syntax of \key{lambda} does not
  15347. include type annotations for the parameters or return type. Instead
  15348. they must be inferred. There are many approaches of type inference to
  15349. choose from of varying degrees of complexity. We choose one of the
  15350. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15351. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15352. this book is compilation, not type inference.
  15353. The main idea of bidirectional type inference is to add an auxiliary
  15354. function, here named \code{check\_exp}, that takes an expected type
  15355. and checks whether the given expression is of that type. Thus, in
  15356. \code{check\_exp}, type information flows in a top-down manner with
  15357. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15358. function, where type information flows in a primarily bottom-up
  15359. manner.
  15360. %
  15361. The idea then is to use \code{check\_exp} in all the places where we
  15362. already know what the type of an expression should be, such as in the
  15363. \code{return} statement of a top-level function definition, or on the
  15364. right-hand side of an annotated assignment statement.
  15365. Getting back to \code{lambda}, it is straightforward to check a
  15366. \code{lambda} inside \code{check\_exp} because the expected type
  15367. provides the parameter types and the return type. On the other hand,
  15368. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15369. that we do not allow \code{lambda} in contexts where we don't already
  15370. know its type. This restriction does not incur a loss of
  15371. expressiveness for \LangLam{} because it is straightforward to modify
  15372. a program to sidestep the restriction, for example, by using an
  15373. annotated assignment statement to assign the \code{lambda} to a
  15374. temporary variable.
  15375. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15376. checker records their type in a \code{has\_type} field. This type
  15377. information is used later in this chapter.
  15378. %
  15379. \fi}
  15380. \begin{figure}[tbp]
  15381. \begin{tcolorbox}[colback=white]
  15382. {\if\edition\racketEd
  15383. \begin{lstlisting}
  15384. (define (type-check-Llambda env)
  15385. (lambda (e)
  15386. (match e
  15387. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15388. (define-values (new-body bodyT)
  15389. ((type-check-exp (append (map cons xs Ts) env)) body))
  15390. (define ty `(,@Ts -> ,rT))
  15391. (cond
  15392. [(equal? rT bodyT)
  15393. (values (HasType (Lambda params rT new-body) ty) ty)]
  15394. [else
  15395. (error "mismatch in return type" bodyT rT)])]
  15396. ...
  15397. )))
  15398. \end{lstlisting}
  15399. \fi}
  15400. {\if\edition\pythonEd
  15401. \begin{lstlisting}
  15402. class TypeCheckLlambda(TypeCheckLfun):
  15403. def type_check_exp(self, e, env):
  15404. match e:
  15405. case Name(id):
  15406. e.has_type = env[id]
  15407. return env[id]
  15408. case Lambda(params, body):
  15409. raise Exception('cannot synthesize a type for a lambda')
  15410. case Call(Name('arity'), [func]):
  15411. func_t = self.type_check_exp(func, env)
  15412. match func_t:
  15413. case FunctionType(params_t, return_t):
  15414. return IntType()
  15415. case _:
  15416. raise Exception('in arity, unexpected ' + repr(func_t))
  15417. case _:
  15418. return super().type_check_exp(e, env)
  15419. def check_exp(self, e, ty, env):
  15420. match e:
  15421. case Lambda(params, body):
  15422. e.has_type = ty
  15423. match ty:
  15424. case FunctionType(params_t, return_t):
  15425. new_env = env.copy().update(zip(params, params_t))
  15426. self.check_exp(body, return_t, new_env)
  15427. case _:
  15428. raise Exception('lambda does not have type ' + str(ty))
  15429. case Call(func, args):
  15430. func_t = self.type_check_exp(func, env)
  15431. match func_t:
  15432. case FunctionType(params_t, return_t):
  15433. for (arg, param_t) in zip(args, params_t):
  15434. self.check_exp(arg, param_t, env)
  15435. self.check_type_equal(return_t, ty, e)
  15436. case _:
  15437. raise Exception('type_check_exp: in call, unexpected ' + \
  15438. repr(func_t))
  15439. case _:
  15440. t = self.type_check_exp(e, env)
  15441. self.check_type_equal(t, ty, e)
  15442. \end{lstlisting}
  15443. \fi}
  15444. \end{tcolorbox}
  15445. \caption{Type checking \LangLam{}\python{, part 1}.}
  15446. \label{fig:type-check-Llambda}
  15447. \end{figure}
  15448. {\if\edition\pythonEd
  15449. \begin{figure}[tbp]
  15450. \begin{tcolorbox}[colback=white]
  15451. \begin{lstlisting}
  15452. def check_stmts(self, ss, return_ty, env):
  15453. if len(ss) == 0:
  15454. return
  15455. match ss[0]:
  15456. case FunctionDef(name, params, body, dl, returns, comment):
  15457. new_env = env.copy().update(params)
  15458. rt = self.check_stmts(body, returns, new_env)
  15459. self.check_stmts(ss[1:], return_ty, env)
  15460. case Return(value):
  15461. self.check_exp(value, return_ty, env)
  15462. case Assign([Name(id)], value):
  15463. if id in env:
  15464. self.check_exp(value, env[id], env)
  15465. else:
  15466. env[id] = self.type_check_exp(value, env)
  15467. self.check_stmts(ss[1:], return_ty, env)
  15468. case Assign([Subscript(tup, Constant(index), Store())], value):
  15469. tup_t = self.type_check_exp(tup, env)
  15470. match tup_t:
  15471. case TupleType(ts):
  15472. self.check_exp(value, ts[index], env)
  15473. case _:
  15474. raise Exception('expected a tuple, not ' + repr(tup_t))
  15475. self.check_stmts(ss[1:], return_ty, env)
  15476. case AnnAssign(Name(id), ty_annot, value, simple):
  15477. ss[0].annotation = ty_annot
  15478. if id in env:
  15479. self.check_type_equal(env[id], ty_annot)
  15480. else:
  15481. env[id] = ty_annot
  15482. self.check_exp(value, ty_annot, env)
  15483. self.check_stmts(ss[1:], return_ty, env)
  15484. case _:
  15485. self.type_check_stmts(ss, env)
  15486. def type_check(self, p):
  15487. match p:
  15488. case Module(body):
  15489. env = {}
  15490. for s in body:
  15491. match s:
  15492. case FunctionDef(name, params, bod, dl, returns, comment):
  15493. params_t = [t for (x,t) in params]
  15494. env[name] = FunctionType(params_t, returns)
  15495. self.check_stmts(body, int, env)
  15496. \end{lstlisting}
  15497. \end{tcolorbox}
  15498. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15499. \label{fig:type-check-Llambda-part2}
  15500. \end{figure}
  15501. \fi}
  15502. \clearpage
  15503. \section{Assignment and Lexically Scoped Functions}
  15504. \label{sec:assignment-scoping}
  15505. The combination of lexically scoped functions and assignment to
  15506. variables raises a challenge with the flat-closure approach to
  15507. implementing lexically scoped functions. Consider the following
  15508. example in which function \code{f} has a free variable \code{x} that
  15509. is changed after \code{f} is created but before the call to \code{f}.
  15510. % loop_test_11.rkt
  15511. {\if\edition\racketEd
  15512. \begin{lstlisting}
  15513. (let ([x 0])
  15514. (let ([y 0])
  15515. (let ([z 20])
  15516. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15517. (begin
  15518. (set! x 10)
  15519. (set! y 12)
  15520. (f y))))))
  15521. \end{lstlisting}
  15522. \fi}
  15523. {\if\edition\pythonEd
  15524. % box_free_assign.py
  15525. \begin{lstlisting}
  15526. def g(z : int) -> int:
  15527. x = 0
  15528. y = 0
  15529. f : Callable[[int],int] = lambda a: a + x + z
  15530. x = 10
  15531. y = 12
  15532. return f(y)
  15533. print( g(20) )
  15534. \end{lstlisting}
  15535. \fi} The correct output for this example is \code{42} because the call
  15536. to \code{f} is required to use the current value of \code{x} (which is
  15537. \code{10}). Unfortunately, the closure conversion pass
  15538. (section~\ref{sec:closure-conversion}) generates code for the
  15539. \code{lambda} that copies the old value of \code{x} into a
  15540. closure. Thus, if we naively applied closure conversion, the output of
  15541. this program would be \code{32}.
  15542. A first attempt at solving this problem would be to save a pointer to
  15543. \code{x} in the closure and change the occurrences of \code{x} inside
  15544. the lambda to dereference the pointer. Of course, this would require
  15545. assigning \code{x} to the stack and not to a register. However, the
  15546. problem goes a bit deeper.
  15547. Consider the following example that returns a function that refers to
  15548. a local variable of the enclosing function:
  15549. \begin{center}
  15550. \begin{minipage}{\textwidth}
  15551. {\if\edition\racketEd
  15552. \begin{lstlisting}
  15553. (define (f []) : Integer
  15554. (let ([x 0])
  15555. (let ([g (lambda: () : Integer x)])
  15556. (begin
  15557. (set! x 42)
  15558. g))))
  15559. ((f))
  15560. \end{lstlisting}
  15561. \fi}
  15562. {\if\edition\pythonEd
  15563. % counter.py
  15564. \begin{lstlisting}
  15565. def f():
  15566. x = 0
  15567. g = lambda: x
  15568. x = 42
  15569. return g
  15570. print( f()() )
  15571. \end{lstlisting}
  15572. \fi}
  15573. \end{minipage}
  15574. \end{center}
  15575. In this example, the lifetime of \code{x} extends beyond the lifetime
  15576. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15577. stack frame for the call to \code{f}, it would be gone by the time we
  15578. called \code{g}, leaving us with dangling pointers for
  15579. \code{x}. This example demonstrates that when a variable occurs free
  15580. inside a function, its lifetime becomes indefinite. Thus, the value of
  15581. the variable needs to live on the heap. The verb
  15582. \emph{box}\index{subject}{box} is often used for allocating a single
  15583. value on the heap, producing a pointer, and
  15584. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15585. %
  15586. We introduce a new pass named \code{convert\_assignments} to address
  15587. this challenge.
  15588. %
  15589. \python{But before diving into that, we have one more
  15590. problem to discuss.}
  15591. \if\edition\pythonEd
  15592. \section{Uniquify Variables}
  15593. \label{sec:uniquify-lambda}
  15594. With the addition of \code{lambda} we have a complication to deal
  15595. with: name shadowing. Consider the following program with a function
  15596. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15597. \code{lambda} expressions. The first \code{lambda} has a parameter
  15598. that is also named \code{x}.
  15599. \begin{lstlisting}
  15600. def f(x:int, y:int) -> Callable[[int], int]:
  15601. g : Callable[[int],int] = (lambda x: x + y)
  15602. h : Callable[[int],int] = (lambda y: x + y)
  15603. x = input_int()
  15604. return g
  15605. print(f(0, 10)(32))
  15606. \end{lstlisting}
  15607. Many of our compiler passes rely on being able to connect variable
  15608. uses with their definitions using just the name of the variable,
  15609. including new passes in this chapter. However, in the above example
  15610. the name of the variable does not uniquely determine its
  15611. definition. To solve this problem we recommend implementing a pass
  15612. named \code{uniquify} that renames every variable in the program to
  15613. make sure they are all unique.
  15614. The following shows the result of \code{uniquify} for the above
  15615. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15616. and the \code{x} parameter of the \code{lambda} is renamed to
  15617. \code{x\_4}.
  15618. \begin{lstlisting}
  15619. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15620. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15621. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15622. x_0 = input_int()
  15623. return g_2
  15624. def main() -> int :
  15625. print(f(0, 10)(32))
  15626. return 0
  15627. \end{lstlisting}
  15628. \fi
  15629. %% \section{Reveal Functions}
  15630. %% \label{sec:reveal-functions-r5}
  15631. %% \racket{To support the \code{procedure-arity} operator we need to
  15632. %% communicate the arity of a function to the point of closure
  15633. %% creation.}
  15634. %% %
  15635. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15636. %% function at runtime. Thus, we need to communicate the arity of a
  15637. %% function to the point of closure creation.}
  15638. %% %
  15639. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15640. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15641. %% \[
  15642. %% \begin{array}{lcl}
  15643. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15644. %% \end{array}
  15645. %% \]
  15646. \section{Assignment Conversion}
  15647. \label{sec:convert-assignments}
  15648. The purpose of the \code{convert\_assignments} pass is to address the
  15649. challenge regarding the interaction between variable assignments and
  15650. closure conversion. First we identify which variables need to be
  15651. boxed, and then we transform the program to box those variables. In
  15652. general, boxing introduces runtime overhead that we would like to
  15653. avoid, so we should box as few variables as possible. We recommend
  15654. boxing the variables in the intersection of the following two sets of
  15655. variables:
  15656. \begin{enumerate}
  15657. \item The variables that are free in a \code{lambda}.
  15658. \item The variables that appear on the left-hand side of an
  15659. assignment.
  15660. \end{enumerate}
  15661. The first condition is a must but the second condition is
  15662. conservative. It is possible to develop a more liberal condition using
  15663. static program analysis.
  15664. Consider again the first example from
  15665. section~\ref{sec:assignment-scoping}:
  15666. %
  15667. {\if\edition\racketEd
  15668. \begin{lstlisting}
  15669. (let ([x 0])
  15670. (let ([y 0])
  15671. (let ([z 20])
  15672. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15673. (begin
  15674. (set! x 10)
  15675. (set! y 12)
  15676. (f y))))))
  15677. \end{lstlisting}
  15678. \fi}
  15679. {\if\edition\pythonEd
  15680. \begin{lstlisting}
  15681. def g(z : int) -> int:
  15682. x = 0
  15683. y = 0
  15684. f : Callable[[int],int] = lambda a: a + x + z
  15685. x = 10
  15686. y = 12
  15687. return f(y)
  15688. print( g(20) )
  15689. \end{lstlisting}
  15690. \fi}
  15691. %
  15692. \noindent The variables \code{x} and \code{y} are assigned to. The
  15693. variables \code{x} and \code{z} occur free inside the
  15694. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15695. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15696. transformations: initialize \code{x} with a tuple whose elements are
  15697. uninitialized, replace reads from \code{x} with tuple reads, and
  15698. replace each assignment to \code{x} with a tuple write. The output of
  15699. \code{convert\_assignments} for this example is as follows:
  15700. %
  15701. {\if\edition\racketEd
  15702. \begin{lstlisting}
  15703. (define (main) : Integer
  15704. (let ([x0 (vector 0)])
  15705. (let ([y1 0])
  15706. (let ([z2 20])
  15707. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15708. (+ a3 (+ (vector-ref x0 0) z2)))])
  15709. (begin
  15710. (vector-set! x0 0 10)
  15711. (set! y1 12)
  15712. (f4 y1)))))))
  15713. \end{lstlisting}
  15714. \fi}
  15715. %
  15716. {\if\edition\pythonEd
  15717. \begin{lstlisting}
  15718. def g(z : int)-> int:
  15719. x = (uninitialized(int),)
  15720. x[0] = 0
  15721. y = 0
  15722. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15723. x[0] = 10
  15724. y = 12
  15725. return f(y)
  15726. def main() -> int:
  15727. print(g(20))
  15728. return 0
  15729. \end{lstlisting}
  15730. \fi}
  15731. To compute the free variables of all the \code{lambda} expressions, we
  15732. recommend defining the following two auxiliary functions:
  15733. \begin{enumerate}
  15734. \item \code{free\_variables} computes the free variables of an expression, and
  15735. \item \code{free\_in\_lambda} collects all the variables that are
  15736. free in any of the \code{lambda} expressions, using
  15737. \code{free\_variables} in the case for each \code{lambda}.
  15738. \end{enumerate}
  15739. {\if\edition\racketEd
  15740. %
  15741. To compute the variables that are assigned to, we recommend updating
  15742. the \code{collect-set!} function that we introduced in
  15743. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15744. as \code{Lambda}.
  15745. %
  15746. \fi}
  15747. {\if\edition\pythonEd
  15748. %
  15749. To compute the variables that are assigned to, we recommend defining
  15750. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15751. the set of variables that occur in the left-hand side of an assignment
  15752. statement, and otherwise returns the empty set.
  15753. %
  15754. \fi}
  15755. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15756. free in a \code{lambda} and that are assigned to in the enclosing
  15757. function definition.
  15758. Next we discuss the \code{convert\_assignments} pass. In the case for
  15759. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15760. $\VAR{x}$ to a tuple read.
  15761. %
  15762. {\if\edition\racketEd
  15763. \begin{lstlisting}
  15764. (Var |$x$|)
  15765. |$\Rightarrow$|
  15766. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15767. \end{lstlisting}
  15768. \fi}
  15769. %
  15770. {\if\edition\pythonEd
  15771. \begin{lstlisting}
  15772. Name(|$x$|)
  15773. |$\Rightarrow$|
  15774. Subscript(Name(|$x$|), Constant(0), Load())
  15775. \end{lstlisting}
  15776. \fi}
  15777. %
  15778. \noindent In the case for assignment, recursively process the
  15779. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15780. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15781. as follows:
  15782. %
  15783. {\if\edition\racketEd
  15784. \begin{lstlisting}
  15785. (SetBang |$x$| |$\itm{rhs}$|)
  15786. |$\Rightarrow$|
  15787. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15788. \end{lstlisting}
  15789. \fi}
  15790. {\if\edition\pythonEd
  15791. \begin{lstlisting}
  15792. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15793. |$\Rightarrow$|
  15794. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15795. \end{lstlisting}
  15796. \fi}
  15797. %
  15798. {\if\edition\racketEd
  15799. The case for \code{Lambda} is nontrivial, but it is similar to the
  15800. case for function definitions, which we discuss next.
  15801. \fi}
  15802. %
  15803. To translate a function definition, we first compute $\mathit{AF}$,
  15804. the intersection of the variables that are free in a \code{lambda} and
  15805. that are assigned to. We then apply assignment conversion to the body
  15806. of the function definition. Finally, we box the parameters of this
  15807. function definition that are in $\mathit{AF}$. For example,
  15808. the parameter \code{x} of the following function \code{g}
  15809. needs to be boxed:
  15810. {\if\edition\racketEd
  15811. \begin{lstlisting}
  15812. (define (g [x : Integer]) : Integer
  15813. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15814. (begin
  15815. (set! x 10)
  15816. (f 32))))
  15817. \end{lstlisting}
  15818. \fi}
  15819. %
  15820. {\if\edition\pythonEd
  15821. \begin{lstlisting}
  15822. def g(x : int) -> int:
  15823. f : Callable[[int],int] = lambda a: a + x
  15824. x = 10
  15825. return f(32)
  15826. \end{lstlisting}
  15827. \fi}
  15828. %
  15829. \noindent We box parameter \code{x} by creating a local variable named
  15830. \code{x} that is initialized to a tuple whose contents is the value of
  15831. the parameter, which has been renamed to \code{x\_0}.
  15832. %
  15833. {\if\edition\racketEd
  15834. \begin{lstlisting}
  15835. (define (g [x_0 : Integer]) : Integer
  15836. (let ([x (vector x_0)])
  15837. (let ([f (lambda: ([a : Integer]) : Integer
  15838. (+ a (vector-ref x 0)))])
  15839. (begin
  15840. (vector-set! x 0 10)
  15841. (f 32)))))
  15842. \end{lstlisting}
  15843. \fi}
  15844. %
  15845. {\if\edition\pythonEd
  15846. \begin{lstlisting}
  15847. def g(x_0 : int)-> int:
  15848. x = (x_0,)
  15849. f : Callable[[int], int] = (lambda a: a + x[0])
  15850. x[0] = 10
  15851. return f(32)
  15852. \end{lstlisting}
  15853. \fi}
  15854. \section{Closure Conversion}
  15855. \label{sec:closure-conversion}
  15856. \index{subject}{closure conversion}
  15857. The compiling of lexically scoped functions into top-level function
  15858. definitions and flat closures is accomplished in the pass
  15859. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15860. and before \code{limit\_functions}.
  15861. As usual, we implement the pass as a recursive function over the
  15862. AST. The interesting cases are for \key{lambda} and function
  15863. application. We transform a \key{lambda} expression into an expression
  15864. that creates a closure, that is, a tuple for which the first element
  15865. is a function pointer and the rest of the elements are the values of
  15866. the free variables of the \key{lambda}.
  15867. %
  15868. However, we use the \code{Closure} AST node instead of using a tuple
  15869. so that we can record the arity.
  15870. %
  15871. In the generated code that follows, \itm{fvs} is the free variables of
  15872. the lambda and \itm{name} is a unique symbol generated to identify the
  15873. lambda.
  15874. %
  15875. \racket{The \itm{arity} is the number of parameters (the length of
  15876. \itm{ps}).}
  15877. %
  15878. {\if\edition\racketEd
  15879. \begin{lstlisting}
  15880. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15881. |$\Rightarrow$|
  15882. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15883. \end{lstlisting}
  15884. \fi}
  15885. %
  15886. {\if\edition\pythonEd
  15887. \begin{lstlisting}
  15888. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15889. |$\Rightarrow$|
  15890. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15891. \end{lstlisting}
  15892. \fi}
  15893. %
  15894. In addition to transforming each \key{Lambda} AST node into a
  15895. tuple, we create a top-level function definition for each
  15896. \key{Lambda}, as shown next.\\
  15897. \begin{minipage}{0.8\textwidth}
  15898. {\if\edition\racketEd
  15899. \begin{lstlisting}
  15900. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15901. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15902. ...
  15903. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15904. |\itm{body'}|)...))
  15905. \end{lstlisting}
  15906. \fi}
  15907. {\if\edition\pythonEd
  15908. \begin{lstlisting}
  15909. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15910. |$\itm{fvs}_1$| = clos[1]
  15911. |$\ldots$|
  15912. |$\itm{fvs}_n$| = clos[|$n$|]
  15913. |\itm{body'}|
  15914. \end{lstlisting}
  15915. \fi}
  15916. \end{minipage}\\
  15917. The \code{clos} parameter refers to the closure. Translate the type
  15918. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15919. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15920. \itm{closTy} is a tuple type for which the first element type is
  15921. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15922. the element types are the types of the free variables in the
  15923. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15924. is nontrivial to give a type to the function in the closure's type.%
  15925. %
  15926. \footnote{To give an accurate type to a closure, we would need to add
  15927. existential types to the type checker~\citep{Minamide:1996ys}.}
  15928. %
  15929. %% The dummy type is considered to be equal to any other type during type
  15930. %% checking.
  15931. The free variables become local variables that are initialized with
  15932. their values in the closure.
  15933. Closure conversion turns every function into a tuple, so the type
  15934. annotations in the program must also be translated. We recommend
  15935. defining an auxiliary recursive function for this purpose. Function
  15936. types should be translated as follows:
  15937. %
  15938. {\if\edition\racketEd
  15939. \begin{lstlisting}
  15940. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15941. |$\Rightarrow$|
  15942. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15943. \end{lstlisting}
  15944. \fi}
  15945. {\if\edition\pythonEd
  15946. \begin{lstlisting}
  15947. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15948. |$\Rightarrow$|
  15949. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15950. \end{lstlisting}
  15951. \fi}
  15952. %
  15953. This type indicates that the first thing in the tuple is a
  15954. function. The first parameter of the function is a tuple (a closure)
  15955. and the rest of the parameters are the ones from the original
  15956. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15957. omits the types of the free variables because (1) those types are not
  15958. available in this context, and (2) we do not need them in the code that
  15959. is generated for function application. So this type describes only the
  15960. first component of the closure tuple. At runtime the tuple may have
  15961. more components, but we ignore them at this point.
  15962. We transform function application into code that retrieves the
  15963. function from the closure and then calls the function, passing the
  15964. closure as the first argument. We place $e'$ in a temporary variable
  15965. to avoid code duplication.
  15966. \begin{center}
  15967. \begin{minipage}{\textwidth}
  15968. {\if\edition\racketEd
  15969. \begin{lstlisting}
  15970. (Apply |$e$| |$\itm{es}$|)
  15971. |$\Rightarrow$|
  15972. (Let |$\itm{tmp}$| |$e'$|
  15973. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15974. \end{lstlisting}
  15975. \fi}
  15976. %
  15977. {\if\edition\pythonEd
  15978. \begin{lstlisting}
  15979. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15980. |$\Rightarrow$|
  15981. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15982. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15983. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15984. \end{lstlisting}
  15985. \fi}
  15986. \end{minipage}
  15987. \end{center}
  15988. There is also the question of what to do with references to top-level
  15989. function definitions. To maintain a uniform translation of function
  15990. application, we turn function references into closures.
  15991. \begin{tabular}{lll}
  15992. \begin{minipage}{0.3\textwidth}
  15993. {\if\edition\racketEd
  15994. \begin{lstlisting}
  15995. (FunRef |$f$| |$n$|)
  15996. \end{lstlisting}
  15997. \fi}
  15998. {\if\edition\pythonEd
  15999. \begin{lstlisting}
  16000. FunRef(|$f$|, |$n$|)
  16001. \end{lstlisting}
  16002. \fi}
  16003. \end{minipage}
  16004. &
  16005. $\Rightarrow$
  16006. &
  16007. \begin{minipage}{0.5\textwidth}
  16008. {\if\edition\racketEd
  16009. \begin{lstlisting}
  16010. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16011. \end{lstlisting}
  16012. \fi}
  16013. {\if\edition\pythonEd
  16014. \begin{lstlisting}
  16015. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16016. \end{lstlisting}
  16017. \fi}
  16018. \end{minipage}
  16019. \end{tabular} \\
  16020. We no longer need the annotated assignment statement \code{AnnAssign}
  16021. to support the type checking of \code{lambda} expressions, so we
  16022. translate it to a regular \code{Assign} statement.
  16023. The top-level function definitions need to be updated to take an extra
  16024. closure parameter, but that parameter is ignored in the body of those
  16025. functions.
  16026. \section{An Example Translation}
  16027. \label{sec:example-lambda}
  16028. Figure~\ref{fig:lexical-functions-example} shows the result of
  16029. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16030. program demonstrating lexical scoping that we discussed at the
  16031. beginning of this chapter.
  16032. \begin{figure}[tbp]
  16033. \begin{tcolorbox}[colback=white]
  16034. \begin{minipage}{0.8\textwidth}
  16035. {\if\edition\racketEd
  16036. % tests/lambda_test_6.rkt
  16037. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16038. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16039. (let ([y8 4])
  16040. (lambda: ([z9 : Integer]) : Integer
  16041. (+ x7 (+ y8 z9)))))
  16042. (define (main) : Integer
  16043. (let ([g0 ((fun-ref f6 1) 5)])
  16044. (let ([h1 ((fun-ref f6 1) 3)])
  16045. (+ (g0 11) (h1 15)))))
  16046. \end{lstlisting}
  16047. $\Rightarrow$
  16048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16049. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16050. (let ([y8 4])
  16051. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16052. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16053. (let ([x7 (vector-ref fvs3 1)])
  16054. (let ([y8 (vector-ref fvs3 2)])
  16055. (+ x7 (+ y8 z9)))))
  16056. (define (main) : Integer
  16057. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16058. ((vector-ref clos5 0) clos5 5))])
  16059. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16060. ((vector-ref clos6 0) clos6 3))])
  16061. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16062. \end{lstlisting}
  16063. \fi}
  16064. %
  16065. {\if\edition\pythonEd
  16066. % free_var.py
  16067. \begin{lstlisting}
  16068. def f(x : int) -> Callable[[int], int]:
  16069. y = 4
  16070. return lambda z: x + y + z
  16071. g = f(5)
  16072. h = f(3)
  16073. print( g(11) + h(15) )
  16074. \end{lstlisting}
  16075. $\Rightarrow$
  16076. \begin{lstlisting}
  16077. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16078. x = fvs_1[1]
  16079. y = fvs_1[2]
  16080. return x + y[0] + z
  16081. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16082. y = (777,)
  16083. y[0] = 4
  16084. return (lambda_0, x, y)
  16085. def main() -> int:
  16086. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16087. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16088. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16089. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16090. return 0
  16091. \end{lstlisting}
  16092. \fi}
  16093. \end{minipage}
  16094. \end{tcolorbox}
  16095. \caption{Example of closure conversion.}
  16096. \label{fig:lexical-functions-example}
  16097. \end{figure}
  16098. \begin{exercise}\normalfont\normalsize
  16099. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16100. Create five new programs that use \key{lambda} functions and make use of
  16101. lexical scoping. Test your compiler on these new programs and all
  16102. your previously created test programs.
  16103. \end{exercise}
  16104. \section{Expose Allocation}
  16105. \label{sec:expose-allocation-r5}
  16106. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16107. that allocates and initializes a tuple, similar to the translation of
  16108. the tuple creation in section~\ref{sec:expose-allocation}.
  16109. The only difference is replacing the use of
  16110. \ALLOC{\itm{len}}{\itm{type}} with
  16111. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16112. \section{Explicate Control and \LangCLam{}}
  16113. \label{sec:explicate-r5}
  16114. The output language of \code{explicate\_control} is \LangCLam{}; the
  16115. definition of its abstract syntax is shown in
  16116. figure~\ref{fig:Clam-syntax}.
  16117. %
  16118. \racket{The only differences with respect to \LangCFun{} are the
  16119. addition of the \code{AllocateClosure} form to the grammar for
  16120. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16121. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16122. similar to the handling of other expressions such as primitive
  16123. operators.}
  16124. %
  16125. \python{The differences with respect to \LangCFun{} are the
  16126. additions of \code{Uninitialized}, \code{AllocateClosure},
  16127. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16128. \code{explicate\_control} pass is similar to the handling of other
  16129. expressions such as primitive operators.}
  16130. \newcommand{\ClambdaASTRacket}{
  16131. \begin{array}{lcl}
  16132. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16133. \itm{op} &::= & \code{procedure-arity}
  16134. \end{array}
  16135. }
  16136. \newcommand{\ClambdaASTPython}{
  16137. \begin{array}{lcl}
  16138. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16139. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16140. &\MID& \ARITY{\Atm}
  16141. \end{array}
  16142. }
  16143. \begin{figure}[tp]
  16144. \begin{tcolorbox}[colback=white]
  16145. \small
  16146. {\if\edition\racketEd
  16147. \[
  16148. \begin{array}{l}
  16149. \gray{\CvarASTRacket} \\ \hline
  16150. \gray{\CifASTRacket} \\ \hline
  16151. \gray{\CloopASTRacket} \\ \hline
  16152. \gray{\CtupASTRacket} \\ \hline
  16153. \gray{\CfunASTRacket} \\ \hline
  16154. \ClambdaASTRacket \\
  16155. \begin{array}{lcl}
  16156. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16157. \end{array}
  16158. \end{array}
  16159. \]
  16160. \fi}
  16161. {\if\edition\pythonEd
  16162. \[
  16163. \begin{array}{l}
  16164. \gray{\CifASTPython} \\ \hline
  16165. \gray{\CtupASTPython} \\ \hline
  16166. \gray{\CfunASTPython} \\ \hline
  16167. \ClambdaASTPython \\
  16168. \begin{array}{lcl}
  16169. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16170. \end{array}
  16171. \end{array}
  16172. \]
  16173. \fi}
  16174. \end{tcolorbox}
  16175. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16176. \label{fig:Clam-syntax}
  16177. \end{figure}
  16178. \section{Select Instructions}
  16179. \label{sec:select-instructions-Llambda}
  16180. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16181. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16182. (section~\ref{sec:select-instructions-gc}). The only difference is
  16183. that you should place the \itm{arity} in the tag that is stored at
  16184. position $0$ of the vector. Recall that in
  16185. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16186. was not used. We store the arity in the $5$ bits starting at position
  16187. $58$.
  16188. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16189. instructions that access the tag from position $0$ of the vector and
  16190. extract the $5$ bits starting at position $58$ from the tag.}
  16191. %
  16192. \python{Compile a call to the \code{arity} operator to a sequence of
  16193. instructions that access the tag from position $0$ of the tuple
  16194. (representing a closure) and extract the $5$-bits starting at position
  16195. $58$ from the tag.}
  16196. \begin{figure}[p]
  16197. \begin{tcolorbox}[colback=white]
  16198. {\if\edition\racketEd
  16199. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16200. \node (Lfun) at (0,2) {\large \LangLam{}};
  16201. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16202. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16203. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16204. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16205. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16206. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16207. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16208. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16209. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16210. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16211. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16212. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16213. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16214. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16215. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16216. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16217. \path[->,bend left=15] (Lfun) edge [above] node
  16218. {\ttfamily\footnotesize shrink} (Lfun-2);
  16219. \path[->,bend left=15] (Lfun-2) edge [above] node
  16220. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16221. \path[->,bend left=15] (Lfun-3) edge [above] node
  16222. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16223. \path[->,bend left=15] (F1-0) edge [left] node
  16224. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16225. \path[->,bend left=15] (F1-1) edge [below] node
  16226. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16227. \path[->,bend right=15] (F1-2) edge [above] node
  16228. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16229. \path[->,bend right=15] (F1-3) edge [above] node
  16230. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16231. \path[->,bend left=15] (F1-4) edge [right] node
  16232. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16233. \path[->,bend right=15] (F1-5) edge [below] node
  16234. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16235. \path[->,bend left=15] (F1-6) edge [above] node
  16236. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16237. \path[->] (C3-2) edge [right] node
  16238. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16239. \path[->,bend right=15] (x86-2) edge [right] node
  16240. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16241. \path[->,bend right=15] (x86-2-1) edge [below] node
  16242. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16243. \path[->,bend right=15] (x86-2-2) edge [right] node
  16244. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16245. \path[->,bend left=15] (x86-3) edge [above] node
  16246. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16247. \path[->,bend left=15] (x86-4) edge [right] node
  16248. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16249. \end{tikzpicture}
  16250. \fi}
  16251. {\if\edition\pythonEd
  16252. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16253. \node (Lfun) at (0,2) {\large \LangLam{}};
  16254. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16255. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16256. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16257. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16258. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16259. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16260. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16261. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16262. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16263. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16264. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16265. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16266. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16267. \path[->,bend left=15] (Lfun) edge [above] node
  16268. {\ttfamily\footnotesize shrink} (Lfun-2);
  16269. \path[->,bend left=15] (Lfun-2) edge [above] node
  16270. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16271. \path[->,bend left=15] (Lfun-3) edge [above] node
  16272. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16273. \path[->,bend left=15] (F1-0) edge [left] node
  16274. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16275. \path[->,bend left=15] (F1-1) edge [below] node
  16276. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16277. \path[->,bend left=15] (F1-2) edge [below] node
  16278. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16279. \path[->,bend right=15] (F1-3) edge [above] node
  16280. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16281. \path[->,bend right=15] (F1-5) edge [right] node
  16282. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16283. \path[->,bend left=15] (F1-6) edge [right] node
  16284. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16285. \path[->,bend right=15] (C3-2) edge [right] node
  16286. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16287. \path[->,bend right=15] (x86-2) edge [below] node
  16288. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16289. \path[->,bend right=15] (x86-3) edge [below] node
  16290. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16291. \path[->,bend left=15] (x86-4) edge [above] node
  16292. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16293. \end{tikzpicture}
  16294. \fi}
  16295. \end{tcolorbox}
  16296. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16297. functions.}
  16298. \label{fig:Llambda-passes}
  16299. \end{figure}
  16300. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16301. needed for the compilation of \LangLam{}.
  16302. \clearpage
  16303. \section{Challenge: Optimize Closures}
  16304. \label{sec:optimize-closures}
  16305. In this chapter we compile lexically scoped functions into a
  16306. relatively efficient representation: flat closures. However, even this
  16307. representation comes with some overhead. For example, consider the
  16308. following program with a function \code{tail\_sum} that does not have
  16309. any free variables and where all the uses of \code{tail\_sum} are in
  16310. applications in which we know that only \code{tail\_sum} is being applied
  16311. (and not any other functions):
  16312. \begin{center}
  16313. \begin{minipage}{0.95\textwidth}
  16314. {\if\edition\racketEd
  16315. \begin{lstlisting}
  16316. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16317. (if (eq? n 0)
  16318. s
  16319. (tail_sum (- n 1) (+ n s))))
  16320. (+ (tail_sum 3 0) 36)
  16321. \end{lstlisting}
  16322. \fi}
  16323. {\if\edition\pythonEd
  16324. \begin{lstlisting}
  16325. def tail_sum(n : int, s : int) -> int:
  16326. if n == 0:
  16327. return s
  16328. else:
  16329. return tail_sum(n - 1, n + s)
  16330. print( tail_sum(3, 0) + 36)
  16331. \end{lstlisting}
  16332. \fi}
  16333. \end{minipage}
  16334. \end{center}
  16335. As described in this chapter, we uniformly apply closure conversion to
  16336. all functions, obtaining the following output for this program:
  16337. \begin{center}
  16338. \begin{minipage}{0.95\textwidth}
  16339. {\if\edition\racketEd
  16340. \begin{lstlisting}
  16341. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16342. (if (eq? n2 0)
  16343. s3
  16344. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16345. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16346. (define (main) : Integer
  16347. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16348. ((vector-ref clos6 0) clos6 3 0)) 27))
  16349. \end{lstlisting}
  16350. \fi}
  16351. {\if\edition\pythonEd
  16352. \begin{lstlisting}
  16353. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16354. if n_0 == 0:
  16355. return s_1
  16356. else:
  16357. return (let clos_2 = (tail_sum,)
  16358. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16359. def main() -> int :
  16360. print((let clos_4 = (tail_sum,)
  16361. in clos_4[0](clos_4, 3, 0)) + 36)
  16362. return 0
  16363. \end{lstlisting}
  16364. \fi}
  16365. \end{minipage}
  16366. \end{center}
  16367. If this program were compiled according to the previous chapter, there
  16368. would be no allocation and the calls to \code{tail\_sum} would be
  16369. direct calls. In contrast, the program presented here allocates memory
  16370. for each closure and the calls to \code{tail\_sum} are indirect. These
  16371. two differences incur considerable overhead in a program such as this,
  16372. in which the allocations and indirect calls occur inside a tight loop.
  16373. One might think that this problem is trivial to solve: can't we just
  16374. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16375. and compile them to direct calls instead of treating it like a call to
  16376. a closure? We would also drop the new \code{fvs} parameter of
  16377. \code{tail\_sum}.
  16378. %
  16379. However, this problem is not so trivial, because a global function may
  16380. \emph{escape} and become involved in applications that also involve
  16381. closures. Consider the following example in which the application
  16382. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16383. application because the \code{lambda} may flow into \code{f}, but the
  16384. \code{inc} function might also flow into \code{f}:
  16385. \begin{center}
  16386. \begin{minipage}{\textwidth}
  16387. % lambda_test_30.rkt
  16388. {\if\edition\racketEd
  16389. \begin{lstlisting}
  16390. (define (inc [x : Integer]) : Integer
  16391. (+ x 1))
  16392. (let ([y (read)])
  16393. (let ([f (if (eq? (read) 0)
  16394. inc
  16395. (lambda: ([x : Integer]) : Integer (- x y)))])
  16396. (f 41)))
  16397. \end{lstlisting}
  16398. \fi}
  16399. {\if\edition\pythonEd
  16400. \begin{lstlisting}
  16401. def add1(x : int) -> int:
  16402. return x + 1
  16403. y = input_int()
  16404. g : Callable[[int], int] = lambda x: x - y
  16405. f = add1 if input_int() == 0 else g
  16406. print( f(41) )
  16407. \end{lstlisting}
  16408. \fi}
  16409. \end{minipage}
  16410. \end{center}
  16411. If a global function name is used in any way other than as the
  16412. operator in a direct call, then we say that the function
  16413. \emph{escapes}. If a global function does not escape, then we do not
  16414. need to perform closure conversion on the function.
  16415. \begin{exercise}\normalfont\normalsize
  16416. Implement an auxiliary function for detecting which global
  16417. functions escape. Using that function, implement an improved version
  16418. of closure conversion that does not apply closure conversion to
  16419. global functions that do not escape but instead compiles them as
  16420. regular functions. Create several new test cases that check whether
  16421. your compiler properly detect whether global functions escape or not.
  16422. \end{exercise}
  16423. So far we have reduced the overhead of calling global functions, but
  16424. it would also be nice to reduce the overhead of calling a
  16425. \code{lambda} when we can determine at compile time which
  16426. \code{lambda} will be called. We refer to such calls as \emph{known
  16427. calls}. Consider the following example in which a \code{lambda} is
  16428. bound to \code{f} and then applied.
  16429. {\if\edition\racketEd
  16430. % lambda_test_9.rkt
  16431. \begin{lstlisting}
  16432. (let ([y (read)])
  16433. (let ([f (lambda: ([x : Integer]) : Integer
  16434. (+ x y))])
  16435. (f 21)))
  16436. \end{lstlisting}
  16437. \fi}
  16438. {\if\edition\pythonEd
  16439. \begin{lstlisting}
  16440. y = input_int()
  16441. f : Callable[[int],int] = lambda x: x + y
  16442. print( f(21) )
  16443. \end{lstlisting}
  16444. \fi}
  16445. %
  16446. \noindent Closure conversion compiles the application
  16447. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16448. %
  16449. {\if\edition\racketEd
  16450. \begin{lstlisting}
  16451. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16452. (let ([y2 (vector-ref fvs6 1)])
  16453. (+ x3 y2)))
  16454. (define (main) : Integer
  16455. (let ([y2 (read)])
  16456. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16457. ((vector-ref f4 0) f4 21))))
  16458. \end{lstlisting}
  16459. \fi}
  16460. {\if\edition\pythonEd
  16461. \begin{lstlisting}
  16462. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16463. y_1 = fvs_4[1]
  16464. return x_2 + y_1[0]
  16465. def main() -> int:
  16466. y_1 = (777,)
  16467. y_1[0] = input_int()
  16468. f_0 = (lambda_3, y_1)
  16469. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16470. return 0
  16471. \end{lstlisting}
  16472. \fi}
  16473. %
  16474. \noindent However, we can instead compile the application
  16475. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16476. %
  16477. {\if\edition\racketEd
  16478. \begin{lstlisting}
  16479. (define (main) : Integer
  16480. (let ([y2 (read)])
  16481. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16482. ((fun-ref lambda5 1) f4 21))))
  16483. \end{lstlisting}
  16484. \fi}
  16485. {\if\edition\pythonEd
  16486. \begin{lstlisting}
  16487. def main() -> int:
  16488. y_1 = (777,)
  16489. y_1[0] = input_int()
  16490. f_0 = (lambda_3, y_1)
  16491. print(lambda_3(f_0, 21))
  16492. return 0
  16493. \end{lstlisting}
  16494. \fi}
  16495. The problem of determining which \code{lambda} will be called from a
  16496. particular application is quite challenging in general and the topic
  16497. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16498. following exercise we recommend that you compile an application to a
  16499. direct call when the operator is a variable and \racket{the variable
  16500. is \code{let}-bound to a closure}\python{the previous assignment to
  16501. the variable is a closure}. This can be accomplished by maintaining
  16502. an environment that maps variables to function names. Extend the
  16503. environment whenever you encounter a closure on the right-hand side of
  16504. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16505. name of the global function for the closure. This pass should come
  16506. after closure conversion.
  16507. \begin{exercise}\normalfont\normalsize
  16508. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16509. compiles known calls into direct calls. Verify that your compiler is
  16510. successful in this regard on several example programs.
  16511. \end{exercise}
  16512. These exercises only scratch the surface of closure optimization. A
  16513. good next step for the interested reader is to look at the work of
  16514. \citet{Keep:2012ab}.
  16515. \section{Further Reading}
  16516. The notion of lexically scoped functions predates modern computers by
  16517. about a decade. They were invented by \citet{Church:1932aa}, who
  16518. proposed the lambda calculus as a foundation for logic. Anonymous
  16519. functions were included in the LISP~\citep{McCarthy:1960dz}
  16520. programming language but were initially dynamically scoped. The Scheme
  16521. dialect of LISP adopted lexical scoping, and
  16522. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16523. Scheme programs. However, environments were represented as linked
  16524. lists, so variable look-up was linear in the size of the
  16525. environment. \citet{Appel91} gives a detailed description of several
  16526. closure representations. In this chapter we represent environments
  16527. using flat closures, which were invented by
  16528. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  16529. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16530. closures, variable look-up is constant time but the time to create a
  16531. closure is proportional to the number of its free variables. Flat
  16532. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16533. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16534. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16535. % compilers)
  16536. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16537. \chapter{Dynamic Typing}
  16538. \label{ch:Ldyn}
  16539. \index{subject}{dynamic typing}
  16540. \setcounter{footnote}{0}
  16541. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16542. typed language that is a subset of \racket{Racket}\python{Python}. The
  16543. focus on dynamic typing is in contrast to the previous chapters, which
  16544. have studied the compilation of statically typed languages. In
  16545. dynamically typed languages such as \LangDyn{}, a particular
  16546. expression may produce a value of a different type each time it is
  16547. executed. Consider the following example with a conditional \code{if}
  16548. expression that may return a Boolean or an integer depending on the
  16549. input to the program:
  16550. % part of dynamic_test_25.rkt
  16551. {\if\edition\racketEd
  16552. \begin{lstlisting}
  16553. (not (if (eq? (read) 1) #f 0))
  16554. \end{lstlisting}
  16555. \fi}
  16556. {\if\edition\pythonEd
  16557. \begin{lstlisting}
  16558. not (False if input_int() == 1 else 0)
  16559. \end{lstlisting}
  16560. \fi}
  16561. Languages that allow expressions to produce different kinds of values
  16562. are called \emph{polymorphic}, a word composed of the Greek roots
  16563. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16564. There are several kinds of polymorphism in programming languages, such as
  16565. subtype polymorphism and parametric polymorphism
  16566. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16567. study in this chapter does not have a special name; it is the kind
  16568. that arises in dynamically typed languages.
  16569. Another characteristic of dynamically typed languages is that
  16570. their primitive operations, such as \code{not}, are often defined to operate
  16571. on many different types of values. In fact, in
  16572. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16573. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16574. given anything else it returns \FALSE{}.
  16575. Furthermore, even when primitive operations restrict their inputs to
  16576. values of a certain type, this restriction is enforced at runtime
  16577. instead of during compilation. For example, the tuple read
  16578. operation
  16579. \racket{\code{(vector-ref \#t 0)}}
  16580. \python{\code{True[0]}}
  16581. results in a runtime error because the first argument must
  16582. be a tuple, not a Boolean.
  16583. \section{The \LangDyn{} Language}
  16584. \newcommand{\LdynGrammarRacket}{
  16585. \begin{array}{rcl}
  16586. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16587. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16588. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16589. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16590. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16591. \end{array}
  16592. }
  16593. \newcommand{\LdynASTRacket}{
  16594. \begin{array}{lcl}
  16595. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16596. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16597. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16598. \end{array}
  16599. }
  16600. \begin{figure}[tp]
  16601. \centering
  16602. \begin{tcolorbox}[colback=white]
  16603. \small
  16604. {\if\edition\racketEd
  16605. \[
  16606. \begin{array}{l}
  16607. \gray{\LintGrammarRacket{}} \\ \hline
  16608. \gray{\LvarGrammarRacket{}} \\ \hline
  16609. \gray{\LifGrammarRacket{}} \\ \hline
  16610. \gray{\LwhileGrammarRacket} \\ \hline
  16611. \gray{\LtupGrammarRacket} \\ \hline
  16612. \LdynGrammarRacket \\
  16613. \begin{array}{rcl}
  16614. \LangDynM{} &::=& \Def\ldots\; \Exp
  16615. \end{array}
  16616. \end{array}
  16617. \]
  16618. \fi}
  16619. {\if\edition\pythonEd
  16620. \[
  16621. \begin{array}{rcl}
  16622. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16623. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16624. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16625. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16626. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16627. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16628. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16629. \MID \CLEN{\Exp} \\
  16630. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16631. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16632. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16633. \MID \Var\mathop{\key{=}}\Exp \\
  16634. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16635. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16636. &\MID& \CRETURN{\Exp} \\
  16637. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16638. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16639. \end{array}
  16640. \]
  16641. \fi}
  16642. \end{tcolorbox}
  16643. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16644. \label{fig:r7-concrete-syntax}
  16645. \end{figure}
  16646. \begin{figure}[tp]
  16647. \centering
  16648. \begin{tcolorbox}[colback=white]
  16649. \small
  16650. {\if\edition\racketEd
  16651. \[
  16652. \begin{array}{l}
  16653. \gray{\LintASTRacket{}} \\ \hline
  16654. \gray{\LvarASTRacket{}} \\ \hline
  16655. \gray{\LifASTRacket{}} \\ \hline
  16656. \gray{\LwhileASTRacket} \\ \hline
  16657. \gray{\LtupASTRacket} \\ \hline
  16658. \LdynASTRacket \\
  16659. \begin{array}{lcl}
  16660. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16661. \end{array}
  16662. \end{array}
  16663. \]
  16664. \fi}
  16665. {\if\edition\pythonEd
  16666. \[
  16667. \begin{array}{rcl}
  16668. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16669. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16670. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16671. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16672. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16673. &\MID & \code{Is()} \\
  16674. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16675. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16676. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16677. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16678. \MID \VAR{\Var{}} \\
  16679. &\MID& \BOOL{\itm{bool}}
  16680. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16681. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16682. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16683. &\MID& \LEN{\Exp} \\
  16684. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16685. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16686. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16687. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16688. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16689. &\MID& \RETURN{\Exp} \\
  16690. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16691. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16692. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16693. \end{array}
  16694. \]
  16695. \fi}
  16696. \end{tcolorbox}
  16697. \caption{The abstract syntax of \LangDyn{}.}
  16698. \label{fig:r7-syntax}
  16699. \end{figure}
  16700. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16701. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16702. %
  16703. There is no type checker for \LangDyn{} because it checks types only
  16704. at runtime.
  16705. The definitional interpreter for \LangDyn{} is presented in
  16706. \racket{figure~\ref{fig:interp-Ldyn}}
  16707. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16708. and definitions of its auxiliary functions are shown in
  16709. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16710. \INT{n}. Instead of simply returning the integer \code{n} (as
  16711. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16712. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16713. value} that combines an underlying value with a tag that identifies
  16714. what kind of value it is. We define the following \racket{struct}\python{class}
  16715. to represent tagged values:
  16716. %
  16717. {\if\edition\racketEd
  16718. \begin{lstlisting}
  16719. (struct Tagged (value tag) #:transparent)
  16720. \end{lstlisting}
  16721. \fi}
  16722. {\if\edition\pythonEd
  16723. \begin{minipage}{\textwidth}
  16724. \begin{lstlisting}
  16725. @dataclass(eq=True)
  16726. class Tagged(Value):
  16727. value : Value
  16728. tag : str
  16729. def __str__(self):
  16730. return str(self.value)
  16731. \end{lstlisting}
  16732. \end{minipage}
  16733. \fi}
  16734. %
  16735. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16736. \code{Vector}, and \code{Procedure}.}
  16737. %
  16738. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16739. \code{'tuple'}, and \code{'function'}.}
  16740. %
  16741. Tags are closely related to types but do not always capture all the
  16742. information that a type does.
  16743. %
  16744. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16745. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16746. Any)} is tagged with \code{Procedure}.}
  16747. %
  16748. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16749. is tagged with \code{'tuple'} and a function of type
  16750. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16751. is tagged with \code{'function'}.}
  16752. Next consider the match case for accessing the element of a tuple.
  16753. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16754. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16755. argument is a tuple and the second is an integer.
  16756. \racket{
  16757. If they are not, a \code{trapped-error} is raised. Recall from
  16758. section~\ref{sec:interp_Lint} that when a definition interpreter
  16759. raises a \code{trapped-error} error, the compiled code must also
  16760. signal an error by exiting with return code \code{255}. A
  16761. \code{trapped-error} is also raised if the index is not less than the
  16762. length of the vector.
  16763. }
  16764. %
  16765. \python{If they are not, an exception is raised. The compiled code
  16766. must also signal an error by exiting with return code \code{255}. A
  16767. exception is also raised if the index is not less than the length of the
  16768. tuple or if it is negative.}
  16769. \begin{figure}[tbp]
  16770. \begin{tcolorbox}[colback=white]
  16771. {\if\edition\racketEd
  16772. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16773. (define ((interp-Ldyn-exp env) ast)
  16774. (define recur (interp-Ldyn-exp env))
  16775. (match ast
  16776. [(Var x) (dict-ref env x)]
  16777. [(Int n) (Tagged n 'Integer)]
  16778. [(Bool b) (Tagged b 'Boolean)]
  16779. [(Lambda xs rt body)
  16780. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16781. [(Prim 'vector es)
  16782. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16783. [(Prim 'vector-ref (list e1 e2))
  16784. (define vec (recur e1)) (define i (recur e2))
  16785. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16786. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16787. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16788. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16789. [(Prim 'vector-set! (list e1 e2 e3))
  16790. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16791. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16792. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16793. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16794. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16795. (Tagged (void) 'Void)]
  16796. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16797. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16798. [(Prim 'or (list e1 e2))
  16799. (define v1 (recur e1))
  16800. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16801. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16802. [(Prim op (list e1))
  16803. #:when (set-member? type-predicates op)
  16804. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16805. [(Prim op es)
  16806. (define args (map recur es))
  16807. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16808. (unless (for/or ([expected-tags (op-tags op)])
  16809. (equal? expected-tags tags))
  16810. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16811. (tag-value
  16812. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16813. [(If q t f)
  16814. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16815. [(Apply f es)
  16816. (define new-f (recur f)) (define args (map recur es))
  16817. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16818. (match f-val
  16819. [`(function ,xs ,body ,lam-env)
  16820. (unless (eq? (length xs) (length args))
  16821. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16822. (define new-env (append (map cons xs args) lam-env))
  16823. ((interp-Ldyn-exp new-env) body)]
  16824. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16825. \end{lstlisting}
  16826. \fi}
  16827. {\if\edition\pythonEd
  16828. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16829. class InterpLdyn(InterpLlambda):
  16830. def interp_exp(self, e, env):
  16831. match e:
  16832. case Constant(n):
  16833. return self.tag(super().interp_exp(e, env))
  16834. case Tuple(es, Load()):
  16835. return self.tag(super().interp_exp(e, env))
  16836. case Lambda(params, body):
  16837. return self.tag(super().interp_exp(e, env))
  16838. case Call(Name('input_int'), []):
  16839. return self.tag(super().interp_exp(e, env))
  16840. case BinOp(left, Add(), right):
  16841. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16842. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16843. case BinOp(left, Sub(), right):
  16844. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16845. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16846. case UnaryOp(USub(), e1):
  16847. v = self.interp_exp(e1, env)
  16848. return self.tag(- self.untag(v, 'int', e))
  16849. case IfExp(test, body, orelse):
  16850. v = self.interp_exp(test, env)
  16851. if self.untag(v, 'bool', e):
  16852. return self.interp_exp(body, env)
  16853. else:
  16854. return self.interp_exp(orelse, env)
  16855. case UnaryOp(Not(), e1):
  16856. v = self.interp_exp(e1, env)
  16857. return self.tag(not self.untag(v, 'bool', e))
  16858. case BoolOp(And(), values):
  16859. left = values[0]; right = values[1]
  16860. l = self.interp_exp(left, env)
  16861. if self.untag(l, 'bool', e):
  16862. return self.interp_exp(right, env)
  16863. else:
  16864. return self.tag(False)
  16865. case BoolOp(Or(), values):
  16866. left = values[0]; right = values[1]
  16867. l = self.interp_exp(left, env)
  16868. if self.untag(l, 'bool', e):
  16869. return self.tag(True)
  16870. else:
  16871. return self.interp_exp(right, env)
  16872. case Compare(left, [cmp], [right]):
  16873. l = self.interp_exp(left, env)
  16874. r = self.interp_exp(right, env)
  16875. if l.tag == r.tag:
  16876. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16877. else:
  16878. raise Exception('interp Compare unexpected '
  16879. + repr(l) + ' ' + repr(r))
  16880. case Subscript(tup, index, Load()):
  16881. t = self.interp_exp(tup, env)
  16882. n = self.interp_exp(index, env)
  16883. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16884. case Call(Name('len'), [tup]):
  16885. t = self.interp_exp(tup, env)
  16886. return self.tag(len(self.untag(t, 'tuple', e)))
  16887. case _:
  16888. return self.tag(super().interp_exp(e, env))
  16889. \end{lstlisting}
  16890. \fi}
  16891. \end{tcolorbox}
  16892. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16893. \label{fig:interp-Ldyn}
  16894. \end{figure}
  16895. {\if\edition\pythonEd
  16896. \begin{figure}[tbp]
  16897. \begin{tcolorbox}[colback=white]
  16898. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16899. class InterpLdyn(InterpLlambda):
  16900. def interp_stmts(self, ss, env):
  16901. if len(ss) == 0:
  16902. return
  16903. match ss[0]:
  16904. case If(test, body, orelse):
  16905. v = self.interp_exp(test, env)
  16906. if self.untag(v, 'bool', ss[0]):
  16907. return self.interp_stmts(body + ss[1:], env)
  16908. else:
  16909. return self.interp_stmts(orelse + ss[1:], env)
  16910. case While(test, body, []):
  16911. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16912. self.interp_stmts(body, env)
  16913. return self.interp_stmts(ss[1:], env)
  16914. case Assign([Subscript(tup, index)], value):
  16915. tup = self.interp_exp(tup, env)
  16916. index = self.interp_exp(index, env)
  16917. tup_v = self.untag(tup, 'tuple', ss[0])
  16918. index_v = self.untag(index, 'int', ss[0])
  16919. tup_v[index_v] = self.interp_exp(value, env)
  16920. return self.interp_stmts(ss[1:], env)
  16921. case FunctionDef(name, params, bod, dl, returns, comment):
  16922. ps = [x for (x,t) in params]
  16923. env[name] = self.tag(Function(name, ps, bod, env))
  16924. return self.interp_stmts(ss[1:], env)
  16925. case _:
  16926. return super().interp_stmts(ss, env)
  16927. \end{lstlisting}
  16928. \end{tcolorbox}
  16929. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16930. \label{fig:interp-Ldyn-2}
  16931. \end{figure}
  16932. \fi}
  16933. \begin{figure}[tbp]
  16934. \begin{tcolorbox}[colback=white]
  16935. {\if\edition\racketEd
  16936. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16937. (define (interp-op op)
  16938. (match op
  16939. ['+ fx+]
  16940. ['- fx-]
  16941. ['read read-fixnum]
  16942. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16943. ['< (lambda (v1 v2)
  16944. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16945. ['<= (lambda (v1 v2)
  16946. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16947. ['> (lambda (v1 v2)
  16948. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16949. ['>= (lambda (v1 v2)
  16950. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16951. ['boolean? boolean?]
  16952. ['integer? fixnum?]
  16953. ['void? void?]
  16954. ['vector? vector?]
  16955. ['vector-length vector-length]
  16956. ['procedure? (match-lambda
  16957. [`(functions ,xs ,body ,env) #t] [else #f])]
  16958. [else (error 'interp-op "unknown operator" op)]))
  16959. (define (op-tags op)
  16960. (match op
  16961. ['+ '((Integer Integer))]
  16962. ['- '((Integer Integer) (Integer))]
  16963. ['read '(())]
  16964. ['not '((Boolean))]
  16965. ['< '((Integer Integer))]
  16966. ['<= '((Integer Integer))]
  16967. ['> '((Integer Integer))]
  16968. ['>= '((Integer Integer))]
  16969. ['vector-length '((Vector))]))
  16970. (define type-predicates
  16971. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16972. (define (tag-value v)
  16973. (cond [(boolean? v) (Tagged v 'Boolean)]
  16974. [(fixnum? v) (Tagged v 'Integer)]
  16975. [(procedure? v) (Tagged v 'Procedure)]
  16976. [(vector? v) (Tagged v 'Vector)]
  16977. [(void? v) (Tagged v 'Void)]
  16978. [else (error 'tag-value "unidentified value ~a" v)]))
  16979. (define (check-tag val expected ast)
  16980. (define tag (Tagged-tag val))
  16981. (unless (eq? tag expected)
  16982. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16983. \end{lstlisting}
  16984. \fi}
  16985. {\if\edition\pythonEd
  16986. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16987. class InterpLdyn(InterpLlambda):
  16988. def tag(self, v):
  16989. if v is True or v is False:
  16990. return Tagged(v, 'bool')
  16991. elif isinstance(v, int):
  16992. return Tagged(v, 'int')
  16993. elif isinstance(v, Function):
  16994. return Tagged(v, 'function')
  16995. elif isinstance(v, tuple):
  16996. return Tagged(v, 'tuple')
  16997. elif isinstance(v, type(None)):
  16998. return Tagged(v, 'none')
  16999. else:
  17000. raise Exception('tag: unexpected ' + repr(v))
  17001. def untag(self, v, expected_tag, ast):
  17002. match v:
  17003. case Tagged(val, tag) if tag == expected_tag:
  17004. return val
  17005. case _:
  17006. raise Exception('expected Tagged value with '
  17007. + expected_tag + ', not ' + ' ' + repr(v))
  17008. def apply_fun(self, fun, args, e):
  17009. f = self.untag(fun, 'function', e)
  17010. return super().apply_fun(f, args, e)
  17011. \end{lstlisting}
  17012. \fi}
  17013. \end{tcolorbox}
  17014. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17015. \label{fig:interp-Ldyn-aux}
  17016. \end{figure}
  17017. \clearpage
  17018. \section{Representation of Tagged Values}
  17019. The interpreter for \LangDyn{} introduced a new kind of value: the
  17020. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17021. represent tagged values at the bit level. Because almost every
  17022. operation in \LangDyn{} involves manipulating tagged values, the
  17023. representation must be efficient. Recall that all our values are 64
  17024. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17025. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17026. $011$ for procedures, and $101$ for the void value\python{,
  17027. \key{None}}. We define the following auxiliary function for mapping
  17028. types to tag codes:
  17029. %
  17030. {\if\edition\racketEd
  17031. \begin{align*}
  17032. \itm{tagof}(\key{Integer}) &= 001 \\
  17033. \itm{tagof}(\key{Boolean}) &= 100 \\
  17034. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17035. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17036. \itm{tagof}(\key{Void}) &= 101
  17037. \end{align*}
  17038. \fi}
  17039. {\if\edition\pythonEd
  17040. \begin{align*}
  17041. \itm{tagof}(\key{IntType()}) &= 001 \\
  17042. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17043. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17044. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17045. \itm{tagof}(\key{type(None)}) &= 101
  17046. \end{align*}
  17047. \fi}
  17048. %
  17049. This stealing of 3 bits comes at some price: integers are now restricted
  17050. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17051. affect tuples and procedures because those values are addresses, and
  17052. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17053. they are always $000$. Thus, we do not lose information by overwriting
  17054. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17055. to recover the original address.
  17056. To make tagged values into first-class entities, we can give them a
  17057. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17058. operations such as \code{Inject} and \code{Project} for creating and
  17059. using them, yielding the statically typed \LangAny{} intermediate
  17060. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17061. section~\ref{sec:compile-r7}; in th next section we describe the
  17062. \LangAny{} language in greater detail.
  17063. \section{The \LangAny{} Language}
  17064. \label{sec:Rany-lang}
  17065. \newcommand{\LanyASTRacket}{
  17066. \begin{array}{lcl}
  17067. \Type &::= & \ANYTY \\
  17068. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17069. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17070. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17071. \itm{op} &::= & \code{any-vector-length}
  17072. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17073. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17074. \MID \code{procedure?} \MID \code{void?} \\
  17075. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17076. \end{array}
  17077. }
  17078. \newcommand{\LanyASTPython}{
  17079. \begin{array}{lcl}
  17080. \Type &::= & \key{AnyType()} \\
  17081. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17082. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17083. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17084. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17085. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17086. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17087. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17088. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17089. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17090. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17091. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17092. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17093. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17094. \end{array}
  17095. }
  17096. \begin{figure}[tp]
  17097. \centering
  17098. \begin{tcolorbox}[colback=white]
  17099. \small
  17100. {\if\edition\racketEd
  17101. \[
  17102. \begin{array}{l}
  17103. \gray{\LintOpAST} \\ \hline
  17104. \gray{\LvarASTRacket{}} \\ \hline
  17105. \gray{\LifASTRacket{}} \\ \hline
  17106. \gray{\LwhileASTRacket{}} \\ \hline
  17107. \gray{\LtupASTRacket{}} \\ \hline
  17108. \gray{\LfunASTRacket} \\ \hline
  17109. \gray{\LlambdaASTRacket} \\ \hline
  17110. \LanyASTRacket \\
  17111. \begin{array}{lcl}
  17112. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17113. \end{array}
  17114. \end{array}
  17115. \]
  17116. \fi}
  17117. {\if\edition\pythonEd
  17118. \[
  17119. \begin{array}{l}
  17120. \gray{\LintASTPython} \\ \hline
  17121. \gray{\LvarASTPython{}} \\ \hline
  17122. \gray{\LifASTPython{}} \\ \hline
  17123. \gray{\LwhileASTPython{}} \\ \hline
  17124. \gray{\LtupASTPython{}} \\ \hline
  17125. \gray{\LfunASTPython} \\ \hline
  17126. \gray{\LlambdaASTPython} \\ \hline
  17127. \LanyASTPython \\
  17128. \begin{array}{lcl}
  17129. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17130. \end{array}
  17131. \end{array}
  17132. \]
  17133. \fi}
  17134. \end{tcolorbox}
  17135. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17136. \label{fig:Lany-syntax}
  17137. \end{figure}
  17138. The definition of the abstract syntax of \LangAny{} is given in
  17139. figure~\ref{fig:Lany-syntax}.
  17140. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17141. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17142. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17143. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17144. converts the tagged value produced by expression $e$ into a value of
  17145. type $T$ or halts the program if the type tag does not match $T$.
  17146. %
  17147. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17148. restricted to be a flat type (the nonterminal $\FType$) which
  17149. simplifies the implementation and complies with the needs for
  17150. compiling \LangDyn{}.
  17151. The \racket{\code{any-vector}} operators
  17152. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17153. operations so that they can be applied to a value of type
  17154. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17155. tuple operations in that the index is not restricted to a literal
  17156. integer in the grammar but is allowed to be any expression.
  17157. \racket{The type predicates such as
  17158. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17159. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17160. the predicate and return {\FALSE} otherwise.}
  17161. The type checker for \LangAny{} is shown in
  17162. figure~\ref{fig:type-check-Lany}
  17163. %
  17164. \racket{ and uses the auxiliary functions presented in
  17165. figure~\ref{fig:type-check-Lany-aux}}.
  17166. %
  17167. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17168. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17169. \begin{figure}[btp]
  17170. \begin{tcolorbox}[colback=white]
  17171. {\if\edition\racketEd
  17172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17173. (define type-check-Lany-class
  17174. (class type-check-Llambda-class
  17175. (super-new)
  17176. (inherit check-type-equal?)
  17177. (define/override (type-check-exp env)
  17178. (lambda (e)
  17179. (define recur (type-check-exp env))
  17180. (match e
  17181. [(Inject e1 ty)
  17182. (unless (flat-ty? ty)
  17183. (error 'type-check "may only inject from flat type, not ~a" ty))
  17184. (define-values (new-e1 e-ty) (recur e1))
  17185. (check-type-equal? e-ty ty e)
  17186. (values (Inject new-e1 ty) 'Any)]
  17187. [(Project e1 ty)
  17188. (unless (flat-ty? ty)
  17189. (error 'type-check "may only project to flat type, not ~a" ty))
  17190. (define-values (new-e1 e-ty) (recur e1))
  17191. (check-type-equal? e-ty 'Any e)
  17192. (values (Project new-e1 ty) ty)]
  17193. [(Prim 'any-vector-length (list e1))
  17194. (define-values (e1^ t1) (recur e1))
  17195. (check-type-equal? t1 'Any e)
  17196. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17197. [(Prim 'any-vector-ref (list e1 e2))
  17198. (define-values (e1^ t1) (recur e1))
  17199. (define-values (e2^ t2) (recur e2))
  17200. (check-type-equal? t1 'Any e)
  17201. (check-type-equal? t2 'Integer e)
  17202. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17203. [(Prim 'any-vector-set! (list e1 e2 e3))
  17204. (define-values (e1^ t1) (recur e1))
  17205. (define-values (e2^ t2) (recur e2))
  17206. (define-values (e3^ t3) (recur e3))
  17207. (check-type-equal? t1 'Any e)
  17208. (check-type-equal? t2 'Integer e)
  17209. (check-type-equal? t3 'Any e)
  17210. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17211. [(Prim pred (list e1))
  17212. #:when (set-member? (type-predicates) pred)
  17213. (define-values (new-e1 e-ty) (recur e1))
  17214. (check-type-equal? e-ty 'Any e)
  17215. (values (Prim pred (list new-e1)) 'Boolean)]
  17216. [(Prim 'eq? (list arg1 arg2))
  17217. (define-values (e1 t1) (recur arg1))
  17218. (define-values (e2 t2) (recur arg2))
  17219. (match* (t1 t2)
  17220. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17221. [(other wise) (check-type-equal? t1 t2 e)])
  17222. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17223. [else ((super type-check-exp env) e)])))
  17224. ))
  17225. \end{lstlisting}
  17226. \fi}
  17227. {\if\edition\pythonEd
  17228. \begin{lstlisting}
  17229. class TypeCheckLany(TypeCheckLlambda):
  17230. def type_check_exp(self, e, env):
  17231. match e:
  17232. case Inject(value, typ):
  17233. self.check_exp(value, typ, env)
  17234. return AnyType()
  17235. case Project(value, typ):
  17236. self.check_exp(value, AnyType(), env)
  17237. return typ
  17238. case Call(Name('any_tuple_load'), [tup, index]):
  17239. self.check_exp(tup, AnyType(), env)
  17240. self.check_exp(index, IntType(), env)
  17241. return AnyType()
  17242. case Call(Name('any_len'), [tup]):
  17243. self.check_exp(tup, AnyType(), env)
  17244. return IntType()
  17245. case Call(Name('arity'), [fun]):
  17246. ty = self.type_check_exp(fun, env)
  17247. match ty:
  17248. case FunctionType(ps, rt):
  17249. return IntType()
  17250. case TupleType([FunctionType(ps,rs)]):
  17251. return IntType()
  17252. case _:
  17253. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17254. case Call(Name('make_any'), [value, tag]):
  17255. self.type_check_exp(value, env)
  17256. self.check_exp(tag, IntType(), env)
  17257. return AnyType()
  17258. case AnnLambda(params, returns, body):
  17259. new_env = {x:t for (x,t) in env.items()}
  17260. for (x,t) in params:
  17261. new_env[x] = t
  17262. return_t = self.type_check_exp(body, new_env)
  17263. self.check_type_equal(returns, return_t, e)
  17264. return FunctionType([t for (x,t) in params], return_t)
  17265. case _:
  17266. return super().type_check_exp(e, env)
  17267. \end{lstlisting}
  17268. \fi}
  17269. \end{tcolorbox}
  17270. \caption{Type checker for the \LangAny{} language.}
  17271. \label{fig:type-check-Lany}
  17272. \end{figure}
  17273. {\if\edition\racketEd
  17274. \begin{figure}[tbp]
  17275. \begin{tcolorbox}[colback=white]
  17276. \begin{lstlisting}
  17277. (define/override (operator-types)
  17278. (append
  17279. '((integer? . ((Any) . Boolean))
  17280. (vector? . ((Any) . Boolean))
  17281. (procedure? . ((Any) . Boolean))
  17282. (void? . ((Any) . Boolean)))
  17283. (super operator-types)))
  17284. (define/public (type-predicates)
  17285. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17286. (define/public (flat-ty? ty)
  17287. (match ty
  17288. [(or `Integer `Boolean `Void) #t]
  17289. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17290. [`(,ts ... -> ,rt)
  17291. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17292. [else #f]))
  17293. \end{lstlisting}
  17294. \end{tcolorbox}
  17295. \caption{Auxiliary methods for type checking \LangAny{}.}
  17296. \label{fig:type-check-Lany-aux}
  17297. \end{figure}
  17298. \fi}
  17299. \begin{figure}[btp]
  17300. \begin{tcolorbox}[colback=white]
  17301. {\if\edition\racketEd
  17302. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17303. (define interp-Lany-class
  17304. (class interp-Llambda-class
  17305. (super-new)
  17306. (define/override (interp-op op)
  17307. (match op
  17308. ['boolean? (match-lambda
  17309. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17310. [else #f])]
  17311. ['integer? (match-lambda
  17312. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17313. [else #f])]
  17314. ['vector? (match-lambda
  17315. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17316. [else #f])]
  17317. ['procedure? (match-lambda
  17318. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17319. [else #f])]
  17320. ['eq? (match-lambda*
  17321. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17322. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17323. [ls (apply (super interp-op op) ls)])]
  17324. ['any-vector-ref (lambda (v i)
  17325. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17326. ['any-vector-set! (lambda (v i a)
  17327. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17328. ['any-vector-length (lambda (v)
  17329. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17330. [else (super interp-op op)]))
  17331. (define/override ((interp-exp env) e)
  17332. (define recur (interp-exp env))
  17333. (match e
  17334. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17335. [(Project e ty2) (apply-project (recur e) ty2)]
  17336. [else ((super interp-exp env) e)]))
  17337. ))
  17338. (define (interp-Lany p)
  17339. (send (new interp-Lany-class) interp-program p))
  17340. \end{lstlisting}
  17341. \fi}
  17342. {\if\edition\pythonEd
  17343. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17344. class InterpLany(InterpLlambda):
  17345. def interp_exp(self, e, env):
  17346. match e:
  17347. case Inject(value, typ):
  17348. v = self.interp_exp(value, env)
  17349. return Tagged(v, self.type_to_tag(typ))
  17350. case Project(value, typ):
  17351. v = self.interp_exp(value, env)
  17352. match v:
  17353. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17354. return val
  17355. case _:
  17356. raise Exception('interp project to ' + repr(typ)
  17357. + ' unexpected ' + repr(v))
  17358. case Call(Name('any_tuple_load'), [tup, index]):
  17359. tv = self.interp_exp(tup, env)
  17360. n = self.interp_exp(index, env)
  17361. match tv:
  17362. case Tagged(v, tag):
  17363. return v[n]
  17364. case _:
  17365. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17366. case Call(Name('any_len'), [value]):
  17367. v = self.interp_exp(value, env)
  17368. match v:
  17369. case Tagged(value, tag):
  17370. return len(value)
  17371. case _:
  17372. raise Exception('interp any_len unexpected ' + repr(v))
  17373. case Call(Name('arity'), [fun]):
  17374. f = self.interp_exp(fun, env)
  17375. return self.arity(f)
  17376. case _:
  17377. return super().interp_exp(e, env)
  17378. \end{lstlisting}
  17379. \fi}
  17380. \end{tcolorbox}
  17381. \caption{Interpreter for \LangAny{}.}
  17382. \label{fig:interp-Lany}
  17383. \end{figure}
  17384. \begin{figure}[tbp]
  17385. \begin{tcolorbox}[colback=white]
  17386. {\if\edition\racketEd
  17387. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17388. (define/public (apply-inject v tg) (Tagged v tg))
  17389. (define/public (apply-project v ty2)
  17390. (define tag2 (any-tag ty2))
  17391. (match v
  17392. [(Tagged v1 tag1)
  17393. (cond
  17394. [(eq? tag1 tag2)
  17395. (match ty2
  17396. [`(Vector ,ts ...)
  17397. (define l1 ((interp-op 'vector-length) v1))
  17398. (cond
  17399. [(eq? l1 (length ts)) v1]
  17400. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17401. l1 (length ts))])]
  17402. [`(,ts ... -> ,rt)
  17403. (match v1
  17404. [`(function ,xs ,body ,env)
  17405. (cond [(eq? (length xs) (length ts)) v1]
  17406. [else
  17407. (error 'apply-project "arity mismatch ~a != ~a"
  17408. (length xs) (length ts))])]
  17409. [else (error 'apply-project "expected function not ~a" v1)])]
  17410. [else v1])]
  17411. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17412. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17413. \end{lstlisting}
  17414. \fi}
  17415. {\if\edition\pythonEd
  17416. \begin{lstlisting}
  17417. class InterpLany(InterpLlambda):
  17418. def type_to_tag(self, typ):
  17419. match typ:
  17420. case FunctionType(params, rt):
  17421. return 'function'
  17422. case TupleType(fields):
  17423. return 'tuple'
  17424. case t if t == int:
  17425. return 'int'
  17426. case t if t == bool:
  17427. return 'bool'
  17428. case IntType():
  17429. return 'int'
  17430. case BoolType():
  17431. return 'int'
  17432. case _:
  17433. raise Exception('type_to_tag unexpected ' + repr(typ))
  17434. def arity(self, v):
  17435. match v:
  17436. case Function(name, params, body, env):
  17437. return len(params)
  17438. case ClosureTuple(args, arity):
  17439. return arity
  17440. case _:
  17441. raise Exception('Lany arity unexpected ' + repr(v))
  17442. \end{lstlisting}
  17443. \fi}
  17444. \end{tcolorbox}
  17445. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17446. \label{fig:interp-Lany-aux}
  17447. \end{figure}
  17448. \clearpage
  17449. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17450. \label{sec:compile-r7}
  17451. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17452. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17453. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17454. is that given any subexpression $e$ in the \LangDyn{} program, the
  17455. pass will produce an expression $e'$ in \LangAny{} that has type
  17456. \ANYTY{}. For example, the first row in
  17457. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17458. \TRUE{}, which must be injected to produce an expression of type
  17459. \ANYTY{}.
  17460. %
  17461. The compilation of addition is shown in the second row of
  17462. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17463. representative of many primitive operations: the arguments have type
  17464. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17465. be performed.
  17466. The compilation of \key{lambda} (third row of
  17467. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17468. produce type annotations: we simply use \ANYTY{}.
  17469. %
  17470. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17471. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17472. this pass has to account for some differences in behavior between
  17473. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17474. permissive than \LangAny{} regarding what kind of values can be used
  17475. in various places. For example, the condition of an \key{if} does
  17476. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17477. of the same type (in that case the result is \code{\#f}).}
  17478. \begin{figure}[btp]
  17479. \centering
  17480. \begin{tcolorbox}[colback=white]
  17481. {\if\edition\racketEd
  17482. \begin{tabular}{lll}
  17483. \begin{minipage}{0.27\textwidth}
  17484. \begin{lstlisting}
  17485. #t
  17486. \end{lstlisting}
  17487. \end{minipage}
  17488. &
  17489. $\Rightarrow$
  17490. &
  17491. \begin{minipage}{0.65\textwidth}
  17492. \begin{lstlisting}
  17493. (inject #t Boolean)
  17494. \end{lstlisting}
  17495. \end{minipage}
  17496. \\[2ex]\hline
  17497. \begin{minipage}{0.27\textwidth}
  17498. \begin{lstlisting}
  17499. (+ |$e_1$| |$e_2$|)
  17500. \end{lstlisting}
  17501. \end{minipage}
  17502. &
  17503. $\Rightarrow$
  17504. &
  17505. \begin{minipage}{0.65\textwidth}
  17506. \begin{lstlisting}
  17507. (inject
  17508. (+ (project |$e'_1$| Integer)
  17509. (project |$e'_2$| Integer))
  17510. Integer)
  17511. \end{lstlisting}
  17512. \end{minipage}
  17513. \\[2ex]\hline
  17514. \begin{minipage}{0.27\textwidth}
  17515. \begin{lstlisting}
  17516. (lambda (|$x_1 \ldots$|) |$e$|)
  17517. \end{lstlisting}
  17518. \end{minipage}
  17519. &
  17520. $\Rightarrow$
  17521. &
  17522. \begin{minipage}{0.65\textwidth}
  17523. \begin{lstlisting}
  17524. (inject
  17525. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17526. (Any|$\ldots$|Any -> Any))
  17527. \end{lstlisting}
  17528. \end{minipage}
  17529. \\[2ex]\hline
  17530. \begin{minipage}{0.27\textwidth}
  17531. \begin{lstlisting}
  17532. (|$e_0$| |$e_1 \ldots e_n$|)
  17533. \end{lstlisting}
  17534. \end{minipage}
  17535. &
  17536. $\Rightarrow$
  17537. &
  17538. \begin{minipage}{0.65\textwidth}
  17539. \begin{lstlisting}
  17540. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17541. \end{lstlisting}
  17542. \end{minipage}
  17543. \\[2ex]\hline
  17544. \begin{minipage}{0.27\textwidth}
  17545. \begin{lstlisting}
  17546. (vector-ref |$e_1$| |$e_2$|)
  17547. \end{lstlisting}
  17548. \end{minipage}
  17549. &
  17550. $\Rightarrow$
  17551. &
  17552. \begin{minipage}{0.65\textwidth}
  17553. \begin{lstlisting}
  17554. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17555. \end{lstlisting}
  17556. \end{minipage}
  17557. \\[2ex]\hline
  17558. \begin{minipage}{0.27\textwidth}
  17559. \begin{lstlisting}
  17560. (if |$e_1$| |$e_2$| |$e_3$|)
  17561. \end{lstlisting}
  17562. \end{minipage}
  17563. &
  17564. $\Rightarrow$
  17565. &
  17566. \begin{minipage}{0.65\textwidth}
  17567. \begin{lstlisting}
  17568. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17569. \end{lstlisting}
  17570. \end{minipage}
  17571. \\[2ex]\hline
  17572. \begin{minipage}{0.27\textwidth}
  17573. \begin{lstlisting}
  17574. (eq? |$e_1$| |$e_2$|)
  17575. \end{lstlisting}
  17576. \end{minipage}
  17577. &
  17578. $\Rightarrow$
  17579. &
  17580. \begin{minipage}{0.65\textwidth}
  17581. \begin{lstlisting}
  17582. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17583. \end{lstlisting}
  17584. \end{minipage}
  17585. \\[2ex]\hline
  17586. \begin{minipage}{0.27\textwidth}
  17587. \begin{lstlisting}
  17588. (not |$e_1$|)
  17589. \end{lstlisting}
  17590. \end{minipage}
  17591. &
  17592. $\Rightarrow$
  17593. &
  17594. \begin{minipage}{0.65\textwidth}
  17595. \begin{lstlisting}
  17596. (if (eq? |$e'_1$| (inject #f Boolean))
  17597. (inject #t Boolean) (inject #f Boolean))
  17598. \end{lstlisting}
  17599. \end{minipage}
  17600. \end{tabular}
  17601. \fi}
  17602. {\if\edition\pythonEd
  17603. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17604. \begin{minipage}{0.23\textwidth}
  17605. \begin{lstlisting}
  17606. True
  17607. \end{lstlisting}
  17608. \end{minipage}
  17609. &
  17610. $\Rightarrow$
  17611. &
  17612. \begin{minipage}{0.7\textwidth}
  17613. \begin{lstlisting}
  17614. Inject(True, BoolType())
  17615. \end{lstlisting}
  17616. \end{minipage}
  17617. \\[2ex]\hline
  17618. \begin{minipage}{0.23\textwidth}
  17619. \begin{lstlisting}
  17620. |$e_1$| + |$e_2$|
  17621. \end{lstlisting}
  17622. \end{minipage}
  17623. &
  17624. $\Rightarrow$
  17625. &
  17626. \begin{minipage}{0.7\textwidth}
  17627. \begin{lstlisting}
  17628. Inject(Project(|$e'_1$|, IntType())
  17629. + Project(|$e'_2$|, IntType()),
  17630. IntType())
  17631. \end{lstlisting}
  17632. \end{minipage}
  17633. \\[2ex]\hline
  17634. \begin{minipage}{0.23\textwidth}
  17635. \begin{lstlisting}
  17636. lambda |$x_1 \ldots$|: |$e$|
  17637. \end{lstlisting}
  17638. \end{minipage}
  17639. &
  17640. $\Rightarrow$
  17641. &
  17642. \begin{minipage}{0.7\textwidth}
  17643. \begin{lstlisting}
  17644. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17645. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17646. \end{lstlisting}
  17647. \end{minipage}
  17648. \\[2ex]\hline
  17649. \begin{minipage}{0.23\textwidth}
  17650. \begin{lstlisting}
  17651. |$e_0$|(|$e_1 \ldots e_n$|)
  17652. \end{lstlisting}
  17653. \end{minipage}
  17654. &
  17655. $\Rightarrow$
  17656. &
  17657. \begin{minipage}{0.7\textwidth}
  17658. \begin{lstlisting}
  17659. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17660. AnyType())), |$e'_1, \ldots, e'_n$|)
  17661. \end{lstlisting}
  17662. \end{minipage}
  17663. \\[2ex]\hline
  17664. \begin{minipage}{0.23\textwidth}
  17665. \begin{lstlisting}
  17666. |$e_1$|[|$e_2$|]
  17667. \end{lstlisting}
  17668. \end{minipage}
  17669. &
  17670. $\Rightarrow$
  17671. &
  17672. \begin{minipage}{0.7\textwidth}
  17673. \begin{lstlisting}
  17674. Call(Name('any_tuple_load'),
  17675. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17676. \end{lstlisting}
  17677. \end{minipage}
  17678. %% \begin{minipage}{0.23\textwidth}
  17679. %% \begin{lstlisting}
  17680. %% |$e_2$| if |$e_1$| else |$e_3$|
  17681. %% \end{lstlisting}
  17682. %% \end{minipage}
  17683. %% &
  17684. %% $\Rightarrow$
  17685. %% &
  17686. %% \begin{minipage}{0.7\textwidth}
  17687. %% \begin{lstlisting}
  17688. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17689. %% \end{lstlisting}
  17690. %% \end{minipage}
  17691. %% \\[2ex]\hline
  17692. %% \begin{minipage}{0.23\textwidth}
  17693. %% \begin{lstlisting}
  17694. %% (eq? |$e_1$| |$e_2$|)
  17695. %% \end{lstlisting}
  17696. %% \end{minipage}
  17697. %% &
  17698. %% $\Rightarrow$
  17699. %% &
  17700. %% \begin{minipage}{0.7\textwidth}
  17701. %% \begin{lstlisting}
  17702. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17703. %% \end{lstlisting}
  17704. %% \end{minipage}
  17705. %% \\[2ex]\hline
  17706. %% \begin{minipage}{0.23\textwidth}
  17707. %% \begin{lstlisting}
  17708. %% (not |$e_1$|)
  17709. %% \end{lstlisting}
  17710. %% \end{minipage}
  17711. %% &
  17712. %% $\Rightarrow$
  17713. %% &
  17714. %% \begin{minipage}{0.7\textwidth}
  17715. %% \begin{lstlisting}
  17716. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17717. %% (inject #t Boolean) (inject #f Boolean))
  17718. %% \end{lstlisting}
  17719. %% \end{minipage}
  17720. %% \\[2ex]\hline
  17721. \\\hline
  17722. \end{tabular}
  17723. \fi}
  17724. \end{tcolorbox}
  17725. \caption{Cast insertion}
  17726. \label{fig:compile-r7-Lany}
  17727. \end{figure}
  17728. \section{Reveal Casts}
  17729. \label{sec:reveal-casts-Lany}
  17730. % TODO: define R'_6
  17731. In the \code{reveal\_casts} pass, we recommend compiling
  17732. \code{Project} into a conditional expression that checks whether the
  17733. value's tag matches the target type; if it does, the value is
  17734. converted to a value of the target type by removing the tag; if it
  17735. does not, the program exits.
  17736. %
  17737. {\if\edition\racketEd
  17738. %
  17739. To perform these actions we need a new primitive operation,
  17740. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17741. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17742. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17743. underlying value from a tagged value. The \code{ValueOf} form
  17744. includes the type for the underlying value that is used by the type
  17745. checker.
  17746. %
  17747. \fi}
  17748. %
  17749. {\if\edition\pythonEd
  17750. %
  17751. To perform these actions we need two new AST classes: \code{TagOf} and
  17752. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17753. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17754. the underlying value from a tagged value. The \code{ValueOf}
  17755. operation includes the type for the underlying value which is used by
  17756. the type checker.
  17757. %
  17758. \fi}
  17759. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17760. \code{Project} can be translated as follows.
  17761. \begin{center}
  17762. \begin{minipage}{1.0\textwidth}
  17763. {\if\edition\racketEd
  17764. \begin{lstlisting}
  17765. (Project |$e$| |$\FType$|)
  17766. |$\Rightarrow$|
  17767. (Let |$\itm{tmp}$| |$e'$|
  17768. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17769. (Int |$\itm{tagof}(\FType)$|)))
  17770. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17771. (Exit)))
  17772. \end{lstlisting}
  17773. \fi}
  17774. {\if\edition\pythonEd
  17775. \begin{lstlisting}
  17776. Project(|$e$|, |$\FType$|)
  17777. |$\Rightarrow$|
  17778. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17779. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17780. [Constant(|$\itm{tagof}(\FType)$|)]),
  17781. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17782. Call(Name('exit'), [])))
  17783. \end{lstlisting}
  17784. \fi}
  17785. \end{minipage}
  17786. \end{center}
  17787. If the target type of the projection is a tuple or function type, then
  17788. there is a bit more work to do. For tuples, check that the length of
  17789. the tuple type matches the length of the tuple. For functions, check
  17790. that the number of parameters in the function type matches the
  17791. function's arity.
  17792. Regarding \code{Inject}, we recommend compiling it to a slightly
  17793. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17794. takes a tag instead of a type.
  17795. \begin{center}
  17796. \begin{minipage}{1.0\textwidth}
  17797. {\if\edition\racketEd
  17798. \begin{lstlisting}
  17799. (Inject |$e$| |$\FType$|)
  17800. |$\Rightarrow$|
  17801. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17802. \end{lstlisting}
  17803. \fi}
  17804. {\if\edition\pythonEd
  17805. \begin{lstlisting}
  17806. Inject(|$e$|, |$\FType$|)
  17807. |$\Rightarrow$|
  17808. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17809. \end{lstlisting}
  17810. \fi}
  17811. \end{minipage}
  17812. \end{center}
  17813. {\if\edition\pythonEd
  17814. %
  17815. The introduction of \code{make\_any} makes it difficult to use
  17816. bidirectional type checking because we no longer have an expected type
  17817. to use for type checking the expression $e'$. Thus, we run into
  17818. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17819. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17820. annotated lambda) whose parameters have type annotations and that
  17821. records the return type.
  17822. %
  17823. \fi}
  17824. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17825. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17826. translation of \code{Project}.}
  17827. {\if\edition\racketEd
  17828. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17829. combine the projection action with the vector operation. Also, the
  17830. read and write operations allow arbitrary expressions for the index, so
  17831. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17832. cannot guarantee that the index is within bounds. Thus, we insert code
  17833. to perform bounds checking at runtime. The translation for
  17834. \code{any-vector-ref} is as follows, and the other two operations are
  17835. translated in a similar way:
  17836. \begin{center}
  17837. \begin{minipage}{0.95\textwidth}
  17838. \begin{lstlisting}
  17839. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17840. |$\Rightarrow$|
  17841. (Let |$v$| |$e'_1$|
  17842. (Let |$i$| |$e'_2$|
  17843. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17844. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17845. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17846. (Exit))
  17847. (Exit))))
  17848. \end{lstlisting}
  17849. \end{minipage}
  17850. \end{center}
  17851. \fi}
  17852. %
  17853. {\if\edition\pythonEd
  17854. %
  17855. The \code{any\_tuple\_load} operation combines the projection action
  17856. with the load operation. Also, the load operation allows arbitrary
  17857. expressions for the index so the type checker for \LangAny{}
  17858. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17859. within bounds. Thus, we insert code to perform bounds checking at
  17860. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17861. \begin{lstlisting}
  17862. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17863. |$\Rightarrow$|
  17864. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17865. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17866. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17867. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17868. Call(Name('exit'), [])),
  17869. Call(Name('exit'), [])))
  17870. \end{lstlisting}
  17871. \fi}
  17872. {\if\edition\pythonEd
  17873. \section{Assignment Conversion}
  17874. \label{sec:convert-assignments-Lany}
  17875. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17876. \code{AnnLambda} AST classes.
  17877. \section{Closure Conversion}
  17878. \label{sec:closure-conversion-Lany}
  17879. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17880. \code{AnnLambda} AST classes.
  17881. \fi}
  17882. \section{Remove Complex Operands}
  17883. \label{sec:rco-Lany}
  17884. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17885. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17886. %
  17887. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17888. complex expressions. Their subexpressions must be atomic.}
  17889. \section{Explicate Control and \LangCAny{}}
  17890. \label{sec:explicate-Lany}
  17891. The output of \code{explicate\_control} is the \LangCAny{} language,
  17892. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17893. %
  17894. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17895. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17896. note that the index argument of \code{vector-ref} and
  17897. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17898. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17899. %
  17900. \python{
  17901. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17902. and \code{explicate\_pred} as appropriately to handle the new expressions
  17903. in \LangCAny{}.
  17904. }
  17905. \newcommand{\CanyASTPython}{
  17906. \begin{array}{lcl}
  17907. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17908. &\MID& \key{TagOf}\LP \Atm \RP
  17909. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17910. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17911. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17912. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17913. \end{array}
  17914. }
  17915. \newcommand{\CanyASTRacket}{
  17916. \begin{array}{lcl}
  17917. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17918. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17919. &\MID& \VALUEOF{\Atm}{\FType} \\
  17920. \Tail &::= & \LP\key{Exit}\RP
  17921. \end{array}
  17922. }
  17923. \begin{figure}[tp]
  17924. \begin{tcolorbox}[colback=white]
  17925. \small
  17926. {\if\edition\racketEd
  17927. \[
  17928. \begin{array}{l}
  17929. \gray{\CvarASTRacket} \\ \hline
  17930. \gray{\CifASTRacket} \\ \hline
  17931. \gray{\CloopASTRacket} \\ \hline
  17932. \gray{\CtupASTRacket} \\ \hline
  17933. \gray{\CfunASTRacket} \\ \hline
  17934. \gray{\ClambdaASTRacket} \\ \hline
  17935. \CanyASTRacket \\
  17936. \begin{array}{lcl}
  17937. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17938. \end{array}
  17939. \end{array}
  17940. \]
  17941. \fi}
  17942. {\if\edition\pythonEd
  17943. \[
  17944. \begin{array}{l}
  17945. \gray{\CifASTPython} \\ \hline
  17946. \gray{\CtupASTPython} \\ \hline
  17947. \gray{\CfunASTPython} \\ \hline
  17948. \gray{\ClambdaASTPython} \\ \hline
  17949. \CanyASTPython \\
  17950. \begin{array}{lcl}
  17951. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17952. \end{array}
  17953. \end{array}
  17954. \]
  17955. \fi}
  17956. \end{tcolorbox}
  17957. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17958. \label{fig:c5-syntax}
  17959. \end{figure}
  17960. \section{Select Instructions}
  17961. \label{sec:select-Lany}
  17962. In the \code{select\_instructions} pass, we translate the primitive
  17963. operations on the \ANYTY{} type to x86 instructions that manipulate
  17964. the three tag bits of the tagged value. In the following descriptions,
  17965. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17966. of translating $e$ into an x86 argument:
  17967. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17968. We recommend compiling the
  17969. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17970. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17971. shifts the destination to the left by the number of bits specified its
  17972. source argument (in this case three, the length of the tag), and it
  17973. preserves the sign of the integer. We use the \key{orq} instruction to
  17974. combine the tag and the value to form the tagged value. \\
  17975. %
  17976. {\if\edition\racketEd
  17977. \begin{lstlisting}
  17978. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17979. |$\Rightarrow$|
  17980. movq |$e'$|, |\itm{lhs'}|
  17981. salq $3, |\itm{lhs'}|
  17982. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17983. \end{lstlisting}
  17984. \fi}
  17985. %
  17986. {\if\edition\pythonEd
  17987. \begin{lstlisting}
  17988. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17989. |$\Rightarrow$|
  17990. movq |$e'$|, |\itm{lhs'}|
  17991. salq $3, |\itm{lhs'}|
  17992. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17993. \end{lstlisting}
  17994. \fi}
  17995. %
  17996. The instruction selection for tuples and procedures is different
  17997. because their is no need to shift them to the left. The rightmost 3
  17998. bits are already zeros, so we simply combine the value and the tag
  17999. using \key{orq}. \\
  18000. %
  18001. {\if\edition\racketEd
  18002. \begin{center}
  18003. \begin{minipage}{\textwidth}
  18004. \begin{lstlisting}
  18005. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18006. |$\Rightarrow$|
  18007. movq |$e'$|, |\itm{lhs'}|
  18008. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18009. \end{lstlisting}
  18010. \end{minipage}
  18011. \end{center}
  18012. \fi}
  18013. %
  18014. {\if\edition\pythonEd
  18015. \begin{lstlisting}
  18016. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18017. |$\Rightarrow$|
  18018. movq |$e'$|, |\itm{lhs'}|
  18019. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18020. \end{lstlisting}
  18021. \fi}
  18022. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18023. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18024. operation extracts the type tag from a value of type \ANYTY{}. The
  18025. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18026. bitwise-and of the value with $111$ ($7$ decimal).
  18027. %
  18028. {\if\edition\racketEd
  18029. \begin{lstlisting}
  18030. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18031. |$\Rightarrow$|
  18032. movq |$e'$|, |\itm{lhs'}|
  18033. andq $7, |\itm{lhs'}|
  18034. \end{lstlisting}
  18035. \fi}
  18036. %
  18037. {\if\edition\pythonEd
  18038. \begin{lstlisting}
  18039. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18040. |$\Rightarrow$|
  18041. movq |$e'$|, |\itm{lhs'}|
  18042. andq $7, |\itm{lhs'}|
  18043. \end{lstlisting}
  18044. \fi}
  18045. \paragraph{\code{ValueOf}}
  18046. The instructions for \key{ValueOf} also differ, depending on whether
  18047. the type $T$ is a pointer (tuple or function) or not (integer or
  18048. Boolean). The following shows the instruction selection for integers
  18049. and Booleans, in which we produce an untagged value by shifting it to
  18050. the right by 3 bits:
  18051. %
  18052. {\if\edition\racketEd
  18053. \begin{lstlisting}
  18054. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18055. |$\Rightarrow$|
  18056. movq |$e'$|, |\itm{lhs'}|
  18057. sarq $3, |\itm{lhs'}|
  18058. \end{lstlisting}
  18059. \fi}
  18060. %
  18061. {\if\edition\pythonEd
  18062. \begin{lstlisting}
  18063. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18064. |$\Rightarrow$|
  18065. movq |$e'$|, |\itm{lhs'}|
  18066. sarq $3, |\itm{lhs'}|
  18067. \end{lstlisting}
  18068. \fi}
  18069. %
  18070. In the case for tuples and procedures, we zero out the rightmost 3
  18071. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18072. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18073. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18074. Finally, we apply \code{andq} with the tagged value to get the desired
  18075. result.
  18076. %
  18077. {\if\edition\racketEd
  18078. \begin{lstlisting}
  18079. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18080. |$\Rightarrow$|
  18081. movq $|$-8$|, |\itm{lhs'}|
  18082. andq |$e'$|, |\itm{lhs'}|
  18083. \end{lstlisting}
  18084. \fi}
  18085. %
  18086. {\if\edition\pythonEd
  18087. \begin{lstlisting}
  18088. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18089. |$\Rightarrow$|
  18090. movq $|$-8$|, |\itm{lhs'}|
  18091. andq |$e'$|, |\itm{lhs'}|
  18092. \end{lstlisting}
  18093. \fi}
  18094. %% \paragraph{Type Predicates} We leave it to the reader to
  18095. %% devise a sequence of instructions to implement the type predicates
  18096. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18097. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18098. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18099. operation combines the effect of \code{ValueOf} with accessing the
  18100. length of a tuple from the tag stored at the zero index of the tuple.
  18101. {\if\edition\racketEd
  18102. \begin{lstlisting}
  18103. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18104. |$\Longrightarrow$|
  18105. movq $|$-8$|, %r11
  18106. andq |$e_1'$|, %r11
  18107. movq 0(%r11), %r11
  18108. andq $126, %r11
  18109. sarq $1, %r11
  18110. movq %r11, |$\itm{lhs'}$|
  18111. \end{lstlisting}
  18112. \fi}
  18113. {\if\edition\pythonEd
  18114. \begin{lstlisting}
  18115. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18116. |$\Longrightarrow$|
  18117. movq $|$-8$|, %r11
  18118. andq |$e_1'$|, %r11
  18119. movq 0(%r11), %r11
  18120. andq $126, %r11
  18121. sarq $1, %r11
  18122. movq %r11, |$\itm{lhs'}$|
  18123. \end{lstlisting}
  18124. \fi}
  18125. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18126. This operation combines the effect of \code{ValueOf} with reading an
  18127. element of the tuple (see
  18128. section~\ref{sec:select-instructions-gc}). However, the index may be
  18129. an arbitrary atom, so instead of computing the offset at compile time,
  18130. we must generate instructions to compute the offset at runtime as
  18131. follows. Note the use of the new instruction \code{imulq}.
  18132. \begin{center}
  18133. \begin{minipage}{0.96\textwidth}
  18134. {\if\edition\racketEd
  18135. \begin{lstlisting}
  18136. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18137. |$\Longrightarrow$|
  18138. movq |$\neg 111$|, %r11
  18139. andq |$e_1'$|, %r11
  18140. movq |$e_2'$|, %rax
  18141. addq $1, %rax
  18142. imulq $8, %rax
  18143. addq %rax, %r11
  18144. movq 0(%r11) |$\itm{lhs'}$|
  18145. \end{lstlisting}
  18146. \fi}
  18147. %
  18148. {\if\edition\pythonEd
  18149. \begin{lstlisting}
  18150. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18151. |$\Longrightarrow$|
  18152. movq $|$-8$|, %r11
  18153. andq |$e_1'$|, %r11
  18154. movq |$e_2'$|, %rax
  18155. addq $1, %rax
  18156. imulq $8, %rax
  18157. addq %rax, %r11
  18158. movq 0(%r11) |$\itm{lhs'}$|
  18159. \end{lstlisting}
  18160. \fi}
  18161. \end{minipage}
  18162. \end{center}
  18163. % $ pacify font lock
  18164. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18165. %% The code generation for
  18166. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18167. %% analogous to the above translation for reading from a tuple.
  18168. \section{Register Allocation for \LangAny{}}
  18169. \label{sec:register-allocation-Lany}
  18170. \index{subject}{register allocation}
  18171. There is an interesting interaction between tagged values and garbage
  18172. collection that has an impact on register allocation. A variable of
  18173. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18174. that needs to be inspected and copied during garbage collection. Thus,
  18175. we need to treat variables of type \ANYTY{} in a similar way to
  18176. variables of tuple type for purposes of register allocation,
  18177. with particular attention to the following:
  18178. \begin{itemize}
  18179. \item If a variable of type \ANYTY{} is live during a function call,
  18180. then it must be spilled. This can be accomplished by changing
  18181. \code{build\_interference} to mark all variables of type \ANYTY{}
  18182. that are live after a \code{callq} to be interfering with all the
  18183. registers.
  18184. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18185. the root stack instead of the normal procedure call stack.
  18186. \end{itemize}
  18187. Another concern regarding the root stack is that the garbage collector
  18188. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18189. tagged value that points to a tuple, and (3) a tagged value that is
  18190. not a tuple. We enable this differentiation by choosing not to use the
  18191. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18192. reserved for identifying plain old pointers to tuples. That way, if
  18193. one of the first three bits is set, then we have a tagged value and
  18194. inspecting the tag can differentiate between tuples ($010$) and the
  18195. other kinds of values.
  18196. %% \begin{exercise}\normalfont
  18197. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18198. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18199. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18200. %% compiler on these new programs and all of your previously created test
  18201. %% programs.
  18202. %% \end{exercise}
  18203. \begin{exercise}\normalfont\normalsize
  18204. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18205. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18206. by removing type annotations. Add five more test programs that
  18207. specifically rely on the language being dynamically typed. That is,
  18208. they should not be legal programs in a statically typed language, but
  18209. nevertheless they should be valid \LangDyn{} programs that run to
  18210. completion without error.
  18211. \end{exercise}
  18212. \begin{figure}[p]
  18213. \begin{tcolorbox}[colback=white]
  18214. {\if\edition\racketEd
  18215. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18216. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18217. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18218. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18219. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18220. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18221. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18222. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18223. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18224. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18225. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18226. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18227. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18228. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18229. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18230. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18231. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18232. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18233. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18234. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18235. \path[->,bend left=15] (Lfun) edge [above] node
  18236. {\ttfamily\footnotesize shrink} (Lfun-2);
  18237. \path[->,bend left=15] (Lfun-2) edge [above] node
  18238. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18239. \path[->,bend left=15] (Lfun-3) edge [above] node
  18240. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18241. \path[->,bend left=15] (Lfun-4) edge [left] node
  18242. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18243. \path[->,bend left=15] (Lfun-5) edge [below] node
  18244. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18245. \path[->,bend left=15] (Lfun-6) edge [below] node
  18246. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18247. \path[->,bend right=15] (Lfun-7) edge [above] node
  18248. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18249. \path[->,bend right=15] (F1-2) edge [right] node
  18250. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18251. \path[->,bend right=15] (F1-3) edge [below] node
  18252. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18253. \path[->,bend right=15] (F1-4) edge [below] node
  18254. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18255. \path[->,bend left=15] (F1-5) edge [above] node
  18256. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18257. \path[->,bend left=15] (F1-6) edge [below] node
  18258. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18259. \path[->,bend left=15] (C3-2) edge [right] node
  18260. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18261. \path[->,bend right=15] (x86-2) edge [right] node
  18262. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18263. \path[->,bend right=15] (x86-2-1) edge [below] node
  18264. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18265. \path[->,bend right=15] (x86-2-2) edge [right] node
  18266. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18267. \path[->,bend left=15] (x86-3) edge [above] node
  18268. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18269. \path[->,bend left=15] (x86-4) edge [right] node
  18270. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18271. \end{tikzpicture}
  18272. \fi}
  18273. {\if\edition\pythonEd
  18274. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18275. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18276. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18277. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18278. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18279. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18280. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18281. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18282. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18283. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18284. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18285. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18286. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18287. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18288. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18289. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18290. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18291. \path[->,bend left=15] (Lfun) edge [above] node
  18292. {\ttfamily\footnotesize shrink} (Lfun-2);
  18293. \path[->,bend left=15] (Lfun-2) edge [above] node
  18294. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18295. \path[->,bend left=15] (Lfun-3) edge [above] node
  18296. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18297. \path[->,bend left=15] (Lfun-4) edge [left] node
  18298. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18299. \path[->,bend left=15] (Lfun-5) edge [below] node
  18300. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18301. \path[->,bend right=15] (Lfun-6) edge [above] node
  18302. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18303. \path[->,bend right=15] (Lfun-7) edge [above] node
  18304. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18305. \path[->,bend right=15] (F1-2) edge [right] node
  18306. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18307. \path[->,bend right=15] (F1-3) edge [below] node
  18308. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18309. \path[->,bend left=15] (F1-5) edge [above] node
  18310. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18311. \path[->,bend left=15] (F1-6) edge [below] node
  18312. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18313. \path[->,bend right=15] (C3-2) edge [right] node
  18314. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18315. \path[->,bend right=15] (x86-2) edge [below] node
  18316. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18317. \path[->,bend right=15] (x86-3) edge [below] node
  18318. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18319. \path[->,bend left=15] (x86-4) edge [above] node
  18320. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18321. \end{tikzpicture}
  18322. \fi}
  18323. \end{tcolorbox}
  18324. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18325. \label{fig:Ldyn-passes}
  18326. \end{figure}
  18327. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18328. for the compilation of \LangDyn{}.
  18329. % Further Reading
  18330. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18331. %% {\if\edition\pythonEd
  18332. %% \chapter{Objects}
  18333. %% \label{ch:Lobject}
  18334. %% \index{subject}{objects}
  18335. %% \index{subject}{classes}
  18336. %% \setcounter{footnote}{0}
  18337. %% \fi}
  18338. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18339. \chapter{Gradual Typing}
  18340. \label{ch:Lgrad}
  18341. \index{subject}{gradual typing}
  18342. \setcounter{footnote}{0}
  18343. This chapter studies the language \LangGrad{}, in which the programmer
  18344. can choose between static and dynamic type checking in different parts
  18345. of a program, thereby mixing the statically typed \LangLam{} language
  18346. with the dynamically typed \LangDyn{}. There are several approaches to
  18347. mixing static and dynamic typing, including multilanguage
  18348. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18349. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18350. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18351. programmer controls the amount of static versus dynamic checking by
  18352. adding or removing type annotations on parameters and
  18353. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18354. The definition of the concrete syntax of \LangGrad{} is shown in
  18355. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  18356. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18357. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18358. annotations are optional, which is specified in the grammar using the
  18359. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18360. annotations are not optional, but we use the \CANYTY{} type when a type
  18361. annotation is absent.
  18362. %
  18363. Both the type checker and the interpreter for \LangGrad{} require some
  18364. interesting changes to enable gradual typing, which we discuss in the
  18365. next two sections.
  18366. \newcommand{\LgradGrammarRacket}{
  18367. \begin{array}{lcl}
  18368. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18369. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18370. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18371. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18372. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18373. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18374. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18375. \end{array}
  18376. }
  18377. \newcommand{\LgradASTRacket}{
  18378. \begin{array}{lcl}
  18379. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18380. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18381. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18382. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18383. \itm{op} &::=& \code{procedure-arity} \\
  18384. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18385. \end{array}
  18386. }
  18387. \newcommand{\LgradGrammarPython}{
  18388. \begin{array}{lcl}
  18389. \Type &::=& \key{Any}
  18390. \MID \key{int}
  18391. \MID \key{bool}
  18392. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18393. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18394. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18395. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18396. \MID \CARITY{\Exp} \\
  18397. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18398. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18399. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18400. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18401. \end{array}
  18402. }
  18403. \newcommand{\LgradASTPython}{
  18404. \begin{array}{lcl}
  18405. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18406. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18407. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18408. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18409. &\MID& \ARITY{\Exp} \\
  18410. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18411. \MID \RETURN{\Exp} \\
  18412. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18413. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18414. \end{array}
  18415. }
  18416. \begin{figure}[tp]
  18417. \centering
  18418. \begin{tcolorbox}[colback=white]
  18419. \small
  18420. {\if\edition\racketEd
  18421. \[
  18422. \begin{array}{l}
  18423. \gray{\LintGrammarRacket{}} \\ \hline
  18424. \gray{\LvarGrammarRacket{}} \\ \hline
  18425. \gray{\LifGrammarRacket{}} \\ \hline
  18426. \gray{\LwhileGrammarRacket} \\ \hline
  18427. \gray{\LtupGrammarRacket} \\ \hline
  18428. \LgradGrammarRacket \\
  18429. \begin{array}{lcl}
  18430. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18431. \end{array}
  18432. \end{array}
  18433. \]
  18434. \fi}
  18435. {\if\edition\pythonEd
  18436. \[
  18437. \begin{array}{l}
  18438. \gray{\LintGrammarPython{}} \\ \hline
  18439. \gray{\LvarGrammarPython{}} \\ \hline
  18440. \gray{\LifGrammarPython{}} \\ \hline
  18441. \gray{\LwhileGrammarPython} \\ \hline
  18442. \gray{\LtupGrammarPython} \\ \hline
  18443. \LgradGrammarPython \\
  18444. \begin{array}{lcl}
  18445. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18446. \end{array}
  18447. \end{array}
  18448. \]
  18449. \fi}
  18450. \end{tcolorbox}
  18451. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18452. \label{fig:Lgrad-concrete-syntax}
  18453. \end{figure}
  18454. \begin{figure}[tp]
  18455. \centering
  18456. \begin{tcolorbox}[colback=white]
  18457. \small
  18458. {\if\edition\racketEd
  18459. \[
  18460. \begin{array}{l}
  18461. \gray{\LintOpAST} \\ \hline
  18462. \gray{\LvarASTRacket{}} \\ \hline
  18463. \gray{\LifASTRacket{}} \\ \hline
  18464. \gray{\LwhileASTRacket{}} \\ \hline
  18465. \gray{\LtupASTRacket{}} \\ \hline
  18466. \LgradASTRacket \\
  18467. \begin{array}{lcl}
  18468. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18469. \end{array}
  18470. \end{array}
  18471. \]
  18472. \fi}
  18473. {\if\edition\pythonEd
  18474. \[
  18475. \begin{array}{l}
  18476. \gray{\LintASTPython{}} \\ \hline
  18477. \gray{\LvarASTPython{}} \\ \hline
  18478. \gray{\LifASTPython{}} \\ \hline
  18479. \gray{\LwhileASTPython} \\ \hline
  18480. \gray{\LtupASTPython} \\ \hline
  18481. \LgradASTPython \\
  18482. \begin{array}{lcl}
  18483. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18484. \end{array}
  18485. \end{array}
  18486. \]
  18487. \fi}
  18488. \end{tcolorbox}
  18489. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18490. \label{fig:Lgrad-syntax}
  18491. \end{figure}
  18492. % TODO: more road map -Jeremy
  18493. %\clearpage
  18494. \section{Type Checking \LangGrad{}}
  18495. \label{sec:gradual-type-check}
  18496. We begin by discussing the type checking of a partially typed variant
  18497. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18498. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18499. statically typed, so there is nothing special happening there with
  18500. respect to type checking. On the other hand, the \code{inc} function
  18501. does not have type annotations, so the type checker assigns the type
  18502. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18503. \code{+} operator inside \code{inc}. It expects both arguments to have
  18504. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18505. a gradually typed language, such differences are allowed so long as
  18506. the types are \emph{consistent}; that is, they are equal except in
  18507. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18508. is consistent with every other type. Figure~\ref{fig:consistent}
  18509. shows the definition of the
  18510. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18511. %
  18512. So the type checker allows the \code{+} operator to be applied
  18513. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18514. %
  18515. Next consider the call to the \code{map} function shown in
  18516. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18517. tuple. The \code{inc} function has type
  18518. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18519. but parameter \code{f} of \code{map} has type
  18520. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18521. The type checker for \LangGrad{} accepts this call because the two types are
  18522. consistent.
  18523. \begin{figure}[btp]
  18524. % gradual_test_9.rkt
  18525. \begin{tcolorbox}[colback=white]
  18526. {\if\edition\racketEd
  18527. \begin{lstlisting}
  18528. (define (map [f : (Integer -> Integer)]
  18529. [v : (Vector Integer Integer)])
  18530. : (Vector Integer Integer)
  18531. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18532. (define (inc x) (+ x 1))
  18533. (vector-ref (map inc (vector 0 41)) 1)
  18534. \end{lstlisting}
  18535. \fi}
  18536. {\if\edition\pythonEd
  18537. \begin{lstlisting}
  18538. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18539. return f(v[0]), f(v[1])
  18540. def inc(x):
  18541. return x + 1
  18542. t = map(inc, (0, 41))
  18543. print(t[1])
  18544. \end{lstlisting}
  18545. \fi}
  18546. \end{tcolorbox}
  18547. \caption{A partially typed version of the \code{map} example.}
  18548. \label{fig:gradual-map}
  18549. \end{figure}
  18550. \begin{figure}[tbp]
  18551. \begin{tcolorbox}[colback=white]
  18552. {\if\edition\racketEd
  18553. \begin{lstlisting}
  18554. (define/public (consistent? t1 t2)
  18555. (match* (t1 t2)
  18556. [('Integer 'Integer) #t]
  18557. [('Boolean 'Boolean) #t]
  18558. [('Void 'Void) #t]
  18559. [('Any t2) #t]
  18560. [(t1 'Any) #t]
  18561. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18562. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18563. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18564. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18565. (consistent? rt1 rt2))]
  18566. [(other wise) #f]))
  18567. \end{lstlisting}
  18568. \fi}
  18569. {\if\edition\pythonEd
  18570. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18571. def consistent(self, t1, t2):
  18572. match (t1, t2):
  18573. case (AnyType(), _):
  18574. return True
  18575. case (_, AnyType()):
  18576. return True
  18577. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18578. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18579. case (TupleType(ts1), TupleType(ts2)):
  18580. return all(map(self.consistent, ts1, ts2))
  18581. case (_, _):
  18582. return t1 == t2
  18583. \end{lstlisting}
  18584. \fi}
  18585. \end{tcolorbox}
  18586. \caption{The consistency method on types.}
  18587. \label{fig:consistent}
  18588. \end{figure}
  18589. It is also helpful to consider how gradual typing handles programs with an
  18590. error, such as applying \code{map} to a function that sometimes
  18591. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18592. type checker for \LangGrad{} accepts this program because the type of
  18593. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18594. \code{map}; that is,
  18595. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18596. is consistent with
  18597. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18598. One might say that a gradual type checker is optimistic in that it
  18599. accepts programs that might execute without a runtime type error.
  18600. %
  18601. The definition of the type checker for \LangGrad{} is shown in
  18602. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18603. and \ref{fig:type-check-Lgradual-3}.
  18604. %% \begin{figure}[tp]
  18605. %% \centering
  18606. %% \fbox{
  18607. %% \begin{minipage}{0.96\textwidth}
  18608. %% \small
  18609. %% \[
  18610. %% \begin{array}{lcl}
  18611. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18612. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18613. %% \end{array}
  18614. %% \]
  18615. %% \end{minipage}
  18616. %% }
  18617. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18618. %% \label{fig:Lgrad-prime-syntax}
  18619. %% \end{figure}
  18620. \begin{figure}[tbp]
  18621. \begin{tcolorbox}[colback=white]
  18622. {\if\edition\racketEd
  18623. \begin{lstlisting}
  18624. (define (map [f : (Integer -> Integer)]
  18625. [v : (Vector Integer Integer)])
  18626. : (Vector Integer Integer)
  18627. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18628. (define (inc x) (+ x 1))
  18629. (define (true) #t)
  18630. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18631. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18632. \end{lstlisting}
  18633. \fi}
  18634. {\if\edition\pythonEd
  18635. \begin{lstlisting}
  18636. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18637. return f(v[0]), f(v[1])
  18638. def inc(x):
  18639. return x + 1
  18640. def true():
  18641. return True
  18642. def maybe_inc(x):
  18643. return inc(x) if input_int() == 0 else true()
  18644. t = map(maybe_inc, (0, 41))
  18645. print( t[1] )
  18646. \end{lstlisting}
  18647. \fi}
  18648. \end{tcolorbox}
  18649. \caption{A variant of the \code{map} example with an error.}
  18650. \label{fig:map-maybe_inc}
  18651. \end{figure}
  18652. Running this program with input \code{1} triggers an
  18653. error when the \code{maybe\_inc} function returns
  18654. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18655. performs checking at runtime to ensure the integrity of the static
  18656. types, such as the
  18657. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18658. annotation on
  18659. parameter \code{f} of \code{map}.
  18660. Here we give a preview of how the runtime checking is accomplished;
  18661. the following sections provide the details.
  18662. The runtime checking is carried out by a new \code{Cast} AST node that
  18663. is generated in a new pass named \code{cast\_insert}. The output of
  18664. \code{cast\_insert} is a program in the \LangCast{} language, which
  18665. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18666. %
  18667. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18668. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18669. inserted every time the type checker encounters two types that are
  18670. consistent but not equal. In the \code{inc} function, \code{x} is
  18671. cast to \INTTY{} and the result of the \code{+} is cast to
  18672. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18673. is cast from
  18674. \racket{\code{(Any -> Any)}}
  18675. \python{\code{Callable[[Any], Any]}}
  18676. to
  18677. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18678. %
  18679. In the next section we see how to interpret the \code{Cast} node.
  18680. \begin{figure}[btp]
  18681. \begin{tcolorbox}[colback=white]
  18682. {\if\edition\racketEd
  18683. \begin{lstlisting}
  18684. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18685. : (Vector Integer Integer)
  18686. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18687. (define (inc [x : Any]) : Any
  18688. (cast (+ (cast x Any Integer) 1) Integer Any))
  18689. (define (true) : Any (cast #t Boolean Any))
  18690. (define (maybe_inc [x : Any]) : Any
  18691. (if (eq? 0 (read)) (inc x) (true)))
  18692. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18693. (vector 0 41)) 0)
  18694. \end{lstlisting}
  18695. \fi}
  18696. {\if\edition\pythonEd
  18697. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18698. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18699. return f(v[0]), f(v[1])
  18700. def inc(x : Any) -> Any:
  18701. return Cast(Cast(x, Any, int) + 1, int, Any)
  18702. def true() -> Any:
  18703. return Cast(True, bool, Any)
  18704. def maybe_inc(x : Any) -> Any:
  18705. return inc(x) if input_int() == 0 else true()
  18706. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18707. (0, 41))
  18708. print(t[1])
  18709. \end{lstlisting}
  18710. \fi}
  18711. \end{tcolorbox}
  18712. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18713. and \code{maybe\_inc} example.}
  18714. \label{fig:map-cast}
  18715. \end{figure}
  18716. {\if\edition\pythonEd
  18717. \begin{figure}[tbp]
  18718. \begin{tcolorbox}[colback=white]
  18719. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18720. class TypeCheckLgrad(TypeCheckLlambda):
  18721. def type_check_exp(self, e, env) -> Type:
  18722. match e:
  18723. case Name(id):
  18724. return env[id]
  18725. case Constant(value) if isinstance(value, bool):
  18726. return BoolType()
  18727. case Constant(value) if isinstance(value, int):
  18728. return IntType()
  18729. case Call(Name('input_int'), []):
  18730. return IntType()
  18731. case BinOp(left, op, right):
  18732. left_type = self.type_check_exp(left, env)
  18733. self.check_consistent(left_type, IntType(), left)
  18734. right_type = self.type_check_exp(right, env)
  18735. self.check_consistent(right_type, IntType(), right)
  18736. return IntType()
  18737. case IfExp(test, body, orelse):
  18738. test_t = self.type_check_exp(test, env)
  18739. self.check_consistent(test_t, BoolType(), test)
  18740. body_t = self.type_check_exp(body, env)
  18741. orelse_t = self.type_check_exp(orelse, env)
  18742. self.check_consistent(body_t, orelse_t, e)
  18743. return self.join_types(body_t, orelse_t)
  18744. case Call(func, args):
  18745. func_t = self.type_check_exp(func, env)
  18746. args_t = [self.type_check_exp(arg, env) for arg in args]
  18747. match func_t:
  18748. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18749. for (arg_t, param_t) in zip(args_t, params_t):
  18750. self.check_consistent(param_t, arg_t, e)
  18751. return return_t
  18752. case AnyType():
  18753. return AnyType()
  18754. case _:
  18755. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18756. ...
  18757. case _:
  18758. raise Exception('type_check_exp: unexpected ' + repr(e))
  18759. \end{lstlisting}
  18760. \end{tcolorbox}
  18761. \caption{Type checking expressions in the \LangGrad{} language.}
  18762. \label{fig:type-check-Lgradual-1}
  18763. \end{figure}
  18764. \begin{figure}[tbp]
  18765. \begin{tcolorbox}[colback=white]
  18766. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18767. def check_exp(self, e, expected_ty, env):
  18768. match e:
  18769. case Lambda(params, body):
  18770. match expected_ty:
  18771. case FunctionType(params_t, return_t):
  18772. new_env = env.copy().update(zip(params, params_t))
  18773. e.has_type = expected_ty
  18774. body_ty = self.type_check_exp(body, new_env)
  18775. self.check_consistent(body_ty, return_t)
  18776. case AnyType():
  18777. new_env = env.copy().update((p, AnyType()) for p in params)
  18778. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18779. body_ty = self.type_check_exp(body, new_env)
  18780. case _:
  18781. raise Exception('lambda does not have type ' + str(expected_ty))
  18782. case _:
  18783. e_ty = self.type_check_exp(e, env)
  18784. self.check_consistent(e_ty, expected_ty, e)
  18785. \end{lstlisting}
  18786. \end{tcolorbox}
  18787. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18788. \label{fig:type-check-Lgradual-2}
  18789. \end{figure}
  18790. \begin{figure}[tbp]
  18791. \begin{tcolorbox}[colback=white]
  18792. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18793. def type_check_stmt(self, s, env, return_type):
  18794. match s:
  18795. case Assign([Name(id)], value):
  18796. value_ty = self.type_check_exp(value, env)
  18797. if id in env:
  18798. self.check_consistent(env[id], value_ty, value)
  18799. else:
  18800. env[id] = value_ty
  18801. ...
  18802. case _:
  18803. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18804. def type_check_stmts(self, ss, env, return_type):
  18805. for s in ss:
  18806. self.type_check_stmt(s, env, return_type)
  18807. \end{lstlisting}
  18808. \end{tcolorbox}
  18809. \caption{Type checking statements in the \LangGrad{} language.}
  18810. \label{fig:type-check-Lgradual-3}
  18811. \end{figure}
  18812. \begin{figure}[tbp]
  18813. \begin{tcolorbox}[colback=white]
  18814. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18815. def join_types(self, t1, t2):
  18816. match (t1, t2):
  18817. case (AnyType(), _):
  18818. return t2
  18819. case (_, AnyType()):
  18820. return t1
  18821. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18822. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18823. self.join_types(rt1,rt2))
  18824. case (TupleType(ts1), TupleType(ts2)):
  18825. return TupleType(list(map(self.join_types, ts1, ts2)))
  18826. case (_, _):
  18827. return t1
  18828. def check_consistent(self, t1, t2, e):
  18829. if not self.consistent(t1, t2):
  18830. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18831. + ' in ' + repr(e))
  18832. \end{lstlisting}
  18833. \end{tcolorbox}
  18834. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18835. \label{fig:type-check-Lgradual-aux}
  18836. \end{figure}
  18837. \fi}
  18838. {\if\edition\racketEd
  18839. \begin{figure}[tbp]
  18840. \begin{tcolorbox}[colback=white]
  18841. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18842. (define/override (type-check-exp env)
  18843. (lambda (e)
  18844. (define recur (type-check-exp env))
  18845. (match e
  18846. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18847. (define-values (new-es ts)
  18848. (for/lists (exprs types) ([e es])
  18849. (recur e)))
  18850. (define t-ret (type-check-op op ts e))
  18851. (values (Prim op new-es) t-ret)]
  18852. [(Prim 'eq? (list e1 e2))
  18853. (define-values (e1^ t1) (recur e1))
  18854. (define-values (e2^ t2) (recur e2))
  18855. (check-consistent? t1 t2 e)
  18856. (define T (meet t1 t2))
  18857. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18858. [(Prim 'and (list e1 e2))
  18859. (recur (If e1 e2 (Bool #f)))]
  18860. [(Prim 'or (list e1 e2))
  18861. (define tmp (gensym 'tmp))
  18862. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18863. [(If e1 e2 e3)
  18864. (define-values (e1^ T1) (recur e1))
  18865. (define-values (e2^ T2) (recur e2))
  18866. (define-values (e3^ T3) (recur e3))
  18867. (check-consistent? T1 'Boolean e)
  18868. (check-consistent? T2 T3 e)
  18869. (define Tif (meet T2 T3))
  18870. (values (If e1^ e2^ e3^) Tif)]
  18871. [(SetBang x e1)
  18872. (define-values (e1^ T1) (recur e1))
  18873. (define varT (dict-ref env x))
  18874. (check-consistent? T1 varT e)
  18875. (values (SetBang x e1^) 'Void)]
  18876. [(WhileLoop e1 e2)
  18877. (define-values (e1^ T1) (recur e1))
  18878. (check-consistent? T1 'Boolean e)
  18879. (define-values (e2^ T2) ((type-check-exp env) e2))
  18880. (values (WhileLoop e1^ e2^) 'Void)]
  18881. [(Prim 'vector-length (list e1))
  18882. (define-values (e1^ t) (recur e1))
  18883. (match t
  18884. [`(Vector ,ts ...)
  18885. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18886. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18887. \end{lstlisting}
  18888. \end{tcolorbox}
  18889. \caption{Type checker for the \LangGrad{} language, part 1.}
  18890. \label{fig:type-check-Lgradual-1}
  18891. \end{figure}
  18892. \begin{figure}[tbp]
  18893. \begin{tcolorbox}[colback=white]
  18894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18895. [(Prim 'vector-ref (list e1 e2))
  18896. (define-values (e1^ t1) (recur e1))
  18897. (define-values (e2^ t2) (recur e2))
  18898. (check-consistent? t2 'Integer e)
  18899. (match t1
  18900. [`(Vector ,ts ...)
  18901. (match e2^
  18902. [(Int i)
  18903. (unless (and (0 . <= . i) (i . < . (length ts)))
  18904. (error 'type-check "invalid index ~a in ~a" i e))
  18905. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18906. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18907. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18908. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18909. [(Prim 'vector-set! (list e1 e2 e3) )
  18910. (define-values (e1^ t1) (recur e1))
  18911. (define-values (e2^ t2) (recur e2))
  18912. (define-values (e3^ t3) (recur e3))
  18913. (check-consistent? t2 'Integer e)
  18914. (match t1
  18915. [`(Vector ,ts ...)
  18916. (match e2^
  18917. [(Int i)
  18918. (unless (and (0 . <= . i) (i . < . (length ts)))
  18919. (error 'type-check "invalid index ~a in ~a" i e))
  18920. (check-consistent? (list-ref ts i) t3 e)
  18921. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18922. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18923. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18924. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18925. [(Apply e1 e2s)
  18926. (define-values (e1^ T1) (recur e1))
  18927. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18928. (match T1
  18929. [`(,T1ps ... -> ,T1rt)
  18930. (for ([T2 T2s] [Tp T1ps])
  18931. (check-consistent? T2 Tp e))
  18932. (values (Apply e1^ e2s^) T1rt)]
  18933. [`Any (values (Apply e1^ e2s^) 'Any)]
  18934. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18935. [(Lambda params Tr e1)
  18936. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18937. (match p
  18938. [`[,x : ,T] (values x T)]
  18939. [(? symbol? x) (values x 'Any)])))
  18940. (define-values (e1^ T1)
  18941. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18942. (check-consistent? Tr T1 e)
  18943. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18944. `(,@Ts -> ,Tr))]
  18945. [else ((super type-check-exp env) e)]
  18946. )))
  18947. \end{lstlisting}
  18948. \end{tcolorbox}
  18949. \caption{Type checker for the \LangGrad{} language, part 2.}
  18950. \label{fig:type-check-Lgradual-2}
  18951. \end{figure}
  18952. \begin{figure}[tbp]
  18953. \begin{tcolorbox}[colback=white]
  18954. \begin{lstlisting}
  18955. (define/override (type-check-def env)
  18956. (lambda (e)
  18957. (match e
  18958. [(Def f params rt info body)
  18959. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18960. (match p
  18961. [`[,x : ,T] (values x T)]
  18962. [(? symbol? x) (values x 'Any)])))
  18963. (define new-env (append (map cons xs ps) env))
  18964. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18965. (check-consistent? ty^ rt e)
  18966. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18967. [else (error 'type-check "ill-formed function definition ~a" e)]
  18968. )))
  18969. (define/override (type-check-program e)
  18970. (match e
  18971. [(Program info body)
  18972. (define-values (body^ ty) ((type-check-exp '()) body))
  18973. (check-consistent? ty 'Integer e)
  18974. (ProgramDefsExp info '() body^)]
  18975. [(ProgramDefsExp info ds body)
  18976. (define new-env (for/list ([d ds])
  18977. (cons (Def-name d) (fun-def-type d))))
  18978. (define ds^ (for/list ([d ds])
  18979. ((type-check-def new-env) d)))
  18980. (define-values (body^ ty) ((type-check-exp new-env) body))
  18981. (check-consistent? ty 'Integer e)
  18982. (ProgramDefsExp info ds^ body^)]
  18983. [else (super type-check-program e)]))
  18984. \end{lstlisting}
  18985. \end{tcolorbox}
  18986. \caption{Type checker for the \LangGrad{} language, part 3.}
  18987. \label{fig:type-check-Lgradual-3}
  18988. \end{figure}
  18989. \begin{figure}[tbp]
  18990. \begin{tcolorbox}[colback=white]
  18991. \begin{lstlisting}
  18992. (define/public (join t1 t2)
  18993. (match* (t1 t2)
  18994. [('Integer 'Integer) 'Integer]
  18995. [('Boolean 'Boolean) 'Boolean]
  18996. [('Void 'Void) 'Void]
  18997. [('Any t2) t2]
  18998. [(t1 'Any) t1]
  18999. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19000. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19001. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19002. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19003. -> ,(join rt1 rt2))]))
  19004. (define/public (meet t1 t2)
  19005. (match* (t1 t2)
  19006. [('Integer 'Integer) 'Integer]
  19007. [('Boolean 'Boolean) 'Boolean]
  19008. [('Void 'Void) 'Void]
  19009. [('Any t2) 'Any]
  19010. [(t1 'Any) 'Any]
  19011. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19012. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19013. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19014. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19015. -> ,(meet rt1 rt2))]))
  19016. (define/public (check-consistent? t1 t2 e)
  19017. (unless (consistent? t1 t2)
  19018. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19019. (define explicit-prim-ops
  19020. (set-union
  19021. (type-predicates)
  19022. (set 'procedure-arity 'eq? 'not 'and 'or
  19023. 'vector 'vector-length 'vector-ref 'vector-set!
  19024. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19025. (define/override (fun-def-type d)
  19026. (match d
  19027. [(Def f params rt info body)
  19028. (define ps
  19029. (for/list ([p params])
  19030. (match p
  19031. [`[,x : ,T] T]
  19032. [(? symbol?) 'Any]
  19033. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19034. `(,@ps -> ,rt)]
  19035. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19036. \end{lstlisting}
  19037. \end{tcolorbox}
  19038. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19039. \label{fig:type-check-Lgradual-aux}
  19040. \end{figure}
  19041. \fi}
  19042. \clearpage
  19043. \section{Interpreting \LangCast{}}
  19044. \label{sec:interp-casts}
  19045. The runtime behavior of casts involving simple types such as
  19046. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19047. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19048. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19049. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19050. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19051. operator, by checking the value's tag and either retrieving
  19052. the underlying integer or signaling an error if the tag is not the
  19053. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19054. %
  19055. Things get more interesting with casts involving
  19056. \racket{function and tuple types}\python{function, tuple, and array types}.
  19057. Consider the cast of the function \code{maybe\_inc} from
  19058. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19059. to
  19060. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19061. shown in figure~\ref{fig:map-maybe_inc}.
  19062. When the \code{maybe\_inc} function flows through
  19063. this cast at runtime, we don't know whether it will return
  19064. an integer, because that depends on the input from the user.
  19065. The \LangCast{} interpreter therefore delays the checking
  19066. of the cast until the function is applied. To do so it
  19067. wraps \code{maybe\_inc} in a new function that casts its parameter
  19068. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19069. casts the return value from \CANYTY{} to \INTTY{}.
  19070. {\if\edition\pythonEd
  19071. %
  19072. There are further complications regarding casts on mutable data
  19073. such as the \code{list} type introduced in
  19074. the challenge assignment of section~\ref{sec:arrays}.
  19075. %
  19076. \fi}
  19077. %
  19078. Consider the example presented in figure~\ref{fig:map-bang} that
  19079. defines a partially typed version of \code{map} whose parameter
  19080. \code{v} has type
  19081. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19082. and that updates \code{v} in place
  19083. instead of returning a new tuple. So, we name this function
  19084. \code{map\_inplace}. We apply \code{map\_inplace} to an
  19085. \racket{tuple}\python{array} of integers, so the type checker inserts a
  19086. cast from
  19087. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19088. to
  19089. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19090. A naive way for the \LangCast{} interpreter to cast between
  19091. \racket{tuple}\python{array} types would be a build a new
  19092. \racket{tuple}\python{array}
  19093. whose elements are the result
  19094. of casting each of the original elements to the appropriate target
  19095. type.
  19096. However, this approach is not valid for mutable data structures.
  19097. In the example of figure~\ref{fig:map-bang},
  19098. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19099. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19100. the original one.
  19101. \begin{figure}[tbp]
  19102. \begin{tcolorbox}[colback=white]
  19103. % gradual_test_11.rkt
  19104. {\if\edition\racketEd
  19105. \begin{lstlisting}
  19106. (define (map_inplace [f : (Any -> Any)]
  19107. [v : (Vector Any Any)]) : Void
  19108. (begin
  19109. (vector-set! v 0 (f (vector-ref v 0)))
  19110. (vector-set! v 1 (f (vector-ref v 1)))))
  19111. (define (inc x) (+ x 1))
  19112. (let ([v (vector 0 41)])
  19113. (begin (map_inplace inc v) (vector-ref v 1)))
  19114. \end{lstlisting}
  19115. \fi}
  19116. {\if\edition\pythonEd
  19117. \begin{lstlisting}
  19118. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19119. i = 0
  19120. while i != len(v):
  19121. v[i] = f(v[i])
  19122. i = i + 1
  19123. def inc(x : int) -> int:
  19124. return x + 1
  19125. v = [0, 41]
  19126. map_inplace(inc, v)
  19127. print( v[1] )
  19128. \end{lstlisting}
  19129. \fi}
  19130. \end{tcolorbox}
  19131. \caption{An example involving casts on arrays.}
  19132. \label{fig:map-bang}
  19133. \end{figure}
  19134. Instead the interpreter needs to create a new kind of value, a
  19135. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19136. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19137. and then applies a
  19138. cast to the resulting value. On a write, the proxy casts the argument
  19139. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19140. \racket{
  19141. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19142. \code{0} from \INTTY{} to \CANYTY{}.
  19143. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19144. from \CANYTY{} to \INTTY{}.
  19145. }
  19146. \python{
  19147. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19148. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19149. For the subscript on the left of the assignment,
  19150. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19151. }
  19152. The final category of cast that we need to consider consist of casts between
  19153. the \CANYTY{} type and higher-order types such as functions and
  19154. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  19155. variant of \code{map\_inplace} in which parameter \code{v} does not
  19156. have a type annotation, so it is given type \CANYTY{}. In the call to
  19157. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19158. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19159. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19160. \code{Inject}, but that doesn't work because
  19161. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19162. a flat type. Instead, we must first cast to
  19163. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19164. and then inject to \CANYTY{}.
  19165. \begin{figure}[tbp]
  19166. \begin{tcolorbox}[colback=white]
  19167. {\if\edition\racketEd
  19168. \begin{lstlisting}
  19169. (define (map_inplace [f : (Any -> Any)] v) : Void
  19170. (begin
  19171. (vector-set! v 0 (f (vector-ref v 0)))
  19172. (vector-set! v 1 (f (vector-ref v 1)))))
  19173. (define (inc x) (+ x 1))
  19174. (let ([v (vector 0 41)])
  19175. (begin (map_inplace inc v) (vector-ref v 1)))
  19176. \end{lstlisting}
  19177. \fi}
  19178. {\if\edition\pythonEd
  19179. \begin{lstlisting}
  19180. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19181. i = 0
  19182. while i != len(v):
  19183. v[i] = f(v[i])
  19184. i = i + 1
  19185. def inc(x):
  19186. return x + 1
  19187. v = [0, 41]
  19188. map_inplace(inc, v)
  19189. print( v[1] )
  19190. \end{lstlisting}
  19191. \fi}
  19192. \end{tcolorbox}
  19193. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  19194. \label{fig:map-any}
  19195. \end{figure}
  19196. \begin{figure}[tbp]
  19197. \begin{tcolorbox}[colback=white]
  19198. {\if\edition\racketEd
  19199. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19200. (define/public (apply_cast v s t)
  19201. (match* (s t)
  19202. [(t1 t2) #:when (equal? t1 t2) v]
  19203. [('Any t2)
  19204. (match t2
  19205. [`(,ts ... -> ,rt)
  19206. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19207. (define v^ (apply-project v any->any))
  19208. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19209. [`(Vector ,ts ...)
  19210. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19211. (define v^ (apply-project v vec-any))
  19212. (apply_cast v^ vec-any `(Vector ,@ts))]
  19213. [else (apply-project v t2)])]
  19214. [(t1 'Any)
  19215. (match t1
  19216. [`(,ts ... -> ,rt)
  19217. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19218. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19219. (apply-inject v^ (any-tag any->any))]
  19220. [`(Vector ,ts ...)
  19221. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19222. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19223. (apply-inject v^ (any-tag vec-any))]
  19224. [else (apply-inject v (any-tag t1))])]
  19225. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19226. (define x (gensym 'x))
  19227. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19228. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19229. (define cast-writes
  19230. (for/list ([t1 ts1] [t2 ts2])
  19231. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19232. `(vector-proxy ,(vector v (apply vector cast-reads)
  19233. (apply vector cast-writes)))]
  19234. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19235. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19236. `(function ,xs ,(Cast
  19237. (Apply (Value v)
  19238. (for/list ([x xs][t1 ts1][t2 ts2])
  19239. (Cast (Var x) t2 t1)))
  19240. rt1 rt2) ())]
  19241. ))
  19242. \end{lstlisting}
  19243. \fi}
  19244. {\if\edition\pythonEd
  19245. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19246. def apply_cast(self, value, src, tgt):
  19247. match (src, tgt):
  19248. case (AnyType(), FunctionType(ps2, rt2)):
  19249. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19250. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19251. case (AnyType(), TupleType(ts2)):
  19252. anytup = TupleType([AnyType() for t1 in ts2])
  19253. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19254. case (AnyType(), ListType(t2)):
  19255. anylist = ListType([AnyType() for t1 in ts2])
  19256. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19257. case (AnyType(), AnyType()):
  19258. return value
  19259. case (AnyType(), _):
  19260. return self.apply_project(value, tgt)
  19261. case (FunctionType(ps1,rt1), AnyType()):
  19262. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19263. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19264. case (TupleType(ts1), AnyType()):
  19265. anytup = TupleType([AnyType() for t1 in ts1])
  19266. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19267. case (ListType(t1), AnyType()):
  19268. anylist = ListType(AnyType())
  19269. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19270. case (_, AnyType()):
  19271. return self.apply_inject(value, src)
  19272. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19273. params = [generate_name('x') for p in ps2]
  19274. args = [Cast(Name(x), t2, t1)
  19275. for (x,t1,t2) in zip(params, ps1, ps2)]
  19276. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19277. return Function('cast', params, [Return(body)], {})
  19278. case (TupleType(ts1), TupleType(ts2)):
  19279. x = generate_name('x')
  19280. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19281. for (t1,t2) in zip(ts1,ts2)]
  19282. return ProxiedTuple(value, reads)
  19283. case (ListType(t1), ListType(t2)):
  19284. x = generate_name('x')
  19285. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19286. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19287. return ProxiedList(value, read, write)
  19288. case (t1, t2) if t1 == t2:
  19289. return value
  19290. case (t1, t2):
  19291. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19292. def apply_inject(self, value, src):
  19293. return Tagged(value, self.type_to_tag(src))
  19294. def apply_project(self, value, tgt):
  19295. match value:
  19296. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19297. return val
  19298. case _:
  19299. raise Exception('apply_project, unexpected ' + repr(value))
  19300. \end{lstlisting}
  19301. \fi}
  19302. \end{tcolorbox}
  19303. \caption{The \code{apply\_cast} auxiliary method.}
  19304. \label{fig:apply_cast}
  19305. \end{figure}
  19306. The \LangCast{} interpreter uses an auxiliary function named
  19307. \code{apply\_cast} to cast a value from a source type to a target type,
  19308. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19309. the kinds of casts that we've discussed in this section.
  19310. %
  19311. The definition of the interpreter for \LangCast{} is shown in
  19312. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19313. dispatching to \code{apply\_cast}.
  19314. \racket{To handle the addition of tuple
  19315. proxies, we update the tuple primitives in \code{interp-op} using the
  19316. functions given in figure~\ref{fig:guarded-tuple}.}
  19317. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19318. \begin{figure}[tbp]
  19319. \begin{tcolorbox}[colback=white]
  19320. {\if\edition\racketEd
  19321. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19322. (define interp-Lcast-class
  19323. (class interp-Llambda-class
  19324. (super-new)
  19325. (inherit apply-fun apply-inject apply-project)
  19326. (define/override (interp-op op)
  19327. (match op
  19328. ['vector-length guarded-vector-length]
  19329. ['vector-ref guarded-vector-ref]
  19330. ['vector-set! guarded-vector-set!]
  19331. ['any-vector-ref (lambda (v i)
  19332. (match v [`(tagged ,v^ ,tg)
  19333. (guarded-vector-ref v^ i)]))]
  19334. ['any-vector-set! (lambda (v i a)
  19335. (match v [`(tagged ,v^ ,tg)
  19336. (guarded-vector-set! v^ i a)]))]
  19337. ['any-vector-length (lambda (v)
  19338. (match v [`(tagged ,v^ ,tg)
  19339. (guarded-vector-length v^)]))]
  19340. [else (super interp-op op)]
  19341. ))
  19342. (define/override ((interp-exp env) e)
  19343. (define (recur e) ((interp-exp env) e))
  19344. (match e
  19345. [(Value v) v]
  19346. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19347. [else ((super interp-exp env) e)]))
  19348. ))
  19349. (define (interp-Lcast p)
  19350. (send (new interp-Lcast-class) interp-program p))
  19351. \end{lstlisting}
  19352. \fi}
  19353. {\if\edition\pythonEd
  19354. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19355. class InterpLcast(InterpLany):
  19356. def interp_exp(self, e, env):
  19357. match e:
  19358. case Cast(value, src, tgt):
  19359. v = self.interp_exp(value, env)
  19360. return self.apply_cast(v, src, tgt)
  19361. case ValueExp(value):
  19362. return value
  19363. ...
  19364. case _:
  19365. return super().interp_exp(e, env)
  19366. \end{lstlisting}
  19367. \fi}
  19368. \end{tcolorbox}
  19369. \caption{The interpreter for \LangCast{}.}
  19370. \label{fig:interp-Lcast}
  19371. \end{figure}
  19372. {\if\edition\racketEd
  19373. \begin{figure}[tbp]
  19374. \begin{tcolorbox}[colback=white]
  19375. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19376. (define (guarded-vector-ref vec i)
  19377. (match vec
  19378. [`(vector-proxy ,proxy)
  19379. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19380. (define rd (vector-ref (vector-ref proxy 1) i))
  19381. (apply-fun rd (list val) 'guarded-vector-ref)]
  19382. [else (vector-ref vec i)]))
  19383. (define (guarded-vector-set! vec i arg)
  19384. (match vec
  19385. [`(vector-proxy ,proxy)
  19386. (define wr (vector-ref (vector-ref proxy 2) i))
  19387. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19388. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19389. [else (vector-set! vec i arg)]))
  19390. (define (guarded-vector-length vec)
  19391. (match vec
  19392. [`(vector-proxy ,proxy)
  19393. (guarded-vector-length (vector-ref proxy 0))]
  19394. [else (vector-length vec)]))
  19395. \end{lstlisting}
  19396. %% {\if\edition\pythonEd
  19397. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19398. %% UNDER CONSTRUCTION
  19399. %% \end{lstlisting}
  19400. %% \fi}
  19401. \end{tcolorbox}
  19402. \caption{The \code{guarded-vector} auxiliary functions.}
  19403. \label{fig:guarded-tuple}
  19404. \end{figure}
  19405. \fi}
  19406. {\if\edition\pythonEd
  19407. \section{Overload Resolution}
  19408. \label{sec:gradual-resolution}
  19409. Recall that when we added support for arrays in
  19410. section~\ref{sec:arrays}, the syntax for the array operations were the
  19411. same as for tuple operations (e.g., accessing an element, getting the
  19412. length). So we performed overload resolution, with a pass named
  19413. \code{resolve}, to separate the array and tuple operations. In
  19414. particular, we introduced the primitives \code{array\_load},
  19415. \code{array\_store}, and \code{array\_len}.
  19416. For gradual typing, we further overload these operators to work on
  19417. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19418. updated with new cases for the \CANYTY{} type, translating the element
  19419. access and length operations to the primitives \code{any\_load},
  19420. \code{any\_store}, and \code{any\_len}.
  19421. \fi}
  19422. \section{Cast Insertion}
  19423. \label{sec:gradual-insert-casts}
  19424. In our discussion of type checking of \LangGrad{}, we mentioned how
  19425. the runtime aspect of type checking is carried out by the \code{Cast}
  19426. AST node, which is added to the program by a new pass named
  19427. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19428. language. We now discuss the details of this pass.
  19429. The \code{cast\_insert} pass is closely related to the type checker
  19430. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19431. In particular, the type checker allows implicit casts between
  19432. consistent types. The job of the \code{cast\_insert} pass is to make
  19433. those casts explicit. It does so by inserting
  19434. \code{Cast} nodes into the AST.
  19435. %
  19436. For the most part, the implicit casts occur in places where the type
  19437. checker checks two types for consistency. Consider the case for
  19438. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19439. checker requires that the type of the left operand is consistent with
  19440. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19441. \code{Cast} around the left operand, converting from its type to
  19442. \INTTY{}. The story is similar for the right operand. It is not always
  19443. necessary to insert a cast, e.g., if the left operand already has type
  19444. \INTTY{} then there is no need for a \code{Cast}.
  19445. Some of the implicit casts are not as straightforward. One such case
  19446. arises with the
  19447. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19448. see that the type checker requires that the two branches have
  19449. consistent types and that type of the conditional expression is the
  19450. meet of the branches' types. In the target language \LangCast{}, both
  19451. branches will need to have the same type, and that type
  19452. will be the type of the conditional expression. Thus, each branch requires
  19453. a \code{Cast} to convert from its type to the meet of the branches' types.
  19454. The case for the function call exhibits another interesting situation. If
  19455. the function expression is of type \CANYTY{}, then it needs to be cast
  19456. to a function type so that it can be used in a function call in
  19457. \LangCast{}. Which function type should it be cast to? The parameter
  19458. and return types are unknown, so we can simply use \CANYTY{} for all
  19459. of them. Furthermore, in \LangCast{} the argument types will need to
  19460. exactly match the parameter types, so we must cast all the arguments
  19461. to type \CANYTY{} (if they are not already of that type).
  19462. {\if\edition\racketEd
  19463. %
  19464. Likewise, the cases for the tuple operators \code{vector-length},
  19465. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19466. where the tuple expression is of type \CANYTY{}. Instead of
  19467. handling these situations with casts, we recommend translating
  19468. the special-purpose variants of the tuple operators that handle
  19469. tuples of type \CANYTY{}: \code{any-vector-length},
  19470. \code{any-vector-ref}, and \code{any-vector-set!}.
  19471. %
  19472. \fi}
  19473. \section{Lower Casts}
  19474. \label{sec:lower_casts}
  19475. The next step in the journey toward x86 is the \code{lower\_casts}
  19476. pass that translates the casts in \LangCast{} to the lower-level
  19477. \code{Inject} and \code{Project} operators and new operators for
  19478. proxies, extending the \LangLam{} language to \LangProxy{}.
  19479. The \LangProxy{} language can also be described as an extension of
  19480. \LangAny{}, with the addition of proxies. We recommend creating an
  19481. auxiliary function named \code{lower\_cast} that takes an expression
  19482. (in \LangCast{}), a source type, and a target type and translates it
  19483. to an expression in \LangProxy{}.
  19484. The \code{lower\_cast} function can follow a code structure similar to
  19485. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19486. the interpreter for \LangCast{}, because it must handle the same cases
  19487. as \code{apply\_cast} and it needs to mimic the behavior of
  19488. \code{apply\_cast}. The most interesting cases concern
  19489. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19490. {\if\edition\racketEd
  19491. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19492. type to another tuple type is accomplished by creating a proxy that
  19493. intercepts the operations on the underlying tuple. Here we make the
  19494. creation of the proxy explicit with the \code{vector-proxy} AST
  19495. node. It takes three arguments: the first is an expression for the
  19496. tuple, the second is tuple of functions for casting an element that is
  19497. being read from the tuple, and the third is a tuple of functions for
  19498. casting an element that is being written to the array. You can create
  19499. the functions for reading and writing using lambda expressions. Also,
  19500. as we show in the next section, we need to differentiate these tuples
  19501. of functions from the user-created ones, so we recommend using a new
  19502. AST node named \code{raw-vector} instead of \code{vector}.
  19503. %
  19504. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19505. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19506. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19507. \fi}
  19508. {\if\edition\pythonEd
  19509. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19510. type to another array type is accomplished by creating a proxy that
  19511. intercepts the operations on the underlying array. Here we make the
  19512. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19513. takes fives arguments: the first is an expression for the array, the
  19514. second is a function for casting an element that is being read from
  19515. the array, the third is a function for casting an element that is
  19516. being written to the array, the fourth is the type of the underlying
  19517. array, and the fifth is the type of the proxied array. You can create
  19518. the functions for reading and writing using lambda expressions.
  19519. A cast between two tuple types can be handled in a similar manner. We
  19520. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19521. immutable, so there is no need for a function to cast the value during
  19522. a write. Because there is a separate element type for each slot in
  19523. the tuple, we need not just one function for casting during a read,
  19524. but instead a tuple of functions.
  19525. %
  19526. Also, as we show in the next section, we need to differentiate these
  19527. tuples from the user-created ones, so we recommend using a new AST
  19528. node named \code{RawTuple} instead of \code{Tuple} to create the
  19529. tuples of functions.
  19530. %
  19531. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19532. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19533. that involved casting an array of integers to an array of \CANYTY{}.
  19534. \fi}
  19535. \begin{figure}[tbp]
  19536. \begin{tcolorbox}[colback=white]
  19537. {\if\edition\racketEd
  19538. \begin{lstlisting}
  19539. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19540. (begin
  19541. (vector-set! v 0 (f (vector-ref v 0)))
  19542. (vector-set! v 1 (f (vector-ref v 1)))))
  19543. (define (inc [x : Any]) : Any
  19544. (inject (+ (project x Integer) 1) Integer))
  19545. (let ([v (vector 0 41)])
  19546. (begin
  19547. (map_inplace inc (vector-proxy v
  19548. (raw-vector (lambda: ([x9 : Integer]) : Any
  19549. (inject x9 Integer))
  19550. (lambda: ([x9 : Integer]) : Any
  19551. (inject x9 Integer)))
  19552. (raw-vector (lambda: ([x9 : Any]) : Integer
  19553. (project x9 Integer))
  19554. (lambda: ([x9 : Any]) : Integer
  19555. (project x9 Integer)))))
  19556. (vector-ref v 1)))
  19557. \end{lstlisting}
  19558. \fi}
  19559. {\if\edition\pythonEd
  19560. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19561. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19562. i = 0
  19563. while i != array_len(v):
  19564. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19565. i = (i + 1)
  19566. def inc(x : int) -> int:
  19567. return (x + 1)
  19568. def main() -> int:
  19569. v = [0, 41]
  19570. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19571. print(array_load(v, 1))
  19572. return 0
  19573. \end{lstlisting}
  19574. \fi}
  19575. \end{tcolorbox}
  19576. \caption{Output of \code{lower\_casts} on the example shown in
  19577. figure~\ref{fig:map-bang}.}
  19578. \label{fig:map-bang-lower-cast}
  19579. \end{figure}
  19580. A cast from one function type to another function type is accomplished
  19581. by generating a \code{lambda} whose parameter and return types match
  19582. the target function type. The body of the \code{lambda} should cast
  19583. the parameters from the target type to the source type. (Yes,
  19584. backward! Functions are contravariant\index{subject}{contravariant}
  19585. in the parameters.). Afterward, call the underlying function and then
  19586. cast the result from the source return type to the target return type.
  19587. Figure~\ref{fig:map-lower-cast} shows the output of the
  19588. \code{lower\_casts} pass on the \code{map} example give in
  19589. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19590. call to \code{map} is wrapped in a \code{lambda}.
  19591. \begin{figure}[tbp]
  19592. \begin{tcolorbox}[colback=white]
  19593. {\if\edition\racketEd
  19594. \begin{lstlisting}
  19595. (define (map [f : (Integer -> Integer)]
  19596. [v : (Vector Integer Integer)])
  19597. : (Vector Integer Integer)
  19598. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19599. (define (inc [x : Any]) : Any
  19600. (inject (+ (project x Integer) 1) Integer))
  19601. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19602. (project (inc (inject x9 Integer)) Integer))
  19603. (vector 0 41)) 1)
  19604. \end{lstlisting}
  19605. \fi}
  19606. {\if\edition\pythonEd
  19607. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19608. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19609. return (f(v[0]), f(v[1]),)
  19610. def inc(x : any) -> any:
  19611. return inject((project(x, int) + 1), int)
  19612. def main() -> int:
  19613. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19614. print(t[1])
  19615. return 0
  19616. \end{lstlisting}
  19617. \fi}
  19618. \end{tcolorbox}
  19619. \caption{Output of \code{lower\_casts} on the example shown in
  19620. figure~\ref{fig:gradual-map}.}
  19621. \label{fig:map-lower-cast}
  19622. \end{figure}
  19623. \section{Differentiate Proxies}
  19624. \label{sec:differentiate-proxies}
  19625. So far, the responsibility of differentiating tuples and tuple proxies
  19626. has been the job of the interpreter.
  19627. %
  19628. \racket{For example, the interpreter for \LangCast{} implements
  19629. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19630. figure~\ref{fig:guarded-tuple}.}
  19631. %
  19632. In the \code{differentiate\_proxies} pass we shift this responsibility
  19633. to the generated code.
  19634. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19635. we used the type \TUPLETYPENAME{} for both
  19636. real tuples and tuple proxies.
  19637. \python{Similarly, we use the type \code{list} for both arrays and
  19638. array proxies.}
  19639. In \LangPVec{} we return the
  19640. \TUPLETYPENAME{} type to its original
  19641. meaning, as the type of just tuples, and we introduce a new type,
  19642. \PTUPLETYNAME{}, whose values
  19643. can be either real tuples or tuple
  19644. proxies.
  19645. %
  19646. {\if\edition\pythonEd
  19647. Likewise, we return the
  19648. \ARRAYTYPENAME{} type to its original
  19649. meaning, as the type of arrays, and we introduce a new type,
  19650. \PARRAYTYNAME{}, whose values
  19651. can be either arrays or array proxies.
  19652. These new types come with a suite of new primitive operations.
  19653. \fi}
  19654. {\if\edition\racketEd
  19655. A tuple proxy is represented by a tuple containing three things: (1) the
  19656. underlying tuple, (2) a tuple of functions for casting elements that
  19657. are read from the tuple, and (3) a tuple of functions for casting
  19658. values to be written to the tuple. So, we define the following
  19659. abbreviation for the type of a tuple proxy:
  19660. \[
  19661. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19662. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19663. \]
  19664. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19665. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19666. %
  19667. Next we describe each of the new primitive operations.
  19668. \begin{description}
  19669. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19670. (\key{PVector} $T \ldots$)]\ \\
  19671. %
  19672. This operation brands a vector as a value of the \code{PVector} type.
  19673. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19674. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19675. %
  19676. This operation brands a vector proxy as value of the \code{PVector} type.
  19677. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19678. \BOOLTY{}] \ \\
  19679. %
  19680. This returns true if the value is a tuple proxy and false if it is a
  19681. real tuple.
  19682. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19683. (\key{Vector} $T \ldots$)]\ \\
  19684. %
  19685. Assuming that the input is a tuple, this operation returns the
  19686. tuple.
  19687. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19688. $\to$ \BOOLTY{}]\ \\
  19689. %
  19690. Given a tuple proxy, this operation returns the length of the tuple.
  19691. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19692. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19693. %
  19694. Given a tuple proxy, this operation returns the $i$th element of the
  19695. tuple.
  19696. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19697. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19698. Given a tuple proxy, this operation writes a value to the $i$th element
  19699. of the tuple.
  19700. \end{description}
  19701. \fi}
  19702. {\if\edition\pythonEd
  19703. %
  19704. A tuple proxy is represented by a tuple containing 1) the underlying
  19705. tuple and 2) a tuple of functions for casting elements that are read
  19706. from the tuple. The \LangPVec{} language includes the following AST
  19707. classes and primitive functions.
  19708. \begin{description}
  19709. \item[\code{InjectTuple}] \ \\
  19710. %
  19711. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19712. \item[\code{InjectTupleProxy}]\ \\
  19713. %
  19714. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19715. \item[\code{is\_tuple\_proxy}]\ \\
  19716. %
  19717. This primitive returns true if the value is a tuple proxy and false
  19718. if it is a tuple.
  19719. \item[\code{project\_tuple}]\ \\
  19720. %
  19721. Converts a tuple that is branded as \PTUPLETYNAME{}
  19722. back to a tuple.
  19723. \item[\code{proxy\_tuple\_len}]\ \\
  19724. %
  19725. Given a tuple proxy, returns the length of the underlying tuple.
  19726. \item[\code{proxy\_tuple\_load}]\ \\
  19727. %
  19728. Given a tuple proxy, returns the $i$th element of the underlying
  19729. tuple.
  19730. \end{description}
  19731. An array proxy is represented by a tuple containing 1) the underlying
  19732. array, 2) a function for casting elements that are read from the
  19733. array, and 3) a function for casting elements that are written to the
  19734. array. The \LangPVec{} language includes the following AST classes
  19735. and primitive functions.
  19736. \begin{description}
  19737. \item[\code{InjectList}]\ \\
  19738. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19739. \item[\code{InjectListProxy}]\ \\
  19740. %
  19741. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19742. \item[\code{is\_array\_proxy}]\ \\
  19743. %
  19744. Returns true if the value is a array proxy and false if it is an
  19745. array.
  19746. \item[\code{project\_array}]\ \\
  19747. %
  19748. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19749. array.
  19750. \item[\code{proxy\_array\_len}]\ \\
  19751. %
  19752. Given a array proxy, returns the length of the underlying array.
  19753. \item[\code{proxy\_array\_load}]\ \\
  19754. %
  19755. Given a array proxy, returns the $i$th element of the underlying
  19756. array.
  19757. \item[\code{proxy\_array\_store}]\ \\
  19758. %
  19759. Given an array proxy, writes a value to the $i$th element of the
  19760. underlying array.
  19761. \end{description}
  19762. \fi}
  19763. Now we discuss the translation that differentiates tuples and arrays
  19764. from proxies. First, every type annotation in the program is
  19765. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19766. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19767. places. For example, we wrap every tuple creation with an
  19768. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19769. %
  19770. {\if\edition\racketEd
  19771. \begin{minipage}{0.96\textwidth}
  19772. \begin{lstlisting}
  19773. (vector |$e_1 \ldots e_n$|)
  19774. |$\Rightarrow$|
  19775. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19776. \end{lstlisting}
  19777. \end{minipage}
  19778. \fi}
  19779. {\if\edition\pythonEd
  19780. \begin{lstlisting}
  19781. Tuple(|$e_1, \ldots, e_n$|)
  19782. |$\Rightarrow$|
  19783. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19784. \end{lstlisting}
  19785. \fi}
  19786. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19787. AST node that we introduced in the previous
  19788. section does not get injected.
  19789. {\if\edition\racketEd
  19790. \begin{lstlisting}
  19791. (raw-vector |$e_1 \ldots e_n$|)
  19792. |$\Rightarrow$|
  19793. (vector |$e'_1 \ldots e'_n$|)
  19794. \end{lstlisting}
  19795. \fi}
  19796. {\if\edition\pythonEd
  19797. \begin{lstlisting}
  19798. RawTuple(|$e_1, \ldots, e_n$|)
  19799. |$\Rightarrow$|
  19800. Tuple(|$e'_1, \ldots, e'_n$|)
  19801. \end{lstlisting}
  19802. \fi}
  19803. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19804. translates as follows:
  19805. %
  19806. {\if\edition\racketEd
  19807. \begin{lstlisting}
  19808. (vector-proxy |$e_1~e_2~e_3$|)
  19809. |$\Rightarrow$|
  19810. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19811. \end{lstlisting}
  19812. \fi}
  19813. {\if\edition\pythonEd
  19814. \begin{lstlisting}
  19815. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19816. |$\Rightarrow$|
  19817. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19818. \end{lstlisting}
  19819. \fi}
  19820. We translate the element access operations into conditional
  19821. expressions that check whether the value is a proxy and then dispatch
  19822. to either the appropriate proxy tuple operation or the regular tuple
  19823. operation.
  19824. {\if\edition\racketEd
  19825. \begin{lstlisting}
  19826. (vector-ref |$e_1$| |$i$|)
  19827. |$\Rightarrow$|
  19828. (let ([|$v~e_1$|])
  19829. (if (proxy? |$v$|)
  19830. (proxy-vector-ref |$v$| |$i$|)
  19831. (vector-ref (project-vector |$v$|) |$i$|)
  19832. \end{lstlisting}
  19833. \fi}
  19834. %
  19835. Note that in the branch for a tuple, we must apply
  19836. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19837. from the tuple.
  19838. The translation of array operations is similar to the ones for tuples.
  19839. \section{Reveal Casts}
  19840. \label{sec:reveal-casts-gradual}
  19841. {\if\edition\racketEd
  19842. Recall that the \code{reveal\_casts} pass
  19843. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19844. \code{Inject} and \code{Project} into lower-level operations.
  19845. %
  19846. In particular, \code{Project} turns into a conditional expression that
  19847. inspects the tag and retrieves the underlying value. Here we need to
  19848. augment the translation of \code{Project} to handle the situation in which
  19849. the target type is \code{PVector}. Instead of using
  19850. \code{vector-length} we need to use \code{proxy-vector-length}.
  19851. \begin{lstlisting}
  19852. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19853. |$\Rightarrow$|
  19854. (let |$\itm{tmp}$| |$e'$|
  19855. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19856. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19857. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19858. (exit)))
  19859. \end{lstlisting}
  19860. \fi}
  19861. %
  19862. {\if\edition\pythonEd
  19863. Recall that the $\itm{tagof}$ function determines the bits used to
  19864. identify values of different types and it is used in the \code{reveal\_casts}
  19865. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19866. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19867. decimal), just like the tuple and array types.
  19868. \fi}
  19869. %
  19870. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19871. \section{Closure Conversion}
  19872. \label{sec:closure-conversion-gradual}
  19873. The auxiliary function that translates type annotations needs to be
  19874. updated to handle the \PTUPLETYNAME{}
  19875. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19876. %
  19877. Otherwise, the only other changes are adding cases that copy the new
  19878. AST nodes.
  19879. \section{Select Instructions}
  19880. \label{sec:select-instructions-gradual}
  19881. Recall that the \code{select\_instructions} pass is responsible for
  19882. lowering the primitive operations into x86 instructions. So, we need
  19883. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19884. to x86. To do so, the first question we need to answer is how to
  19885. differentiate between tuple and tuples proxies\python{, and likewise for
  19886. arrays and array proxies}. We need just one bit to accomplish this;
  19887. we use the bit in position $63$ of the 64-bit tag at the front of
  19888. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19889. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19890. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19891. it that way.
  19892. {\if\edition\racketEd
  19893. \begin{lstlisting}
  19894. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19895. |$\Rightarrow$|
  19896. movq |$e'_1$|, |$\itm{lhs'}$|
  19897. \end{lstlisting}
  19898. \fi}
  19899. {\if\edition\pythonEd
  19900. \begin{lstlisting}
  19901. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19902. |$\Rightarrow$|
  19903. movq |$e'_1$|, |$\itm{lhs'}$|
  19904. \end{lstlisting}
  19905. \fi}
  19906. \python{The translation for \code{InjectList} is also a move instruction.}
  19907. \noindent On the other hand,
  19908. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19909. $63$ to $1$.
  19910. %
  19911. {\if\edition\racketEd
  19912. \begin{lstlisting}
  19913. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19914. |$\Rightarrow$|
  19915. movq |$e'_1$|, %r11
  19916. movq |$(1 << 63)$|, %rax
  19917. orq 0(%r11), %rax
  19918. movq %rax, 0(%r11)
  19919. movq %r11, |$\itm{lhs'}$|
  19920. \end{lstlisting}
  19921. \fi}
  19922. {\if\edition\pythonEd
  19923. \begin{lstlisting}
  19924. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19925. |$\Rightarrow$|
  19926. movq |$e'_1$|, %r11
  19927. movq |$(1 << 63)$|, %rax
  19928. orq 0(%r11), %rax
  19929. movq %rax, 0(%r11)
  19930. movq %r11, |$\itm{lhs'}$|
  19931. \end{lstlisting}
  19932. \fi}
  19933. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19934. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19935. The \racket{\code{proxy?} operation consumes}%
  19936. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19937. consume}
  19938. the information so carefully stashed away by the injections. It
  19939. isolates bit $63$ to tell whether the value is a proxy.
  19940. %
  19941. {\if\edition\racketEd
  19942. \begin{lstlisting}
  19943. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19944. |$\Rightarrow$|
  19945. movq |$e_1'$|, %r11
  19946. movq 0(%r11), %rax
  19947. sarq $63, %rax
  19948. andq $1, %rax
  19949. movq %rax, |$\itm{lhs'}$|
  19950. \end{lstlisting}
  19951. \fi}%
  19952. %
  19953. {\if\edition\pythonEd
  19954. \begin{lstlisting}
  19955. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19956. |$\Rightarrow$|
  19957. movq |$e_1'$|, %r11
  19958. movq 0(%r11), %rax
  19959. sarq $63, %rax
  19960. andq $1, %rax
  19961. movq %rax, |$\itm{lhs'}$|
  19962. \end{lstlisting}
  19963. \fi}%
  19964. %
  19965. The \racket{\code{project-vector} operation is}
  19966. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19967. straightforward to translate, so we leave that to the reader.
  19968. Regarding the element access operations for tuples\python{ and arrays}, the
  19969. runtime provides procedures that implement them (they are recursive
  19970. functions!), so here we simply need to translate these tuple
  19971. operations into the appropriate function call. For example, here is
  19972. the translation for
  19973. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19974. {\if\edition\racketEd
  19975. \begin{minipage}{0.96\textwidth}
  19976. \begin{lstlisting}
  19977. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19978. |$\Rightarrow$|
  19979. movq |$e_1'$|, %rdi
  19980. movq |$e_2'$|, %rsi
  19981. callq proxy_vector_ref
  19982. movq %rax, |$\itm{lhs'}$|
  19983. \end{lstlisting}
  19984. \end{minipage}
  19985. \fi}
  19986. {\if\edition\pythonEd
  19987. \begin{lstlisting}
  19988. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19989. |$\Rightarrow$|
  19990. movq |$e_1'$|, %rdi
  19991. movq |$e_2'$|, %rsi
  19992. callq proxy_vector_ref
  19993. movq %rax, |$\itm{lhs'}$|
  19994. \end{lstlisting}
  19995. \fi}
  19996. {\if\edition\pythonEd
  19997. % TODO: revisit the names vecof for python -Jeremy
  19998. We translate
  19999. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20000. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20001. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20002. \fi}
  20003. We have another batch of operations to deal with: those for the
  20004. \CANYTY{} type. Recall that we generate an
  20005. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20006. there is a element access on something of type \CANYTY{}, and
  20007. similarly for
  20008. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20009. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20010. section~\ref{sec:select-Lany} we selected instructions for these
  20011. operations on the basis of the idea that the underlying value was a tuple or
  20012. array. But in the current setting, the underlying value is of type
  20013. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20014. functions to deal with this:
  20015. \code{proxy\_vector\_ref},
  20016. \code{proxy\_vector\_set}, and
  20017. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  20018. to determine whether the value is a proxy, and then
  20019. dispatches to the the appropriate code.
  20020. %
  20021. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20022. can be translated as follows.
  20023. We begin by projecting the underlying value out of the tagged value and
  20024. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20025. {\if\edition\racketEd
  20026. \begin{lstlisting}
  20027. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20028. |$\Rightarrow$|
  20029. movq |$\neg 111$|, %rdi
  20030. andq |$e_1'$|, %rdi
  20031. movq |$e_2'$|, %rsi
  20032. callq proxy_vector_ref
  20033. movq %rax, |$\itm{lhs'}$|
  20034. \end{lstlisting}
  20035. \fi}
  20036. {\if\edition\pythonEd
  20037. \begin{lstlisting}
  20038. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20039. |$\Rightarrow$|
  20040. movq |$\neg 111$|, %rdi
  20041. andq |$e_1'$|, %rdi
  20042. movq |$e_2'$|, %rsi
  20043. callq proxy_vector_ref
  20044. movq %rax, |$\itm{lhs'}$|
  20045. \end{lstlisting}
  20046. \fi}
  20047. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20048. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20049. are translated in a similar way. Alternatively, you could generate
  20050. instructions to open-code
  20051. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20052. and \code{proxy\_vector\_length} functions.
  20053. \begin{exercise}\normalfont\normalsize
  20054. Implement a compiler for the gradually typed \LangGrad{} language by
  20055. extending and adapting your compiler for \LangLam{}. Create ten new
  20056. partially typed test programs. In addition to testing with these
  20057. new programs, test your compiler on all the tests for \LangLam{}
  20058. and for \LangDyn{}.
  20059. %
  20060. \racket{Sometimes you may get a type checking error on the
  20061. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20062. the \CANYTY{} type around each subexpression that has caused a type
  20063. error. Although \LangDyn{} does not have explicit casts, you can
  20064. induce one by wrapping the subexpression \code{e} with a call to
  20065. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20066. %
  20067. \python{Sometimes you may get a type checking error on the
  20068. \LangDyn{} programs but you can adapt them by inserting a
  20069. temporary variable of type \CANYTY{} that is initialized with the
  20070. troublesome expression.}
  20071. \end{exercise}
  20072. \begin{figure}[p]
  20073. \begin{tcolorbox}[colback=white]
  20074. {\if\edition\racketEd
  20075. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20076. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20077. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20078. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20079. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20080. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20081. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20082. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20083. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20084. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20085. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20086. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20087. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20088. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20089. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20090. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20091. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20092. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20093. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20094. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20095. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20096. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20097. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20098. \path[->,bend left=15] (Lgradual) edge [above] node
  20099. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20100. \path[->,bend left=15] (Lgradual2) edge [above] node
  20101. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20102. \path[->,bend left=15] (Lgradual3) edge [above] node
  20103. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20104. \path[->,bend left=15] (Lgradual4) edge [left] node
  20105. {\ttfamily\footnotesize shrink} (Lgradualr);
  20106. \path[->,bend left=15] (Lgradualr) edge [above] node
  20107. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20108. \path[->,bend right=15] (Lgradualp) edge [above] node
  20109. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20110. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20111. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20112. \path[->,bend right=15] (Llambdapp) edge [above] node
  20113. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20114. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20115. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20116. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20117. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20118. \path[->,bend left=15] (F1-2) edge [above] node
  20119. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20120. \path[->,bend left=15] (F1-3) edge [left] node
  20121. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20122. \path[->,bend left=15] (F1-4) edge [below] node
  20123. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20124. \path[->,bend right=15] (F1-5) edge [above] node
  20125. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20126. \path[->,bend right=15] (F1-6) edge [above] node
  20127. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20128. \path[->,bend right=15] (C3-2) edge [right] node
  20129. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20130. \path[->,bend right=15] (x86-2) edge [right] node
  20131. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20132. \path[->,bend right=15] (x86-2-1) edge [below] node
  20133. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20134. \path[->,bend right=15] (x86-2-2) edge [right] node
  20135. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20136. \path[->,bend left=15] (x86-3) edge [above] node
  20137. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20138. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20139. \end{tikzpicture}
  20140. \fi}
  20141. {\if\edition\pythonEd
  20142. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20143. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20144. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20145. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20146. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20147. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20148. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20149. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20150. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20151. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20152. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20153. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20154. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20155. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20156. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20157. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20158. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20159. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20160. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20161. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20162. \path[->,bend left=15] (Lgradual) edge [above] node
  20163. {\ttfamily\footnotesize shrink} (Lgradual2);
  20164. \path[->,bend left=15] (Lgradual2) edge [above] node
  20165. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20166. \path[->,bend left=15] (Lgradual3) edge [above] node
  20167. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20168. \path[->,bend left=15] (Lgradual4) edge [left] node
  20169. {\ttfamily\footnotesize resolve} (Lgradualr);
  20170. \path[->,bend left=15] (Lgradualr) edge [below] node
  20171. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20172. \path[->,bend right=15] (Lgradualp) edge [above] node
  20173. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20174. \path[->,bend right=15] (Llambdapp) edge [above] node
  20175. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20176. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20177. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20178. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20179. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20180. \path[->,bend left=15] (F1-1) edge [above] node
  20181. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20182. \path[->,bend left=15] (F1-2) edge [above] node
  20183. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20184. \path[->,bend left=15] (F1-3) edge [right] node
  20185. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20186. \path[->,bend right=15] (F1-5) edge [above] node
  20187. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20188. \path[->,bend right=15] (F1-6) edge [above] node
  20189. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20190. \path[->,bend right=15] (C3-2) edge [right] node
  20191. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20192. \path[->,bend right=15] (x86-2) edge [below] node
  20193. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20194. \path[->,bend right=15] (x86-3) edge [below] node
  20195. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20196. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20197. \end{tikzpicture}
  20198. \fi}
  20199. \end{tcolorbox}
  20200. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20201. \label{fig:Lgradual-passes}
  20202. \end{figure}
  20203. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20204. needed for the compilation of \LangGrad{}.
  20205. \section{Further Reading}
  20206. This chapter just scratches the surface of gradual typing. The basic
  20207. approach described here is missing two key ingredients that one would
  20208. want in a implementation of gradual typing: blame
  20209. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20210. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20211. problem addressed by blame tracking is that when a cast on a
  20212. higher-order value fails, it often does so at a point in the program
  20213. that is far removed from the original cast. Blame tracking is a
  20214. technique for propagating extra information through casts and proxies
  20215. so that when a cast fails, the error message can point back to the
  20216. original location of the cast in the source program.
  20217. The problem addressed by space-efficient casts also relates to
  20218. higher-order casts. It turns out that in partially typed programs, a
  20219. function or tuple can flow through a great many casts at runtime. With
  20220. the approach described in this chapter, each cast adds another
  20221. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20222. considerable space, but it also makes the function calls and tuple
  20223. operations slow. For example, a partially typed version of quicksort
  20224. could, in the worst case, build a chain of proxies of length $O(n)$
  20225. around the tuple, changing the overall time complexity of the
  20226. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20227. solution to this problem by representing casts using the coercion
  20228. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20229. long chains of proxies by compressing them into a concise normal
  20230. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20231. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20232. the Grift compiler:
  20233. \begin{center}
  20234. \url{https://github.com/Gradual-Typing/Grift}
  20235. \end{center}
  20236. There are also interesting interactions between gradual typing and
  20237. other language features, such as generics, information-flow types, and
  20238. type inference, to name a few. We recommend to the reader the
  20239. online gradual typing bibliography for more material:
  20240. \begin{center}
  20241. \url{http://samth.github.io/gradual-typing-bib/}
  20242. \end{center}
  20243. % TODO: challenge problem:
  20244. % type analysis and type specialization?
  20245. % coercions?
  20246. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20247. \chapter{Generics}
  20248. \label{ch:Lpoly}
  20249. \index{subject}{parametric polymorphism}
  20250. \index{subject}{generics}
  20251. \setcounter{footnote}{0}
  20252. This chapter studies the compilation of
  20253. generics\index{subject}{generics} (aka parametric
  20254. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20255. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20256. enable programmers to make code more reusable by parameterizing
  20257. functions and data structures with respect to the types on which they
  20258. operate. For example, figure~\ref{fig:map-poly} revisits the
  20259. \code{map} example and this time gives it a more fitting type. This
  20260. \code{map} function is parameterized with respect to the element type
  20261. of the tuple. The type of \code{map} is the following generic type
  20262. specified by the \code{All} type with parameter \code{T}:
  20263. \if\edition\racketEd
  20264. \begin{lstlisting}
  20265. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20266. \end{lstlisting}
  20267. \fi
  20268. \if\edition\pythonEd
  20269. \begin{lstlisting}
  20270. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20271. \end{lstlisting}
  20272. \fi
  20273. %
  20274. The idea is that \code{map} can be used at \emph{all} choices of a
  20275. type for parameter \code{T}. In the example shown in
  20276. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20277. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20278. \code{T}, but we could have just as well applied \code{map} to a tuple
  20279. of Booleans.
  20280. %
  20281. A \emph{monomorphic} function is simply one that is not generic.
  20282. %
  20283. We use the term \emph{instantiation} for the process (within the
  20284. language implementation) of turning a generic function into a
  20285. monomorphic one, where the type parameters have been replaced by
  20286. types.
  20287. \if\edition\pythonEd
  20288. %
  20289. In Python, when writing a generic function such as \code{map}, one
  20290. does not explicitly write down its generic type (using \code{All}).
  20291. Instead, the fact that it is generic is implied by the use of type
  20292. variables (such as \code{T}) in the type annotations of its
  20293. parameters.
  20294. %
  20295. \fi
  20296. \begin{figure}[tbp]
  20297. % poly_test_2.rkt
  20298. \begin{tcolorbox}[colback=white]
  20299. \if\edition\racketEd
  20300. \begin{lstlisting}
  20301. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20302. (define (map f v)
  20303. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20304. (define (inc [x : Integer]) : Integer (+ x 1))
  20305. (vector-ref (map inc (vector 0 41)) 1)
  20306. \end{lstlisting}
  20307. \fi
  20308. \if\edition\pythonEd
  20309. \begin{lstlisting}
  20310. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20311. return (f(tup[0]), f(tup[1]))
  20312. def add1(x : int) -> int:
  20313. return x + 1
  20314. t = map(add1, (0, 41))
  20315. print(t[1])
  20316. \end{lstlisting}
  20317. \fi
  20318. \end{tcolorbox}
  20319. \caption{A generic version of the \code{map} function.}
  20320. \label{fig:map-poly}
  20321. \end{figure}
  20322. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20323. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20324. shows the definition of the abstract syntax.
  20325. %
  20326. \if\edition\racketEd
  20327. We add a second form for function definitions in which a type
  20328. declaration comes before the \code{define}. In the abstract syntax,
  20329. the return type in the \code{Def} is \CANYTY{}, but that should be
  20330. ignored in favor of the return type in the type declaration. (The
  20331. \CANYTY{} comes from using the same parser as discussed in
  20332. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20333. enables the use of an \code{All} type for a function, thereby making
  20334. it generic.
  20335. \fi
  20336. %
  20337. The grammar for types is extended to include the type of a generic
  20338. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  20339. abstract syntax)}.
  20340. \newcommand{\LpolyGrammarRacket}{
  20341. \begin{array}{lcl}
  20342. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20343. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20344. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20345. \end{array}
  20346. }
  20347. \newcommand{\LpolyASTRacket}{
  20348. \begin{array}{lcl}
  20349. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20350. \Def &::=& \DECL{\Var}{\Type} \\
  20351. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20352. \end{array}
  20353. }
  20354. \newcommand{\LpolyGrammarPython}{
  20355. \begin{array}{lcl}
  20356. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20357. \end{array}
  20358. }
  20359. \newcommand{\LpolyASTPython}{
  20360. \begin{array}{lcl}
  20361. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20362. \MID \key{GenericVar}\LP\Var\RP
  20363. \end{array}
  20364. }
  20365. \begin{figure}[tp]
  20366. \centering
  20367. \begin{tcolorbox}[colback=white]
  20368. \footnotesize
  20369. \if\edition\racketEd
  20370. \[
  20371. \begin{array}{l}
  20372. \gray{\LintGrammarRacket{}} \\ \hline
  20373. \gray{\LvarGrammarRacket{}} \\ \hline
  20374. \gray{\LifGrammarRacket{}} \\ \hline
  20375. \gray{\LwhileGrammarRacket} \\ \hline
  20376. \gray{\LtupGrammarRacket} \\ \hline
  20377. \gray{\LfunGrammarRacket} \\ \hline
  20378. \gray{\LlambdaGrammarRacket} \\ \hline
  20379. \LpolyGrammarRacket \\
  20380. \begin{array}{lcl}
  20381. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20382. \end{array}
  20383. \end{array}
  20384. \]
  20385. \fi
  20386. \if\edition\pythonEd
  20387. \[
  20388. \begin{array}{l}
  20389. \gray{\LintGrammarPython{}} \\ \hline
  20390. \gray{\LvarGrammarPython{}} \\ \hline
  20391. \gray{\LifGrammarPython{}} \\ \hline
  20392. \gray{\LwhileGrammarPython} \\ \hline
  20393. \gray{\LtupGrammarPython} \\ \hline
  20394. \gray{\LfunGrammarPython} \\ \hline
  20395. \gray{\LlambdaGrammarPython} \\\hline
  20396. \LpolyGrammarPython \\
  20397. \begin{array}{lcl}
  20398. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20399. \end{array}
  20400. \end{array}
  20401. \]
  20402. \fi
  20403. \end{tcolorbox}
  20404. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20405. (figure~\ref{fig:Llam-concrete-syntax}).}
  20406. \label{fig:Lpoly-concrete-syntax}
  20407. \end{figure}
  20408. \begin{figure}[tp]
  20409. \centering
  20410. \begin{tcolorbox}[colback=white]
  20411. \footnotesize
  20412. \if\edition\racketEd
  20413. \[
  20414. \begin{array}{l}
  20415. \gray{\LintOpAST} \\ \hline
  20416. \gray{\LvarASTRacket{}} \\ \hline
  20417. \gray{\LifASTRacket{}} \\ \hline
  20418. \gray{\LwhileASTRacket{}} \\ \hline
  20419. \gray{\LtupASTRacket{}} \\ \hline
  20420. \gray{\LfunASTRacket} \\ \hline
  20421. \gray{\LlambdaASTRacket} \\ \hline
  20422. \LpolyASTRacket \\
  20423. \begin{array}{lcl}
  20424. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20425. \end{array}
  20426. \end{array}
  20427. \]
  20428. \fi
  20429. \if\edition\pythonEd
  20430. \[
  20431. \begin{array}{l}
  20432. \gray{\LintASTPython} \\ \hline
  20433. \gray{\LvarASTPython{}} \\ \hline
  20434. \gray{\LifASTPython{}} \\ \hline
  20435. \gray{\LwhileASTPython{}} \\ \hline
  20436. \gray{\LtupASTPython{}} \\ \hline
  20437. \gray{\LfunASTPython} \\ \hline
  20438. \gray{\LlambdaASTPython} \\ \hline
  20439. \LpolyASTPython \\
  20440. \begin{array}{lcl}
  20441. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20442. \end{array}
  20443. \end{array}
  20444. \]
  20445. \fi
  20446. \end{tcolorbox}
  20447. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20448. (figure~\ref{fig:Llam-syntax}).}
  20449. \label{fig:Lpoly-syntax}
  20450. \end{figure}
  20451. By including the \code{All} type in the $\Type$ nonterminal of the
  20452. grammar we choose to make generics first class, which has interesting
  20453. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20454. not include syntax for the \code{All} type. It is inferred for functions whose
  20455. type annotations contain type variables.} Many languages with generics, such as
  20456. C++~\citep{stroustrup88:_param_types} and Standard
  20457. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20458. may be helpful to see an example of first-class generics in action. In
  20459. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20460. whose parameter is a generic function. Indeed, because the grammar for
  20461. $\Type$ includes the \code{All} type, a generic function may also be
  20462. returned from a function or stored inside a tuple. The body of
  20463. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20464. and also to an integer, which would not be possible if \code{f} were
  20465. not generic.
  20466. \begin{figure}[tbp]
  20467. \begin{tcolorbox}[colback=white]
  20468. \if\edition\racketEd
  20469. \begin{lstlisting}
  20470. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20471. (define (apply_twice f)
  20472. (if (f #t) (f 42) (f 777)))
  20473. (: id (All (T) (T -> T)))
  20474. (define (id x) x)
  20475. (apply_twice id)
  20476. \end{lstlisting}
  20477. \fi
  20478. \if\edition\pythonEd
  20479. \begin{lstlisting}
  20480. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20481. if f(True):
  20482. return f(42)
  20483. else:
  20484. return f(777)
  20485. def id(x: T) -> T:
  20486. return x
  20487. print(apply_twice(id))
  20488. \end{lstlisting}
  20489. \fi
  20490. \end{tcolorbox}
  20491. \caption{An example illustrating first-class generics.}
  20492. \label{fig:apply-twice}
  20493. \end{figure}
  20494. The type checker for \LangPoly{} shown in
  20495. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20496. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20497. \if\edition\pythonEd
  20498. %
  20499. Regarding function definitions, if the type annotations on its
  20500. parameters contain generic variables, then the function is generic and
  20501. therefore its type is an \code{All} type wrapped around a function
  20502. type. Otherwise the function is monomorphic and its type is simply
  20503. a function type.
  20504. %
  20505. \fi
  20506. The type checking of a function application is extended to handle the
  20507. case in which the operator expression is a generic function. In that case
  20508. the type arguments are deduced by matching the type of the parameters
  20509. with the types of the arguments.
  20510. %
  20511. The \code{match\_types} auxiliary function
  20512. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20513. recursively descending through a parameter type \code{param\_ty} and
  20514. the corresponding argument type \code{arg\_ty}, making sure that they
  20515. are equal except when there is a type parameter in the parameter
  20516. type. Upon encountering a type parameter for the first time, the
  20517. algorithm deduces an association of the type parameter to the
  20518. corresponding part of the argument type. If it is not the first time
  20519. that the type parameter has been encountered, the algorithm looks up
  20520. its deduced type and makes sure that it is equal to the corresponding
  20521. part of the argument type. The return type of the application is the
  20522. return type of the generic function with the type parameters
  20523. replaced by the deduced type arguments, using the
  20524. \code{substitute\_type} auxiliary function, which is also listed in
  20525. figure~\ref{fig:type-check-Lpoly-aux}.
  20526. The type checker extends type equality to handle the \code{All} type.
  20527. This is not quite as simple as for other types, such as function and
  20528. tuple types, because two \code{All} types can be syntactically
  20529. different even though they are equivalent. For example,
  20530. %
  20531. \racket{\code{(All (T) (T -> T))}}
  20532. \python{\code{All[[T], Callable[[T], T]]}}
  20533. is equivalent to
  20534. \racket{\code{(All (U) (U -> U))}}
  20535. \python{\code{All[[U], Callable[[U], U]]}}.
  20536. %
  20537. Two generic types should be considered equal if they differ only in
  20538. the choice of the names of the type parameters. The definition of type
  20539. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20540. parameters in one type to match the type parameters of the other type.
  20541. \if\edition\racketEd
  20542. %
  20543. The type checker also ensures that only defined type variables appear
  20544. in type annotations. The \code{check\_well\_formed} function for which
  20545. the definition is shown in figure~\ref{fig:well-formed-types}
  20546. recursively inspects a type, making sure that each type variable has
  20547. been defined.
  20548. %
  20549. \fi
  20550. \begin{figure}[tbp]
  20551. \begin{tcolorbox}[colback=white]
  20552. \if\edition\racketEd
  20553. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20554. (define type-check-poly-class
  20555. (class type-check-Llambda-class
  20556. (super-new)
  20557. (inherit check-type-equal?)
  20558. (define/override (type-check-apply env e1 es)
  20559. (define-values (e^ ty) ((type-check-exp env) e1))
  20560. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20561. ((type-check-exp env) e)))
  20562. (match ty
  20563. [`(,ty^* ... -> ,rt)
  20564. (for ([arg-ty ty*] [param-ty ty^*])
  20565. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20566. (values e^ es^ rt)]
  20567. [`(All ,xs (,tys ... -> ,rt))
  20568. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20569. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20570. (match_types env^^ param-ty arg-ty)))
  20571. (define targs
  20572. (for/list ([x xs])
  20573. (match (dict-ref env^^ x (lambda () #f))
  20574. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20575. x (Apply e1 es))]
  20576. [ty ty])))
  20577. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20578. [else (error 'type-check "expected a function, not ~a" ty)]))
  20579. (define/override ((type-check-exp env) e)
  20580. (match e
  20581. [(Lambda `([,xs : ,Ts] ...) rT body)
  20582. (for ([T Ts]) ((check_well_formed env) T))
  20583. ((check_well_formed env) rT)
  20584. ((super type-check-exp env) e)]
  20585. [(HasType e1 ty)
  20586. ((check_well_formed env) ty)
  20587. ((super type-check-exp env) e)]
  20588. [else ((super type-check-exp env) e)]))
  20589. (define/override ((type-check-def env) d)
  20590. (verbose 'type-check "poly/def" d)
  20591. (match d
  20592. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20593. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20594. (for ([p ps]) ((check_well_formed ts-env) p))
  20595. ((check_well_formed ts-env) rt)
  20596. (define new-env (append ts-env (map cons xs ps) env))
  20597. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20598. (check-type-equal? ty^ rt body)
  20599. (Generic ts (Def f p:t* rt info body^))]
  20600. [else ((super type-check-def env) d)]))
  20601. (define/override (type-check-program p)
  20602. (match p
  20603. [(Program info body)
  20604. (type-check-program (ProgramDefsExp info '() body))]
  20605. [(ProgramDefsExp info ds body)
  20606. (define ds^ (combine-decls-defs ds))
  20607. (define new-env (for/list ([d ds^])
  20608. (cons (def-name d) (fun-def-type d))))
  20609. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20610. (define-values (body^ ty) ((type-check-exp new-env) body))
  20611. (check-type-equal? ty 'Integer body)
  20612. (ProgramDefsExp info ds^^ body^)]))
  20613. ))
  20614. \end{lstlisting}
  20615. \fi
  20616. \if\edition\pythonEd
  20617. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20618. def type_check_exp(self, e, env):
  20619. match e:
  20620. case Call(Name(f), args) if f in builtin_functions:
  20621. return super().type_check_exp(e, env)
  20622. case Call(func, args):
  20623. func_t = self.type_check_exp(func, env)
  20624. func.has_type = func_t
  20625. match func_t:
  20626. case AllType(ps, FunctionType(p_tys, rt)):
  20627. for arg in args:
  20628. arg.has_type = self.type_check_exp(arg, env)
  20629. arg_tys = [arg.has_type for arg in args]
  20630. deduced = {}
  20631. for (p, a) in zip(p_tys, arg_tys):
  20632. self.match_types(p, a, deduced, e)
  20633. return self.substitute_type(rt, deduced)
  20634. case _:
  20635. return super().type_check_exp(e, env)
  20636. case _:
  20637. return super().type_check_exp(e, env)
  20638. def type_check(self, p):
  20639. match p:
  20640. case Module(body):
  20641. env = {}
  20642. for s in body:
  20643. match s:
  20644. case FunctionDef(name, params, bod, dl, returns, comment):
  20645. params_t = [t for (x,t) in params]
  20646. ty_params = set()
  20647. for t in params_t:
  20648. ty_params |$\mid$|= self.generic_variables(t)
  20649. ty = FunctionType(params_t, returns)
  20650. if len(ty_params) > 0:
  20651. ty = AllType(list(ty_params), ty)
  20652. env[name] = ty
  20653. self.check_stmts(body, IntType(), env)
  20654. case _:
  20655. raise Exception('type_check: unexpected ' + repr(p))
  20656. \end{lstlisting}
  20657. \fi
  20658. \end{tcolorbox}
  20659. \caption{Type checker for the \LangPoly{} language.}
  20660. \label{fig:type-check-Lpoly}
  20661. \end{figure}
  20662. \begin{figure}[tbp]
  20663. \begin{tcolorbox}[colback=white]
  20664. \if\edition\racketEd
  20665. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20666. (define/override (type-equal? t1 t2)
  20667. (match* (t1 t2)
  20668. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20669. (define env (map cons xs ys))
  20670. (type-equal? (substitute_type env T1) T2)]
  20671. [(other wise)
  20672. (super type-equal? t1 t2)]))
  20673. (define/public (match_types env pt at)
  20674. (match* (pt at)
  20675. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20676. [('Void 'Void) env] [('Any 'Any) env]
  20677. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20678. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20679. (match_types env^ pt1 at1))]
  20680. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20681. (define env^ (match_types env prt art))
  20682. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20683. (match_types env^^ pt1 at1))]
  20684. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20685. (define env^ (append (map cons pxs axs) env))
  20686. (match_types env^ pt1 at1)]
  20687. [((? symbol? x) at)
  20688. (match (dict-ref env x (lambda () #f))
  20689. [#f (error 'type-check "undefined type variable ~a" x)]
  20690. ['Type (cons (cons x at) env)]
  20691. [t^ (check-type-equal? at t^ 'matching) env])]
  20692. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20693. (define/public (substitute_type env pt)
  20694. (match pt
  20695. ['Integer 'Integer] ['Boolean 'Boolean]
  20696. ['Void 'Void] ['Any 'Any]
  20697. [`(Vector ,ts ...)
  20698. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20699. [`(,ts ... -> ,rt)
  20700. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20701. [`(All ,xs ,t)
  20702. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20703. [(? symbol? x) (dict-ref env x)]
  20704. [else (error 'type-check "expected a type not ~a" pt)]))
  20705. (define/public (combine-decls-defs ds)
  20706. (match ds
  20707. ['() '()]
  20708. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20709. (unless (equal? name f)
  20710. (error 'type-check "name mismatch, ~a != ~a" name f))
  20711. (match type
  20712. [`(All ,xs (,ps ... -> ,rt))
  20713. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20714. (cons (Generic xs (Def name params^ rt info body))
  20715. (combine-decls-defs ds^))]
  20716. [`(,ps ... -> ,rt)
  20717. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20718. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20719. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20720. [`(,(Def f params rt info body) . ,ds^)
  20721. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20722. \end{lstlisting}
  20723. \fi
  20724. \if\edition\pythonEd
  20725. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20726. def match_types(self, param_ty, arg_ty, deduced, e):
  20727. match (param_ty, arg_ty):
  20728. case (GenericVar(id), _):
  20729. if id in deduced:
  20730. self.check_type_equal(arg_ty, deduced[id], e)
  20731. else:
  20732. deduced[id] = arg_ty
  20733. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20734. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20735. new_arg_ty = self.substitute_type(arg_ty, rename)
  20736. self.match_types(ty, new_arg_ty, deduced, e)
  20737. case (TupleType(ps), TupleType(ts)):
  20738. for (p, a) in zip(ps, ts):
  20739. self.match_types(p, a, deduced, e)
  20740. case (ListType(p), ListType(a)):
  20741. self.match_types(p, a, deduced, e)
  20742. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20743. for (pp, ap) in zip(pps, aps):
  20744. self.match_types(pp, ap, deduced, e)
  20745. self.match_types(prt, art, deduced, e)
  20746. case (IntType(), IntType()):
  20747. pass
  20748. case (BoolType(), BoolType()):
  20749. pass
  20750. case _:
  20751. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20752. def substitute_type(self, ty, var_map):
  20753. match ty:
  20754. case GenericVar(id):
  20755. return var_map[id]
  20756. case AllType(ps, ty):
  20757. new_map = copy.deepcopy(var_map)
  20758. for p in ps:
  20759. new_map[p] = GenericVar(p)
  20760. return AllType(ps, self.substitute_type(ty, new_map))
  20761. case TupleType(ts):
  20762. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20763. case ListType(ty):
  20764. return ListType(self.substitute_type(ty, var_map))
  20765. case FunctionType(pts, rt):
  20766. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20767. self.substitute_type(rt, var_map))
  20768. case IntType():
  20769. return IntType()
  20770. case BoolType():
  20771. return BoolType()
  20772. case _:
  20773. raise Exception('substitute_type: unexpected ' + repr(ty))
  20774. def check_type_equal(self, t1, t2, e):
  20775. match (t1, t2):
  20776. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20777. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20778. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20779. case (_, _):
  20780. return super().check_type_equal(t1, t2, e)
  20781. \end{lstlisting}
  20782. \fi
  20783. \end{tcolorbox}
  20784. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20785. \label{fig:type-check-Lpoly-aux}
  20786. \end{figure}
  20787. \if\edition\racketEd
  20788. \begin{figure}[tbp]
  20789. \begin{tcolorbox}[colback=white]
  20790. \begin{lstlisting}
  20791. (define/public ((check_well_formed env) ty)
  20792. (match ty
  20793. ['Integer (void)]
  20794. ['Boolean (void)]
  20795. ['Void (void)]
  20796. [(? symbol? a)
  20797. (match (dict-ref env a (lambda () #f))
  20798. ['Type (void)]
  20799. [else (error 'type-check "undefined type variable ~a" a)])]
  20800. [`(Vector ,ts ...)
  20801. (for ([t ts]) ((check_well_formed env) t))]
  20802. [`(,ts ... -> ,t)
  20803. (for ([t ts]) ((check_well_formed env) t))
  20804. ((check_well_formed env) t)]
  20805. [`(All ,xs ,t)
  20806. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20807. ((check_well_formed env^) t)]
  20808. [else (error 'type-check "unrecognized type ~a" ty)]))
  20809. \end{lstlisting}
  20810. \end{tcolorbox}
  20811. \caption{Well-formed types.}
  20812. \label{fig:well-formed-types}
  20813. \end{figure}
  20814. \fi
  20815. % TODO: interpreter for R'_10
  20816. \clearpage
  20817. \section{Compiling Generics}
  20818. \label{sec:compiling-poly}
  20819. Broadly speaking, there are four approaches to compiling generics, as
  20820. follows:
  20821. \begin{description}
  20822. \item[Monomorphization] generates a different version of a generic
  20823. function for each set of type arguments with which it is used,
  20824. producing type-specialized code. This approach results in the most
  20825. efficient code but requires whole-program compilation (no separate
  20826. compilation) and may increase code size. Unfortunately,
  20827. monomorphization is incompatible with first-class generics, because
  20828. it is not always possible to determine which generic functions are
  20829. used with which type arguments during compilation. (It can be done
  20830. at runtime, with just-in-time compilation.) Monomorphization is
  20831. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20832. generic functions in NESL~\citep{Blelloch:1993aa} and
  20833. ML~\citep{Weeks:2006aa}.
  20834. \item[Uniform representation] generates one version of each generic
  20835. function and requires all values to have a common \emph{boxed} format,
  20836. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20837. generic and monomorphic code is compiled similarly to code in a
  20838. dynamically typed language (like \LangDyn{}), in which primitive
  20839. operators require their arguments to be projected from \CANYTY{} and
  20840. their results to be injected into \CANYTY{}. (In object-oriented
  20841. languages, the projection is accomplished via virtual method
  20842. dispatch.) The uniform representation approach is compatible with
  20843. separate compilation and with first-class generics. However, it
  20844. produces the least efficient code because it introduces overhead in
  20845. the entire program. This approach is used in
  20846. Java~\citep{Bracha:1998fk},
  20847. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20848. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20849. \item[Mixed representation] generates one version of each generic
  20850. function, using a boxed representation for type variables. However,
  20851. monomorphic code is compiled as usual (as in \LangLam{}), and
  20852. conversions are performed at the boundaries between monomorphic code
  20853. and polymorphic code (e.g., when a generic function is instantiated
  20854. and called). This approach is compatible with separate compilation
  20855. and first-class generics and maintains efficiency in monomorphic
  20856. code. The trade-off is increased overhead at the boundary between
  20857. monomorphic and generic code. This approach is used in
  20858. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20859. Java 5 with the addition of autoboxing.
  20860. \item[Type passing] uses the unboxed representation in both
  20861. monomorphic and generic code. Each generic function is compiled to a
  20862. single function with extra parameters that describe the type
  20863. arguments. The type information is used by the generated code to
  20864. determine how to access the unboxed values at runtime. This approach is
  20865. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20866. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20867. compilation and first-class generics and maintains the
  20868. efficiency for monomorphic code. There is runtime overhead in
  20869. polymorphic code from dispatching on type information.
  20870. \end{description}
  20871. In this chapter we use the mixed representation approach, partly
  20872. because of its favorable attributes and partly because it is
  20873. straightforward to implement using the tools that we have already
  20874. built to support gradual typing. The work of compiling generic
  20875. functions is performed in two passes, \code{resolve} and
  20876. \code{erase\_types}, that we discuss next. The output of
  20877. \code{erase\_types} is \LangCast{}
  20878. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20879. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20880. \section{Resolve Instantiation}
  20881. \label{sec:generic-resolve}
  20882. Recall that the type checker for \LangPoly{} deduces the type
  20883. arguments at call sites to a generic function. The purpose of the
  20884. \code{resolve} pass is to turn this implicit instantiation into an
  20885. explicit one, by adding \code{inst} nodes to the syntax of the
  20886. intermediate language. An \code{inst} node records the mapping of
  20887. type parameters to type arguments. The semantics of the \code{inst}
  20888. node is to instantiate the result of its first argument, a generic
  20889. function, to produce a monomorphic function. However, because the
  20890. interpreter never analyzes type annotations, instantiation can be a
  20891. no-op and simply return the generic function.
  20892. %
  20893. The output language of the \code{resolve} pass is \LangInst{},
  20894. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20895. \if\edition\racketEd
  20896. The \code{resolve} pass combines the type declaration and polymorphic
  20897. function into a single definition, using the \code{Poly} form, to make
  20898. polymorphic functions more convenient to process in the next pass of the
  20899. compiler.
  20900. \fi
  20901. \newcommand{\LinstASTRacket}{
  20902. \begin{array}{lcl}
  20903. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20904. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20905. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20906. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20907. \end{array}
  20908. }
  20909. \newcommand{\LinstASTPython}{
  20910. \begin{array}{lcl}
  20911. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20912. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20913. \end{array}
  20914. }
  20915. \begin{figure}[tp]
  20916. \centering
  20917. \begin{tcolorbox}[colback=white]
  20918. \small
  20919. \if\edition\racketEd
  20920. \[
  20921. \begin{array}{l}
  20922. \gray{\LintOpAST} \\ \hline
  20923. \gray{\LvarASTRacket{}} \\ \hline
  20924. \gray{\LifASTRacket{}} \\ \hline
  20925. \gray{\LwhileASTRacket{}} \\ \hline
  20926. \gray{\LtupASTRacket{}} \\ \hline
  20927. \gray{\LfunASTRacket} \\ \hline
  20928. \gray{\LlambdaASTRacket} \\ \hline
  20929. \LinstASTRacket \\
  20930. \begin{array}{lcl}
  20931. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20932. \end{array}
  20933. \end{array}
  20934. \]
  20935. \fi
  20936. \if\edition\pythonEd
  20937. \[
  20938. \begin{array}{l}
  20939. \gray{\LintASTPython} \\ \hline
  20940. \gray{\LvarASTPython{}} \\ \hline
  20941. \gray{\LifASTPython{}} \\ \hline
  20942. \gray{\LwhileASTPython{}} \\ \hline
  20943. \gray{\LtupASTPython{}} \\ \hline
  20944. \gray{\LfunASTPython} \\ \hline
  20945. \gray{\LlambdaASTPython} \\ \hline
  20946. \LinstASTPython \\
  20947. \begin{array}{lcl}
  20948. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20949. \end{array}
  20950. \end{array}
  20951. \]
  20952. \fi
  20953. \end{tcolorbox}
  20954. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20955. (figure~\ref{fig:Llam-syntax}).}
  20956. \label{fig:Lpoly-prime-syntax}
  20957. \end{figure}
  20958. The output of the \code{resolve} pass on the generic \code{map}
  20959. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20960. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20961. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20962. \begin{figure}[tbp]
  20963. % poly_test_2.rkt
  20964. \begin{tcolorbox}[colback=white]
  20965. \if\edition\racketEd
  20966. \begin{lstlisting}
  20967. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20968. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20969. (define (inc [x : Integer]) : Integer (+ x 1))
  20970. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20971. (Integer))
  20972. inc (vector 0 41)) 1)
  20973. \end{lstlisting}
  20974. \fi
  20975. \if\edition\pythonEd
  20976. \begin{lstlisting}
  20977. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20978. return (f(tup[0]), f(tup[1]))
  20979. def add1(x : int) -> int:
  20980. return x + 1
  20981. t = inst(map, {T: int})(add1, (0, 41))
  20982. print(t[1])
  20983. \end{lstlisting}
  20984. \fi
  20985. \end{tcolorbox}
  20986. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20987. \label{fig:map-resolve}
  20988. \end{figure}
  20989. \section{Erase Types}
  20990. \label{sec:erase_types}
  20991. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20992. represent type variables. For example, figure~\ref{fig:map-erase}
  20993. shows the output of the \code{erase\_types} pass on the generic
  20994. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20995. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  20996. \code{All} types are removed from the type of \code{map}.
  20997. \begin{figure}[tbp]
  20998. \begin{tcolorbox}[colback=white]
  20999. \if\edition\racketEd
  21000. \begin{lstlisting}
  21001. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21002. : (Vector Any Any)
  21003. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21004. (define (inc [x : Integer]) : Integer (+ x 1))
  21005. (vector-ref ((cast map
  21006. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21007. ((Integer -> Integer) (Vector Integer Integer)
  21008. -> (Vector Integer Integer)))
  21009. inc (vector 0 41)) 1)
  21010. \end{lstlisting}
  21011. \fi
  21012. \if\edition\pythonEd
  21013. \begin{lstlisting}
  21014. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21015. return (f(tup[0]), f(tup[1]))
  21016. def add1(x : int) -> int:
  21017. return (x + 1)
  21018. def main() -> int:
  21019. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21020. print(t[1])
  21021. return 0
  21022. \end{lstlisting}
  21023. {\small
  21024. where\\
  21025. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21026. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21027. }
  21028. \fi
  21029. \end{tcolorbox}
  21030. \caption{The generic \code{map} example after type erasure.}
  21031. \label{fig:map-erase}
  21032. \end{figure}
  21033. This process of type erasure creates a challenge at points of
  21034. instantiation. For example, consider the instantiation of
  21035. \code{map} shown in figure~\ref{fig:map-resolve}.
  21036. The type of \code{map} is
  21037. %
  21038. \if\edition\racketEd
  21039. \begin{lstlisting}
  21040. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21041. \end{lstlisting}
  21042. \fi
  21043. \if\edition\pythonEd
  21044. \begin{lstlisting}
  21045. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21046. \end{lstlisting}
  21047. \fi
  21048. %
  21049. and it is instantiated to
  21050. %
  21051. \if\edition\racketEd
  21052. \begin{lstlisting}
  21053. ((Integer -> Integer) (Vector Integer Integer)
  21054. -> (Vector Integer Integer))
  21055. \end{lstlisting}
  21056. \fi
  21057. \if\edition\pythonEd
  21058. \begin{lstlisting}
  21059. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21060. \end{lstlisting}
  21061. \fi
  21062. %
  21063. After erasure, the type of \code{map} is
  21064. %
  21065. \if\edition\racketEd
  21066. \begin{lstlisting}
  21067. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21068. \end{lstlisting}
  21069. \fi
  21070. \if\edition\pythonEd
  21071. \begin{lstlisting}
  21072. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21073. \end{lstlisting}
  21074. \fi
  21075. %
  21076. but we need to convert it to the instantiated type. This is easy to
  21077. do in the language \LangCast{} with a single \code{cast}. In the
  21078. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21079. \code{map} has been compiled to a \code{cast} from the type of
  21080. \code{map} to the instantiated type. The source and the target type of a
  21081. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21082. the case because both the source and target are obtained from the same
  21083. generic type of \code{map}, replacing the type parameters with
  21084. \CANYTY{} in the former and with the deduced type arguments in the
  21085. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21086. To implement the \code{erase\_types} pass, we first recommend defining
  21087. a recursive function that translates types, named
  21088. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21089. follows.
  21090. %
  21091. \if\edition\racketEd
  21092. \begin{lstlisting}
  21093. |$T$|
  21094. |$\Rightarrow$|
  21095. Any
  21096. \end{lstlisting}
  21097. \fi
  21098. \if\edition\pythonEd
  21099. \begin{lstlisting}
  21100. GenericVar(|$T$|)
  21101. |$\Rightarrow$|
  21102. Any
  21103. \end{lstlisting}
  21104. \fi
  21105. %
  21106. \noindent The \code{erase\_type} function also removes the generic
  21107. \code{All} types.
  21108. %
  21109. \if\edition\racketEd
  21110. \begin{lstlisting}
  21111. (All |$xs$| |$T_1$|)
  21112. |$\Rightarrow$|
  21113. |$T'_1$|
  21114. \end{lstlisting}
  21115. \fi
  21116. \if\edition\pythonEd
  21117. \begin{lstlisting}
  21118. AllType(|$xs$|, |$T_1$|)
  21119. |$\Rightarrow$|
  21120. |$T'_1$|
  21121. \end{lstlisting}
  21122. \fi
  21123. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21124. %
  21125. In this compiler pass, apply the \code{erase\_type} function to all
  21126. the type annotations in the program.
  21127. Regarding the translation of expressions, the case for \code{Inst} is
  21128. the interesting one. We translate it into a \code{Cast}, as shown
  21129. next.
  21130. The type of the subexpression $e$ is a generic type of the form
  21131. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  21132. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  21133. cast is the erasure of $T$, the type $T_s$.
  21134. %
  21135. \if\edition\racketEd
  21136. %
  21137. The target type $T_t$ is the result of substituting the argument types
  21138. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21139. erasure.
  21140. %
  21141. \begin{lstlisting}
  21142. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21143. |$\Rightarrow$|
  21144. (Cast |$e'$| |$T_s$| |$T_t$|)
  21145. \end{lstlisting}
  21146. %
  21147. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21148. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21149. \fi
  21150. \if\edition\pythonEd
  21151. %
  21152. The target type $T_t$ is the result of substituting the deduced
  21153. argument types $d$ in $T$ followed by doing type erasure.
  21154. %
  21155. \begin{lstlisting}
  21156. Inst(|$e$|, |$d$|)
  21157. |$\Rightarrow$|
  21158. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21159. \end{lstlisting}
  21160. %
  21161. where
  21162. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21163. \fi
  21164. Finally, each generic function is translated to a regular
  21165. function in which type erasure has been applied to all the type
  21166. annotations and the body.
  21167. %% \begin{lstlisting}
  21168. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21169. %% |$\Rightarrow$|
  21170. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21171. %% \end{lstlisting}
  21172. \begin{exercise}\normalfont\normalsize
  21173. Implement a compiler for the polymorphic language \LangPoly{} by
  21174. extending and adapting your compiler for \LangGrad{}. Create six new
  21175. test programs that use polymorphic functions. Some of them should
  21176. make use of first-class generics.
  21177. \end{exercise}
  21178. \begin{figure}[tbp]
  21179. \begin{tcolorbox}[colback=white]
  21180. \if\edition\racketEd
  21181. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21182. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21183. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21184. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21185. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21186. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21187. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21188. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21189. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21190. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21191. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21192. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21193. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21194. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21195. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21196. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21197. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21198. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21199. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21200. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21201. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21202. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21203. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21204. \path[->,bend left=15] (Lpoly) edge [above] node
  21205. {\ttfamily\footnotesize resolve} (Lpolyp);
  21206. \path[->,bend left=15] (Lpolyp) edge [above] node
  21207. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21208. \path[->,bend left=15] (Lgradualp) edge [above] node
  21209. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21210. \path[->,bend left=15] (Llambdapp) edge [left] node
  21211. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21212. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21213. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21214. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21215. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21216. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21217. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21218. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21219. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21220. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21221. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21222. \path[->,bend left=15] (F1-1) edge [above] node
  21223. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21224. \path[->,bend left=15] (F1-2) edge [above] node
  21225. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21226. \path[->,bend left=15] (F1-3) edge [left] node
  21227. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21228. \path[->,bend left=15] (F1-4) edge [below] node
  21229. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21230. \path[->,bend right=15] (F1-5) edge [above] node
  21231. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21232. \path[->,bend right=15] (F1-6) edge [above] node
  21233. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21234. \path[->,bend right=15] (C3-2) edge [right] node
  21235. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21236. \path[->,bend right=15] (x86-2) edge [right] node
  21237. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21238. \path[->,bend right=15] (x86-2-1) edge [below] node
  21239. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21240. \path[->,bend right=15] (x86-2-2) edge [right] node
  21241. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21242. \path[->,bend left=15] (x86-3) edge [above] node
  21243. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21244. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21245. \end{tikzpicture}
  21246. \fi
  21247. \if\edition\pythonEd
  21248. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21249. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21250. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21251. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21252. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21253. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21254. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21255. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21256. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21257. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21258. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21259. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21260. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21261. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21262. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21263. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21264. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21265. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21266. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21267. \path[->,bend left=15] (Lgradual) edge [above] node
  21268. {\ttfamily\footnotesize shrink} (Lgradual2);
  21269. \path[->,bend left=15] (Lgradual2) edge [above] node
  21270. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21271. \path[->,bend left=15] (Lgradual3) edge [above] node
  21272. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21273. \path[->,bend left=15] (Lgradual4) edge [left] node
  21274. {\ttfamily\footnotesize resolve} (Lgradualr);
  21275. \path[->,bend left=15] (Lgradualr) edge [below] node
  21276. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21277. \path[->,bend right=15] (Llambdapp) edge [above] node
  21278. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21279. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21280. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21281. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21282. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21283. \path[->,bend right=15] (F1-1) edge [below] node
  21284. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21285. \path[->,bend right=15] (F1-2) edge [below] node
  21286. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21287. \path[->,bend left=15] (F1-3) edge [above] node
  21288. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21289. \path[->,bend left=15] (F1-5) edge [left] node
  21290. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21291. \path[->,bend left=5] (F1-6) edge [below] node
  21292. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21293. \path[->,bend right=15] (C3-2) edge [right] node
  21294. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21295. \path[->,bend right=15] (x86-2) edge [below] node
  21296. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21297. \path[->,bend right=15] (x86-3) edge [below] node
  21298. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21299. \path[->,bend left=15] (x86-4) edge [above] node
  21300. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21301. \end{tikzpicture}
  21302. \fi
  21303. \end{tcolorbox}
  21304. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21305. \label{fig:Lpoly-passes}
  21306. \end{figure}
  21307. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21308. needed to compile \LangPoly{}.
  21309. % TODO: challenge problem: specialization of instantiations
  21310. % Further Reading
  21311. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21312. \clearpage
  21313. \appendix
  21314. \chapter{Appendix}
  21315. \setcounter{footnote}{0}
  21316. \if\edition\racketEd
  21317. \section{Interpreters}
  21318. \label{appendix:interp}
  21319. \index{subject}{interpreter}
  21320. We provide interpreters for each of the source languages \LangInt{},
  21321. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21322. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21323. intermediate languages \LangCVar{} and \LangCIf{} are in
  21324. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21325. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21326. \key{interp.rkt} file.
  21327. \section{Utility Functions}
  21328. \label{appendix:utilities}
  21329. The utility functions described in this section are in the
  21330. \key{utilities.rkt} file of the support code.
  21331. \paragraph{\code{interp-tests}}
  21332. This function runs the compiler passes and the interpreters on each of
  21333. the specified tests to check whether each pass is correct. The
  21334. \key{interp-tests} function has the following parameters:
  21335. \begin{description}
  21336. \item[name (a string)] A name to identify the compiler,
  21337. \item[typechecker] A function of exactly one argument that either
  21338. raises an error using the \code{error} function when it encounters a
  21339. type error or returns \code{\#f} when it encounters a type
  21340. error. If there is no type error, the type checker returns the
  21341. program.
  21342. \item[passes] A list with one entry per pass. An entry is a list
  21343. consisting of four things:
  21344. \begin{enumerate}
  21345. \item a string giving the name of the pass;
  21346. \item the function that implements the pass (a translator from AST
  21347. to AST);
  21348. \item a function that implements the interpreter (a function from
  21349. AST to result value) for the output language; and,
  21350. \item a type checker for the output language. Type checkers for
  21351. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21352. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21353. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21354. type checker entry is optional. The support code does not provide
  21355. type checkers for the x86 languages.
  21356. \end{enumerate}
  21357. \item[source-interp] An interpreter for the source language. The
  21358. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21359. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21360. \item[tests] A list of test numbers that specifies which tests to
  21361. run (explained next).
  21362. \end{description}
  21363. %
  21364. The \key{interp-tests} function assumes that the subdirectory
  21365. \key{tests} has a collection of Racket programs whose names all start
  21366. with the family name, followed by an underscore and then the test
  21367. number, and ending with the file extension \key{.rkt}. Also, for each test
  21368. program that calls \code{read} one or more times, there is a file with
  21369. the same name except that the file extension is \key{.in}, which
  21370. provides the input for the Racket program. If the test program is
  21371. expected to fail type checking, then there should be an empty file of
  21372. the same name with extension \key{.tyerr}.
  21373. \paragraph{\code{compiler-tests}}
  21374. This function runs the compiler passes to generate x86 (a \key{.s}
  21375. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21376. It runs the machine code and checks that the output is $42$. The
  21377. parameters to the \code{compiler-tests} function are similar to those
  21378. of the \code{interp-tests} function, and they consist of
  21379. \begin{itemize}
  21380. \item a compiler name (a string),
  21381. \item a type checker,
  21382. \item description of the passes,
  21383. \item name of a test-family, and
  21384. \item a list of test numbers.
  21385. \end{itemize}
  21386. \paragraph{\code{compile-file}}
  21387. This function takes a description of the compiler passes (see the
  21388. comment for \key{interp-tests}) and returns a function that, given a
  21389. program file name (a string ending in \key{.rkt}), applies all the
  21390. passes and writes the output to a file whose name is the same as the
  21391. program file name with extension \key{.rkt} replaced by \key{.s}.
  21392. \paragraph{\code{read-program}}
  21393. This function takes a file path and parses that file (it must be a
  21394. Racket program) into an abstract syntax tree.
  21395. \paragraph{\code{parse-program}}
  21396. This function takes an S-expression representation of an abstract
  21397. syntax tree and converts it into the struct-based representation.
  21398. \paragraph{\code{assert}}
  21399. This function takes two parameters, a string (\code{msg}) and Boolean
  21400. (\code{bool}), and displays the message \key{msg} if the Boolean
  21401. \key{bool} is false.
  21402. \paragraph{\code{lookup}}
  21403. % remove discussion of lookup? -Jeremy
  21404. This function takes a key and an alist and returns the first value that is
  21405. associated with the given key, if there is one. If not, an error is
  21406. triggered. The alist may contain both immutable pairs (built with
  21407. \key{cons}) and mutable pairs (built with \key{mcons}).
  21408. %The \key{map2} function ...
  21409. \fi %\racketEd
  21410. \section{x86 Instruction Set Quick Reference}
  21411. \label{sec:x86-quick-reference}
  21412. \index{subject}{x86}
  21413. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21414. do. We write $A \to B$ to mean that the value of $A$ is written into
  21415. location $B$. Address offsets are given in bytes. The instruction
  21416. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21417. registers (such as \code{\%rax}), or memory references (such as
  21418. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21419. reference per instruction. Other operands must be immediates or
  21420. registers.
  21421. \begin{table}[tbp]
  21422. \centering
  21423. \begin{tabular}{l|l}
  21424. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21425. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21426. \texttt{negq} $A$ & $- A \to A$ \\
  21427. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21428. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21429. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21430. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21431. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21432. \texttt{retq} & Pops the return address and jumps to it \\
  21433. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21434. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21435. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21436. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21437. be an immediate) \\
  21438. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21439. matches the condition code of the instruction; otherwise go to the
  21440. next instructions. The condition codes are \key{e} for \emph{equal},
  21441. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21442. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21443. \texttt{jl} $L$ & \\
  21444. \texttt{jle} $L$ & \\
  21445. \texttt{jg} $L$ & \\
  21446. \texttt{jge} $L$ & \\
  21447. \texttt{jmp} $L$ & Jump to label $L$ \\
  21448. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21449. \texttt{movzbq} $A$, $B$ &
  21450. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21451. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21452. and the extra bytes of $B$ are set to zero.} \\
  21453. & \\
  21454. & \\
  21455. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21456. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21457. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21458. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21459. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21460. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21461. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21462. description of the condition codes. $A$ must be a single byte register
  21463. (e.g., \texttt{al} or \texttt{cl}).} \\
  21464. \texttt{setl} $A$ & \\
  21465. \texttt{setle} $A$ & \\
  21466. \texttt{setg} $A$ & \\
  21467. \texttt{setge} $A$ &
  21468. \end{tabular}
  21469. \vspace{5pt}
  21470. \caption{Quick reference for the x86 instructions used in this book.}
  21471. \label{tab:x86-instr}
  21472. \end{table}
  21473. %% \if\edition\racketEd
  21474. %% \cleardoublepage
  21475. %% \section{Concrete Syntax for Intermediate Languages}
  21476. %% The concrete syntax of \LangAny{} is defined in
  21477. %% figure~\ref{fig:Lany-concrete-syntax}.
  21478. %% \begin{figure}[tp]
  21479. %% \centering
  21480. %% \fbox{
  21481. %% \begin{minipage}{0.97\textwidth}\small
  21482. %% \[
  21483. %% \begin{array}{lcl}
  21484. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  21485. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  21486. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  21487. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  21488. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  21489. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  21490. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  21491. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  21492. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  21493. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  21494. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  21495. %% \MID \LP\key{void?}\;\Exp\RP \\
  21496. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  21497. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  21498. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  21499. %% \end{array}
  21500. %% \]
  21501. %% \end{minipage}
  21502. %% }
  21503. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  21504. %% (figure~\ref{fig:Llam-syntax}).}
  21505. %% \label{fig:Lany-concrete-syntax}
  21506. %% \end{figure}
  21507. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  21508. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  21509. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  21510. %% \ref{fig:c3-concrete-syntax}, respectively.
  21511. %% \begin{figure}[tbp]
  21512. %% \fbox{
  21513. %% \begin{minipage}{0.96\textwidth}
  21514. %% \small
  21515. %% \[
  21516. %% \begin{array}{lcl}
  21517. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  21518. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21519. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  21520. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  21521. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  21522. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  21523. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  21524. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  21525. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  21526. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  21527. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  21528. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  21529. %% \end{array}
  21530. %% \]
  21531. %% \end{minipage}
  21532. %% }
  21533. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  21534. %% \label{fig:c2-concrete-syntax}
  21535. %% \end{figure}
  21536. %% \begin{figure}[tp]
  21537. %% \fbox{
  21538. %% \begin{minipage}{0.96\textwidth}
  21539. %% \small
  21540. %% \[
  21541. %% \begin{array}{lcl}
  21542. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  21543. %% \\
  21544. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21545. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  21546. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  21547. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  21548. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  21549. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  21550. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  21551. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  21552. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  21553. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  21554. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  21555. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  21556. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  21557. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  21558. %% \LangCFunM{} & ::= & \Def\ldots
  21559. %% \end{array}
  21560. %% \]
  21561. %% \end{minipage}
  21562. %% }
  21563. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  21564. %% \label{fig:c3-concrete-syntax}
  21565. %% \end{figure}
  21566. %% \fi % racketEd
  21567. \backmatter
  21568. \addtocontents{toc}{\vspace{11pt}}
  21569. %% \addtocontents{toc}{\vspace{11pt}}
  21570. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  21571. \nocite{*}\let\bibname\refname
  21572. \addcontentsline{toc}{fmbm}{\refname}
  21573. \printbibliography
  21574. %\printindex{authors}{Author Index}
  21575. \printindex{subject}{Index}
  21576. \end{document}
  21577. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21578. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21579. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21580. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21581. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21582. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21583. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21584. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21585. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21586. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21587. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21588. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21589. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21590. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21591. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21592. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21593. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21594. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21595. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21596. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21597. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21598. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21599. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21600. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21601. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21602. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21603. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21604. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21605. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21606. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21607. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21608. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21609. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21610. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21611. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21612. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21613. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21614. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21615. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21616. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21617. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21618. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21619. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21620. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21621. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21622. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21623. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21624. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21625. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21626. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21627. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21628. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21629. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21630. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21631. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21632. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21633. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21634. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21635. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21636. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21637. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21638. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21639. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21640. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21641. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21642. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21643. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21644. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21645. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21646. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21647. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21648. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21649. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21650. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21651. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21652. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21653. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21654. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21655. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21656. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith
  21657. % LocalWords: racketEd subparts subpart nonterminal nonterminals
  21658. % LocalWords: pseudocode underapproximation underapproximations
  21659. % LocalWords: semilattices overapproximate incrementing
  21660. % LocalWords: multilanguage