book.tex 820 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571
  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~\citep{DeRemer69,Anderson73}.
  3757. A parser framework such as Lark takes in a specification of the
  3758. concrete syntax and an 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. Also, some algorithms, such
  3763. as LALR(1) place restrictions on the grammars they can handle, in
  3764. which case it helps to know the algorithm when trying to decipher the
  3765. error messages.
  3766. The process of parsing is traditionally subdivided into two phases:
  3767. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3768. analysis} (also called parsing). The lexical analysis phase
  3769. translates the sequence of characters into a sequence of
  3770. \emph{tokens}, that is, words consisting of several characters. The
  3771. parsing phase organizes the tokens into a \emph{parse tree} that
  3772. captures how the tokens were matched by rules in the grammar of the
  3773. language. The reason for the subdivision into two phases is to enable
  3774. the use of a faster but less powerful algorithm for lexical analysis
  3775. and the use of a slower but more powerful algorithm for parsing.
  3776. %
  3777. %% Likewise, parser generators typical come in pairs, with separate
  3778. %% generators for the lexical analyzer (or lexer for short) and for the
  3779. %% parser. A particularly influential pair of generators were
  3780. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3781. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3782. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3783. %% Compiler Compiler.
  3784. %
  3785. The Lark parser framework that we use in this chapter includes both
  3786. lexical analyzers and parsers. The next section discusses lexical
  3787. analysis and the remainder of the chapter discusses parsing.
  3788. \section{Lexical Analysis and Regular Expressions}
  3789. \label{sec:lex}
  3790. The lexical analyzers produced by Lark turn a sequence of characters
  3791. (a string) into a sequence of token objects. For example, a Lark
  3792. generated lexer for \LangInt{} converts the string
  3793. \begin{lstlisting}
  3794. 'print(1 + 3)'
  3795. \end{lstlisting}
  3796. \noindent into the following sequence of token objects
  3797. \begin{center}
  3798. \begin{minipage}{0.95\textwidth}
  3799. \begin{lstlisting}
  3800. Token('PRINT', 'print')
  3801. Token('LPAR', '(')
  3802. Token('INT', '1')
  3803. Token('PLUS', '+')
  3804. Token('INT', '3')
  3805. Token('RPAR', ')')
  3806. Token('NEWLINE', '\n')
  3807. \end{lstlisting}
  3808. \end{minipage}
  3809. \end{center}
  3810. Each token includes a field for its \code{type}, such as \code{'INT'},
  3811. and a field for its \code{value}, such as \code{'1'}.
  3812. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3813. specification language for Lark's lexical analysis generator is one
  3814. regular expression for each type of token. The term \emph{regular}
  3815. comes from the term \emph{regular languages}, which are the languages
  3816. that can be recognized by a finite automata. A \emph{regular
  3817. expression} is a pattern formed of the following core
  3818. elements:\index{subject}{regular expression}\footnote{Regular
  3819. expressions traditionally include the empty regular expression that
  3820. matches any zero-length part of a string, but Lark does not support
  3821. the empty regular expression.}
  3822. \begin{itemize}
  3823. \item A single character $c$ is a regular expression and it only
  3824. matches itself. For example, the regular expression \code{a} only
  3825. matches with the string \code{'a'}.
  3826. \item Two regular expressions separated by a vertical bar $R_1 \mid
  3827. R_2$ form a regular expression that matches any string that matches
  3828. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3829. matches the string \code{'a'} and the string \code{'c'}.
  3830. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3831. expression that matches any string that can be formed by
  3832. concatenating two strings, where the first matches $R_1$
  3833. and the second matches $R_2$. For example, the regular expression
  3834. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3835. (Parentheses can be used to control the grouping of operators within
  3836. a regular expression.)
  3837. \item A regular expression followed by an asterisks $R*$ (called
  3838. Kleene closure) is a regular expression that matches any string that
  3839. can be formed by concatenating zero or more strings that each match
  3840. the regular expression $R$. For example, the regular expression
  3841. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} and
  3842. \code{''}, but not \code{'abc'}.
  3843. \end{itemize}
  3844. For our convenience, Lark also accepts an extended set of regular
  3845. expressions that are automatically translated into the core regular
  3846. expressions.
  3847. \begin{itemize}
  3848. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3849. c_n]$ is a regular expression that matches any one of the
  3850. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3851. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3852. \item A range of characters enclosed in square brackets $[c_1-c_2]$ is
  3853. a regular expression that matches any character between $c_1$ and
  3854. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3855. letter in the alphabet.
  3856. \item A regular expression followed by the plus symbol $R+$
  3857. is a regular expression that matches any string that can
  3858. be formed by concatenating one or more strings that each match $R$.
  3859. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3860. matches \code{'b'} and \code{'bzca'}.
  3861. \item A regular expression followed by a question mark $R?$
  3862. is a regular expression that matches any string that either
  3863. matches $R$ or that is the empty string.
  3864. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3865. \item A string, such as \code{"hello"}, which matches itself,
  3866. that is, \code{'hello'}.
  3867. \end{itemize}
  3868. In a Lark grammar file, specify a name for each type of token followed
  3869. by a colon and then a regular expression surrounded by \code{/}
  3870. characters. For example, the \code{DIGIT}, \code{INT}, and
  3871. \code{NEWLINE} types of tokens are specified in the following way.
  3872. \begin{center}
  3873. \begin{minipage}{0.95\textwidth}
  3874. \begin{lstlisting}
  3875. DIGIT: /[0-9]/
  3876. INT: "-"? DIGIT+
  3877. NEWLINE: (/\r/? /\n/)+
  3878. \end{lstlisting}
  3879. \end{minipage}
  3880. \end{center}
  3881. \noindent In Lark, the regular expression operators can be used both
  3882. inside a regular expression, that is, between the \code{/} characters,
  3883. and they can be used to combine regular expressions, outside the
  3884. \code{/} characters.
  3885. \section{Grammars and Parse Trees}
  3886. \label{sec:CFG}
  3887. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3888. specify the abstract syntax of a language. We now take a closer look
  3889. at using grammar rules to specify the concrete syntax. Recall that
  3890. each rule has a left-hand side and a right-hand side. However, for
  3891. concrete syntax, each right-hand side expresses a pattern for a
  3892. string, instead of a patter for an abstract syntax tree. In
  3893. particular, each right-hand side is a sequence of
  3894. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3895. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3896. a string. The nonterminals play the same role as in the abstract
  3897. syntax, defining categories of syntax. The nonterminals of a grammar
  3898. include the tokens defined in the lexer and all the nonterminals
  3899. defined by the grammar rules.
  3900. As an example, let us take a closer look at the concrete syntax of the
  3901. \LangInt{} language, repeated here.
  3902. \[
  3903. \begin{array}{l}
  3904. \LintGrammarPython \\
  3905. \begin{array}{rcl}
  3906. \LangInt{} &::=& \Stmt^{*}
  3907. \end{array}
  3908. \end{array}
  3909. \]
  3910. The Lark syntax for grammar rules differs slightly from the variant of
  3911. BNF that we use in this book. In particular, the notation $::=$ is
  3912. replaced by a single colon and the use of typewriter font for string
  3913. literals is replaced by quotation marks. The following grammar serves
  3914. as a first draft of a Lark grammar for \LangInt{}.
  3915. \begin{center}
  3916. \begin{minipage}{0.95\textwidth}
  3917. \begin{lstlisting}[escapechar=$]
  3918. exp: INT
  3919. | "input_int" "(" ")"
  3920. | "-" exp
  3921. | exp "+" exp
  3922. | exp "-" exp
  3923. | "(" exp ")"
  3924. stmt_list:
  3925. | stmt NEWLINE stmt_list
  3926. lang_int: stmt_list
  3927. \end{lstlisting}
  3928. \end{minipage}
  3929. \end{center}
  3930. Let us begin by discussing the rule \code{exp: INT}. In
  3931. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  3932. nonterminal with an English sentence. Here we specify \code{INT} more
  3933. formally using a type of token \code{INT} and its regular expression
  3934. \code{"-"? DIGIT+}. Thus, the rule \code{exp: INT} says that if the
  3935. lexer matches a string to \code{INT}, then the parser also categorizes
  3936. the string as an \code{exp}.
  3937. The rule \code{exp: exp "+" exp} says that any string that matches
  3938. \code{exp}, followed by the \code{+} character, followed by another
  3939. string that matches \code{exp}, is itself an \code{exp}. For example,
  3940. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  3941. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  3942. the rule for addition applies to categorize \code{'1+3'} as an
  3943. \Exp{}. We can visualize the application of grammar rules to parse a
  3944. string using a \emph{parse tree}\index{subject}{parse tree}. Each
  3945. internal node in the tree is an application of a grammar rule and is
  3946. labeled with its left-hand side nonterminal. Each leaf node is a
  3947. substring of the input program. The parse tree for \code{'1+3'} is
  3948. shown in figure~\ref{fig:simple-parse-tree}.
  3949. \begin{figure}[tbp]
  3950. \begin{tcolorbox}[colback=white]
  3951. \centering
  3952. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  3953. \end{tcolorbox}
  3954. \caption{The parse tree for \code{'1+3'}.}
  3955. \label{fig:simple-parse-tree}
  3956. \end{figure}
  3957. The result of parsing \code{'1+3'} with this Lark grammar is the
  3958. following parse tree as represented by \code{Tree} and \code{Token}
  3959. objects.
  3960. \begin{lstlisting}
  3961. Tree('lang_int',
  3962. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  3963. Tree('exp', [Token('INT', '3')])])]),
  3964. Token('NEWLINE', '\n')])
  3965. \end{lstlisting}
  3966. The nodes that come from the lexer are \code{Token} objects whereas
  3967. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  3968. object has a \code{data} field containing the name of the nonterminal
  3969. for the grammar rule that was applied. Each \code{Tree} object also
  3970. has a \code{children} field that is a list containing trees and/or
  3971. tokens. Note that Lark does not produce nodes for string literals in
  3972. the grammar. For example, the \code{Tree} node for the addition
  3973. expression has only two children for the two integers but is missing
  3974. its middle child for the \code{"+"} terminal. This would be
  3975. problematic except that Lark provides a mechanism for customizing the
  3976. \code{data} field of each \code{Tree} node based on which rule was
  3977. applied. Next to each alternative in a grammar rule, write \code{->}
  3978. followed by a string that you would like to appear in the \code{data}
  3979. field. The following is a second draft of a Lark grammar for
  3980. \LangInt{}, this time with more specific labels on the \code{Tree}
  3981. nodes.
  3982. \begin{center}
  3983. \begin{minipage}{0.95\textwidth}
  3984. \begin{lstlisting}[escapechar=$]
  3985. exp: INT -> int
  3986. | "input_int" "(" ")" -> input_int
  3987. | "-" exp -> usub
  3988. | exp "+" exp -> add
  3989. | exp "-" exp -> sub
  3990. | "(" exp ")" -> paren
  3991. stmt: "print" "(" exp ")" -> print
  3992. | exp -> expr
  3993. stmt_list: -> empty_stmt
  3994. | stmt NEWLINE stmt_list -> add_stmt
  3995. lang_int: stmt_list -> module
  3996. \end{lstlisting}
  3997. \end{minipage}
  3998. \end{center}
  3999. Here is the resulting parse tree.
  4000. \begin{lstlisting}
  4001. Tree('module',
  4002. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4003. Tree('int', [Token('INT', '3')])])]),
  4004. Token('NEWLINE', '\n')])
  4005. \end{lstlisting}
  4006. \section{Ambiguous Grammars}
  4007. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4008. can be parsed in more than one way. For example, consider the string
  4009. \code{'1-2+3'}. This string can parsed in two different ways using
  4010. our draft grammar, resulting in the two parse trees shown in
  4011. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4012. interpreting the second parse tree would yield \code{-4} even through
  4013. the correct answer is \code{2}.
  4014. \begin{figure}[tbp]
  4015. \begin{tcolorbox}[colback=white]
  4016. \centering
  4017. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4018. \end{tcolorbox}
  4019. \caption{The two parse trees for \code{'1-2+3'}.}
  4020. \label{fig:ambig-parse-tree}
  4021. \end{figure}
  4022. To deal with this problem we can change the grammar by categorizing
  4023. the syntax in a more fine grained fashion. In this case we want to
  4024. disallow the application of the rule \code{exp: exp "-" exp} when the
  4025. child on the right is an addition. To do this we can replace the
  4026. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4027. the expressions except for addition, as in the following.
  4028. \begin{center}
  4029. \begin{minipage}{0.95\textwidth}
  4030. \begin{lstlisting}[escapechar=$]
  4031. exp: exp "-" exp_no_add -> sub
  4032. | exp "+" exp -> add
  4033. | exp_no_add
  4034. exp_no_add: INT -> int
  4035. | "input_int" "(" ")" -> input_int
  4036. | "-" exp -> usub
  4037. | exp "-" exp_no_add -> sub
  4038. | "(" exp ")" -> paren
  4039. \end{lstlisting}
  4040. \end{minipage}
  4041. \end{center}
  4042. However, there remains some ambiguity in the grammar. For example, the
  4043. string \code{'1-2-3'} can still be parsed in two different ways, as
  4044. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4045. to say, subtraction is left associative. Likewise, addition in Python
  4046. is left associative. We also need to consider the interaction of unary
  4047. subtraction with both addition and subtraction. How should we parse
  4048. \code{'-1+2'}? Unary subtraction has higher
  4049. \emph{precendence}\index{subject}{precedence} than addition and
  4050. subtraction, so \code{'-1+2'} should parse the same as \code{'(-1)+2'}
  4051. and not \code{'-(1+2)'}. The grammar in
  4052. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4053. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4054. all the other expressions, and uses \code{exp\_hi} for the second
  4055. child in the rules for addition and subtraction. Furthermore, unary
  4056. subtraction uses \code{exp\_hi} for its child.
  4057. For languages with more operators and more precedence levels, one must
  4058. refine the \code{exp} nonterminal into several nonterminals, one for
  4059. each precedence level.
  4060. \begin{figure}[tbp]
  4061. \begin{tcolorbox}[colback=white]
  4062. \centering
  4063. \begin{lstlisting}[escapechar=$]
  4064. exp: exp "+" exp_hi -> add
  4065. | exp "-" exp_hi -> sub
  4066. | exp_hi
  4067. exp_hi: INT -> int
  4068. | "input_int" "(" ")" -> input_int
  4069. | "-" exp_hi -> usub
  4070. | "(" exp ")" -> paren
  4071. stmt: "print" "(" exp ")" -> print
  4072. | exp -> expr
  4073. stmt_list: -> empty_stmt
  4074. | stmt NEWLINE stmt_list -> add_stmt
  4075. lang_int: stmt_list -> module
  4076. \end{lstlisting}
  4077. \end{tcolorbox}
  4078. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4079. \label{fig:Lint-lark-grammar}
  4080. \end{figure}
  4081. \section{From Parse Trees to Abstract Syntax Trees}
  4082. As we have seen, the output of a Lark parser is a parse tree, that is,
  4083. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4084. step is to convert the parse tree to an abstract syntax tree. This can
  4085. be accomplished with a recursive function that inspects the
  4086. \code{data} field of each node and then constructs the corresponding
  4087. AST node, using recursion to handle its children. The following is an
  4088. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4089. \begin{center}
  4090. \begin{minipage}{0.95\textwidth}
  4091. \begin{lstlisting}
  4092. def parse_tree_to_ast(e):
  4093. if e.data == 'int':
  4094. return Constant(int(e.children[0].value))
  4095. elif e.data == 'input_int':
  4096. return Call(Name('input_int'), [])
  4097. elif e.data == 'add':
  4098. e1, e2 = e.children
  4099. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4100. ...
  4101. else:
  4102. raise Exception('unhandled parse tree', e)
  4103. \end{lstlisting}
  4104. \end{minipage}
  4105. \end{center}
  4106. \begin{exercise}
  4107. \normalfont\normalsize
  4108. %
  4109. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4110. default parsing algorithm (Earley) with the \code{ambiguity} option
  4111. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4112. output will include multiple parse trees which will indicate to you
  4113. that there is a problem with your grammar. Your parser should ignore
  4114. white space so we recommend using Lark's \code{\%ignore} directive
  4115. as follows.
  4116. \begin{lstlisting}
  4117. WS: /[ \t\f\r\n]/+
  4118. %ignore WS
  4119. \end{lstlisting}
  4120. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4121. Lark-generated parser instead of using the \code{parse} function from
  4122. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4123. programs that you have created and create four additional programs
  4124. that would reveal ambiguities in your grammar.
  4125. \end{exercise}
  4126. \section{The Earley Algorithm}
  4127. \label{sec:earley}
  4128. In this section we discuss the parsing algorithm of
  4129. \citet{Earley:1970ly}, which is the default algorithm used by Lark.
  4130. The algorithm is powerful in that it can handle any context-free
  4131. grammar, which makes it easy to use. However, it is not the most
  4132. efficient parsing algorithm: it is $O(n^3)$ for ambiguous grammars and
  4133. $O(n^2)$ for unambiguous grammars, where $n$ is the number of tokens
  4134. in the input string~\citep{Hopcroft06:_automata}. In
  4135. section~\ref{sec:lalr} we learn about the LALR(1) algorithm, which is
  4136. more efficient but cannot handle all context-free grammars.
  4137. The Earley algorithm can be viewed as an interpreter; it treats the
  4138. grammar as the program being interpreted and it treats the concrete
  4139. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4140. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4141. keep track of its progress and to memoize its results. The chart is an
  4142. array with one slot for each position in the input string, where
  4143. position $0$ is before the first character and position $n$ is
  4144. immediately after the last character. So the array has length $n+1$
  4145. for an input string of length $n$. Each slot in the chart contains a
  4146. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4147. with a period indicating how much of its right-hand side has already
  4148. been parsed. For example, the dotted rule
  4149. \begin{lstlisting}
  4150. exp: exp "+" . exp_hi
  4151. \end{lstlisting}
  4152. represents a partial parse that has matched an \code{exp} followed by
  4153. \code{+}, but has not yet parsed an \code{exp} to the right of
  4154. \code{+}.
  4155. %
  4156. The Earley algorithm starts with an initialization phase, and then
  4157. repeats three actions---prediction, scanning, and completion---for as
  4158. long as opportunities arise. We demonstrate the Earley algorithm on a
  4159. running example, parsing the following program:
  4160. \begin{lstlisting}
  4161. print(1 + 3)
  4162. \end{lstlisting}
  4163. The algorithm's initialization phase creates dotted rules for all the
  4164. grammar rules whose left-hand side is the start symbol and places them
  4165. in slot $0$ of the chart. We also record the starting position of the
  4166. dotted rule in parentheses on the right. For example, given the
  4167. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4168. \begin{lstlisting}
  4169. lang_int: . stmt_list (0)
  4170. \end{lstlisting}
  4171. in slot $0$ of the chart. The algorithm then proceeds to with
  4172. \emph{prediction} actions in which it adds more dotted rules to the
  4173. chart based on which nonterminals come immediately after a period. In
  4174. the above, the nonterminal \code{stmt\_list} appears after a period,
  4175. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4176. period at the beginning of their right-hand sides, as follows:
  4177. \begin{lstlisting}
  4178. stmt_list: . (0)
  4179. stmt_list: . stmt NEWLINE stmt_list (0)
  4180. \end{lstlisting}
  4181. We continue to perform prediction actions as more opportunities
  4182. arise. For example, the \code{stmt} nonterminal now appears after a
  4183. period, so we add all the rules for \code{stmt}.
  4184. \begin{lstlisting}
  4185. stmt: . "print" "(" exp ")" (0)
  4186. stmt: . exp (0)
  4187. \end{lstlisting}
  4188. This reveals yet more opportunities for prediction, so we add the grammar
  4189. rules for \code{exp} and \code{exp\_hi}.
  4190. \begin{lstlisting}[escapechar=$]
  4191. exp: . exp "+" exp_hi (0)
  4192. exp: . exp "-" exp_hi (0)
  4193. exp: . exp_hi (0)
  4194. exp_hi: . INT (0)
  4195. exp_hi: . "input_int" "(" ")" (0)
  4196. exp_hi: . "-" exp_hi (0)
  4197. exp_hi: . "(" exp ")" (0)
  4198. \end{lstlisting}
  4199. We have exhausted the opportunities for prediction, so the algorithm
  4200. proceeds to \emph{scanning}, in which we inspect the next input token
  4201. and look for a dotted rule at the current position that has a matching
  4202. terminal following the period. In our running example, the first input
  4203. token is \code{"print"} so we identify the rule in slot $0$ of
  4204. the chart whose dot comes before \code{"print"}:
  4205. \begin{lstlisting}
  4206. stmt: . "print" "(" exp ")" (0)
  4207. \end{lstlisting}
  4208. and add the following rule to slot $1$ of the chart, with the period
  4209. moved forward past \code{"print"}.
  4210. \begin{lstlisting}
  4211. stmt: "print" . "(" exp ")" (0)
  4212. \end{lstlisting}
  4213. If the new dotted rule had a nonterminal after the period, we would
  4214. need to carry out a prediction action, adding more dotted rules into
  4215. slot $1$. That is not the case, so we continue scanning. The next
  4216. input token is \code{"("}, so we add the following to slot $2$ of the
  4217. chart.
  4218. \begin{lstlisting}
  4219. stmt: "print" "(" . exp ")" (0)
  4220. \end{lstlisting}
  4221. Now we have a nonterminal after the period, so we carry out several
  4222. prediction actions, adding dotted rules for \code{exp} and
  4223. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4224. starting position $2$.
  4225. \begin{lstlisting}[escapechar=$]
  4226. exp: . exp "+" exp_hi (2)
  4227. exp: . exp "-" exp_hi (2)
  4228. exp: . exp_hi (2)
  4229. exp_hi: . INT (2)
  4230. exp_hi: . "input_int" "(" ")" (2)
  4231. exp_hi: . "-" exp_hi (2)
  4232. exp_hi: . "(" exp ")" (2)
  4233. \end{lstlisting}
  4234. With that prediction complete, we return to scanning, noting that the
  4235. next input token is \code{"1"} which the lexer parses as an
  4236. \code{INT}. There is a matching rule is slot $2$:
  4237. \begin{lstlisting}
  4238. exp_hi: . INT (2)
  4239. \end{lstlisting}
  4240. so we advance the period and put the following rule is slot $3$.
  4241. \begin{lstlisting}
  4242. exp_hi: INT . (2)
  4243. \end{lstlisting}
  4244. This brings us to \emph{completion} actions. When the period reaches
  4245. the end of a dotted rule, we recognize that the substring
  4246. has matched the nonterminal on the left-hand side of the rule, in this case
  4247. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4248. rules in slot $2$ (the starting position for the finished rule) if
  4249. period is immediately followed by \code{exp\_hi}. So we identify
  4250. \begin{lstlisting}
  4251. exp: . exp_hi (2)
  4252. \end{lstlisting}
  4253. and add the following dotted rule to slot $3$
  4254. \begin{lstlisting}
  4255. exp: exp_hi . (2)
  4256. \end{lstlisting}
  4257. This triggers another completion step for the nonterminal \code{exp},
  4258. adding two more dotted rules to slot $3$.
  4259. \begin{lstlisting}[escapechar=$]
  4260. exp: exp . "+" exp_hi (2)
  4261. exp: exp . "-" exp_hi (2)
  4262. \end{lstlisting}
  4263. Returning to scanning, the next input token is \code{"+"}, so
  4264. we add the following to slot $4$.
  4265. \begin{lstlisting}[escapechar=$]
  4266. exp: exp "+" . exp_hi (2)
  4267. \end{lstlisting}
  4268. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4269. the following dotted rules to slot $4$ of the chart.
  4270. \begin{lstlisting}[escapechar=$]
  4271. exp_hi: . INT (4)
  4272. exp_hi: . "input_int" "(" ")" (4)
  4273. exp_hi: . "-" exp_hi (4)
  4274. exp_hi: . "(" exp ")" (4)
  4275. \end{lstlisting}
  4276. The next input token is \code{"3"} which the lexer categorized as an
  4277. \code{INT}, so we advance the period past \code{INT} for the rules in
  4278. slot $4$, of which there is just one, and put the following in slot $5$.
  4279. \begin{lstlisting}[escapechar=$]
  4280. exp_hi: INT . (4)
  4281. \end{lstlisting}
  4282. The period at the end of the rule triggers a completion action for the
  4283. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4284. So we advance the period and put the following in slot $5$.
  4285. \begin{lstlisting}[escapechar=$]
  4286. exp: exp "+" exp_hi . (2)
  4287. \end{lstlisting}
  4288. This triggers another completion action for the rules in slot $2$ that
  4289. have a period before \code{exp}.
  4290. \begin{lstlisting}[escapechar=$]
  4291. stmt: "print" "(" exp . ")" (0)
  4292. exp: exp . "+" exp_hi (2)
  4293. exp: exp . "-" exp_hi (2)
  4294. \end{lstlisting}
  4295. We scan the next input token \code{")"}, placing the following dotted
  4296. rule in slot $6$.
  4297. \begin{lstlisting}[escapechar=$]
  4298. stmt: "print" "(" exp ")" . (0)
  4299. \end{lstlisting}
  4300. This triggers the completion of \code{stmt} in slot $0$
  4301. \begin{lstlisting}
  4302. stmt_list: stmt . NEWLINE stmt_list (0)
  4303. \end{lstlisting}
  4304. The last input token is a \code{NEWLINE}, so we advance the period
  4305. and place the new dotted rule in slot $7$.
  4306. \begin{lstlisting}
  4307. stmt_list: stmt NEWLINE . stmt_list (0)
  4308. \end{lstlisting}
  4309. We are close to the end of parsing the input!
  4310. The period is before the \code{stmt\_list} nonterminal, so we
  4311. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4312. \begin{lstlisting}
  4313. stmt_list: . (7)
  4314. stmt_list: . stmt NEWLINE stmt_list (7)
  4315. stmt: . "print" "(" exp ")" (7)
  4316. stmt: . exp (7)
  4317. \end{lstlisting}
  4318. There is immediately an opportunity for completion of \code{stmt\_list},
  4319. so we add the following to slot $7$.
  4320. \begin{lstlisting}
  4321. stmt_list: stmt NEWLINE stmt_list . (0)
  4322. \end{lstlisting}
  4323. This triggers another completion action for \code{stmt\_list} in slot $0$
  4324. \begin{lstlisting}
  4325. lang_int: stmt_list . (0)
  4326. \end{lstlisting}
  4327. which in turn completes \code{lang\_int}, the start symbol of the
  4328. grammar, so the parsing of the input is complete.
  4329. For reference, we now give a general description of the Earley
  4330. algorithm.
  4331. \begin{enumerate}
  4332. \item The algorithm begins by initializing slot $0$ of the chart with the
  4333. grammar rule for the start symbol, placing a period at the beginning
  4334. of the right-hand side, and recording its starting position as $0$.
  4335. \item The algorithm repeatedly applies the following three kinds of
  4336. actions for as long as there are opportunities to do so.
  4337. \begin{itemize}
  4338. \item Prediction: if there is a dotted rule in slot $k$ whose period
  4339. comes before a nonterminal, add all the rules for that nonterminal
  4340. into slot $k$, placing a period at the beginning of their
  4341. right-hand sides, and recording their starting position as
  4342. $k$.
  4343. \item Scanning: If the token at position $k$ of the input string
  4344. matches the symbol after the period in a dotted rule in slot $k$
  4345. of the chart, advance the prior in the dotted rule, adding
  4346. the result to slot $k+1$.
  4347. \item Completion: If a dotted rule in slot $k$ has a period at the
  4348. end, consider the rules in the slot corresponding to the starting
  4349. position of the completed rule. If any of those rules have a
  4350. nonterminal following their period that matches the left-hand side
  4351. of the completed rule, then advance their period, placing the new
  4352. dotted rule in slot $k$.
  4353. \end{itemize}
  4354. While repeating these three actions, take care to never add
  4355. duplicate dotted rules to the chart.
  4356. \end{enumerate}
  4357. We have described how the Earley algorithm recognizes that an input
  4358. string matches a grammar, but we have not described how it builds a
  4359. parse tree. The basic idea is simple, but building parse trees in an
  4360. efficient way is more complex, requiring a data structure called a
  4361. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4362. to attach a partial parse tree to every dotted rule in the chart.
  4363. Initially, the tree node associated with a dotted rule has no
  4364. children. As the period moves to the right, the nodes from the
  4365. subparses are added as children to this tree node.
  4366. As mentioned at the beginning of this section, the Earley algorithm is
  4367. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4368. files that contain thousands of tokens in a reasonable amount of time,
  4369. but not millions. In the next section we discuss the LALR(1) parsing
  4370. algorithm, which has time complexity $O(n)$, making it practical to
  4371. use with even the largest of input files.
  4372. \section{The LALR(1) Algorithm}
  4373. \label{sec:lalr}
  4374. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4375. two phase approach in which it first compiles the grammar into a state
  4376. machine and then runs the state machine to parse an input string.
  4377. %
  4378. A particularly influential implementation of LALR(1) was the
  4379. \texttt{yacc} parser generator by \citet{Johnson:1979qy}, which stands
  4380. for Yet Another Compiler Compiler.
  4381. %
  4382. The LALR(1) state machine uses a stack to record its progress in
  4383. parsing the input string. Each element of the stack is a pair: a
  4384. state number and a grammar symbol (a terminal or nonterminal). The
  4385. symbol characterizes the input that has been parsed so-far and the
  4386. state number is used to remember how to proceed once the next
  4387. symbol-worth of input has been parsed. Each state in the machine
  4388. represents where the parser stands in the parsing process with respect
  4389. to certain grammar rules. In particular, each state is associated with
  4390. a set of dotted rules.
  4391. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4392. (also called parse table) for the following simple but ambiguous
  4393. grammar:
  4394. \begin{lstlisting}[escapechar=$]
  4395. exp: INT
  4396. | exp "+" exp
  4397. stmt: "print" exp
  4398. start: stmt
  4399. \end{lstlisting}
  4400. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4401. read in a \lstinline{PRINT} token, so the top of the stack is
  4402. \lstinline{(1,PRINT)}. The parser is part of the way through parsing
  4403. the input according to grammar rule 1, which is signified by showing
  4404. rule 1 with a period after the \code{PRINT} token and before the
  4405. \code{exp} nonterminal. A rule with a period in it is called an
  4406. \emph{item}. There are several rules that could apply next, both rule
  4407. 2 and 3, so state 1 also shows those rules with a period at the
  4408. beginning of their right-hand sides. The edges between states indicate
  4409. which transitions the machine should make depending on the next input
  4410. token. So, for example, if the next input token is \code{INT} then the
  4411. parser will push \code{INT} and the target state 4 on the stack and
  4412. transition to state 4. Suppose we are now at the end of the input. In
  4413. state 4 it says we should reduce by rule 3, so we pop from the stack
  4414. the same number of items as the number of symbols in the right-hand
  4415. side of the rule, in this case just one. We then momentarily jump to
  4416. the state at the top of the stack (state 1) and then follow the goto
  4417. edge that corresponds to the left-hand side of the rule we just
  4418. reduced by, in this case \code{exp}, so we arrive at state 3. (A
  4419. slightly longer example parse is shown in
  4420. Figure~\ref{fig:shift-reduce}.)
  4421. \begin{figure}[htbp]
  4422. \centering
  4423. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4424. \caption{An LALR(1) parse table and a trace of an example run.}
  4425. \label{fig:shift-reduce}
  4426. \end{figure}
  4427. In general, the algorithm works as follows. Look at the next input
  4428. token.
  4429. \begin{itemize}
  4430. \item If there there is a shift edge for the input token, push the
  4431. edge's target state and the input token on the stack and proceed to
  4432. the edge's target state.
  4433. \item If there is a reduce action for the input token, pop $k$
  4434. elements from the stack, where $k$ is the number of symbols in the
  4435. right-hand side of the rule being reduced. Jump to the state at the
  4436. top of the stack and then follow the goto edge for the nonterminal
  4437. that matches the left-hand side of the rule that we reducing
  4438. by. Push the edge's target state and the nonterminal on the stack.
  4439. \end{itemize}
  4440. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4441. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4442. algorithm does not know which action to take in this case. When a
  4443. state has both a shift and a reduce action for the same token, we say
  4444. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4445. will arise, for example, when trying to parse the input
  4446. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4447. the parser will be in state 6, and it will not know whether to
  4448. reduce to form an \emph{exp} of \lstinline{1 + 2}, or whether it
  4449. should proceed by shifting the next \lstinline{+} from the input.
  4450. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4451. arises when there are two reduce actions in a state for the same
  4452. token. To understand which grammars gives rise to shift/reduce and
  4453. reduce/reduce conflicts, it helps to know how the parse table is
  4454. generated from the grammar, which we discuss next.
  4455. The parse table is generated one state at a time. State 0 represents
  4456. the start of the parser. We add the grammar rule for the start symbol
  4457. to this state with a period at the beginning of the right-hand side,
  4458. similar to the initialization phase of the Earley parser. If the
  4459. period appears immediately before another nonterminal, we add all the
  4460. rules with that nonterminal on the left-hand side. Again, we place a
  4461. period at the beginning of the right-hand side of each the new
  4462. rules. This process called \emph{state closure} is continued
  4463. until there are no more rules to add (similar to the prediction
  4464. actions of an Earley parser). We then examine each dotted rule in the
  4465. current state $I$. Suppose a dotted rule has the form $A ::=
  4466. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4467. are sequences of symbols. We create a new state, call it $J$. If $X$
  4468. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4469. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4470. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4471. state $J$. We start by adding all dotted rules from state $I$ that
  4472. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4473. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4474. the period moved past the $X$. (This is analogous to completion in
  4475. the Earley algorithm.) We then perform state closure on $J$. This
  4476. process repeats until there are no more states or edges to add.
  4477. We then mark states as accepting states if they have a dotted rule
  4478. that is the start rule with a period at the end. Also, to add
  4479. in the reduce actions, we look for any state containing a dotted rule
  4480. with a period at the end. Let $n$ be the rule number for this dotted
  4481. rule. We then put a reduce $n$ action into that state for every token
  4482. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4483. dotted rule with a period at the end. We therefore put a reduce by
  4484. rule 3 action into state 4 for every
  4485. token.
  4486. %% (Figure~\ref{fig:shift-reduce} does not show a reduce rule for
  4487. %% \code{INT} in state 4 because this grammar does not allow two
  4488. %% consecutive \code{INT} tokens in the input. We will not go into how
  4489. %% this can be figured out, but in any event it does no harm to have a
  4490. %% reduce rule for \code{INT} in state 4; it just means the input will be
  4491. %% rejected at a later point in the parsing process.)
  4492. When inserting reduce actions, take care to spot any shift/reduce or
  4493. reduce/reduce conflicts. If there are any, abort the construction of
  4494. the parse table.
  4495. \begin{exercise}
  4496. \normalfont\normalsize
  4497. %
  4498. On a piece of paper, walk through the parse table generation process
  4499. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4500. your results against parse table in figure~\ref{fig:shift-reduce}.
  4501. \end{exercise}
  4502. \begin{exercise}
  4503. \normalfont\normalsize
  4504. %
  4505. Change the parser in your compiler for \LangVar{} to set the
  4506. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4507. all the \LangVar{} programs that you have created. In doing so, Lark
  4508. may signal an error due to shift/reduce or reduce/reduce conflicts
  4509. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4510. remove those conflicts.
  4511. \end{exercise}
  4512. \section{Further Reading}
  4513. In this chapter we have just scratched the surface of the field of
  4514. parsing, with the study of a very general but less efficient algorithm
  4515. (Earley) and with a more limited but highly efficient algorithm
  4516. (LALR). There are many more algorithms, and classes of grammars, that
  4517. fall between these two ends of the spectrum. We recommend the reader
  4518. to \citet{Aho:2006wb} for a thorough treatment of parsing.
  4519. Regarding lexical analysis, we described the specification language,
  4520. the regular expressions, but not the algorithms for recognizing them.
  4521. In short, regular expressions can be translated to nondeterministic
  4522. finite automata, which in turn are translated to finite automata. We
  4523. refer the reader again to \citet{Aho:2006wb} for all the details on
  4524. lexical analysis.
  4525. \fi}
  4526. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4527. \chapter{Register Allocation}
  4528. \label{ch:register-allocation-Lvar}
  4529. \setcounter{footnote}{0}
  4530. \index{subject}{register allocation}
  4531. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4532. storing variables on the procedure call stack. The CPU may require tens
  4533. to hundreds of cycles to access a location on the stack, whereas
  4534. accessing a register takes only a single cycle. In this chapter we
  4535. improve the efficiency of our generated code by storing some variables
  4536. in registers. The goal of register allocation is to fit as many
  4537. variables into registers as possible. Some programs have more
  4538. variables than registers, so we cannot always map each variable to a
  4539. different register. Fortunately, it is common for different variables
  4540. to be in use during different periods of time during program
  4541. execution, and in those cases we can map multiple variables to the
  4542. same register.
  4543. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4544. example. The source program is on the left and the output of
  4545. instruction selection is on the right. The program is almost
  4546. completely in the x86 assembly language, but it still uses variables.
  4547. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4548. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4549. the other hand, is used only after this point, so \code{x} and
  4550. \code{z} could share the same register.
  4551. \begin{figure}
  4552. \begin{tcolorbox}[colback=white]
  4553. \begin{minipage}{0.45\textwidth}
  4554. Example \LangVar{} program:
  4555. % var_test_28.rkt
  4556. {\if\edition\racketEd
  4557. \begin{lstlisting}
  4558. (let ([v 1])
  4559. (let ([w 42])
  4560. (let ([x (+ v 7)])
  4561. (let ([y x])
  4562. (let ([z (+ x w)])
  4563. (+ z (- y)))))))
  4564. \end{lstlisting}
  4565. \fi}
  4566. {\if\edition\pythonEd
  4567. \begin{lstlisting}
  4568. v = 1
  4569. w = 42
  4570. x = v + 7
  4571. y = x
  4572. z = x + w
  4573. print(z + (- y))
  4574. \end{lstlisting}
  4575. \fi}
  4576. \end{minipage}
  4577. \begin{minipage}{0.45\textwidth}
  4578. After instruction selection:
  4579. {\if\edition\racketEd
  4580. \begin{lstlisting}
  4581. locals-types:
  4582. x : Integer, y : Integer,
  4583. z : Integer, t : Integer,
  4584. v : Integer, w : Integer
  4585. start:
  4586. movq $1, v
  4587. movq $42, w
  4588. movq v, x
  4589. addq $7, x
  4590. movq x, y
  4591. movq x, z
  4592. addq w, z
  4593. movq y, t
  4594. negq t
  4595. movq z, %rax
  4596. addq t, %rax
  4597. jmp conclusion
  4598. \end{lstlisting}
  4599. \fi}
  4600. {\if\edition\pythonEd
  4601. \begin{lstlisting}
  4602. movq $1, v
  4603. movq $42, w
  4604. movq v, x
  4605. addq $7, x
  4606. movq x, y
  4607. movq x, z
  4608. addq w, z
  4609. movq y, tmp_0
  4610. negq tmp_0
  4611. movq z, tmp_1
  4612. addq tmp_0, tmp_1
  4613. movq tmp_1, %rdi
  4614. callq print_int
  4615. \end{lstlisting}
  4616. \fi}
  4617. \end{minipage}
  4618. \end{tcolorbox}
  4619. \caption{A running example for register allocation.}
  4620. \label{fig:reg-eg}
  4621. \end{figure}
  4622. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4623. compute where a variable is in use. Once we have that information, we
  4624. compute which variables are in use at the same time, i.e., which ones
  4625. \emph{interfere}\index{subject}{interfere} with each other, and
  4626. represent this relation as an undirected graph whose vertices are
  4627. variables and edges indicate when two variables interfere
  4628. (section~\ref{sec:build-interference}). We then model register
  4629. allocation as a graph coloring problem
  4630. (section~\ref{sec:graph-coloring}).
  4631. If we run out of registers despite these efforts, we place the
  4632. remaining variables on the stack, similarly to how we handled
  4633. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4634. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4635. location. The decision to spill a variable is handled as part of the
  4636. graph coloring process.
  4637. We make the simplifying assumption that each variable is assigned to
  4638. one location (a register or stack address). A more sophisticated
  4639. approach is to assign a variable to one or more locations in different
  4640. regions of the program. For example, if a variable is used many times
  4641. in short sequence and then used again only after many other
  4642. instructions, it could be more efficient to assign the variable to a
  4643. register during the initial sequence and then move it to the stack for
  4644. the rest of its lifetime. We refer the interested reader to
  4645. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4646. approach.
  4647. % discuss prioritizing variables based on how much they are used.
  4648. \section{Registers and Calling Conventions}
  4649. \label{sec:calling-conventions}
  4650. \index{subject}{calling conventions}
  4651. As we perform register allocation, we must be aware of the
  4652. \emph{calling conventions} \index{subject}{calling conventions} that
  4653. govern how functions calls are performed in x86.
  4654. %
  4655. Even though \LangVar{} does not include programmer-defined functions,
  4656. our generated code includes a \code{main} function that is called by
  4657. the operating system and our generated code contains calls to the
  4658. \code{read\_int} function.
  4659. Function calls require coordination between two pieces of code that
  4660. may be written by different programmers or generated by different
  4661. compilers. Here we follow the System V calling conventions that are
  4662. used by the GNU C compiler on Linux and
  4663. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4664. %
  4665. The calling conventions include rules about how functions share the
  4666. use of registers. In particular, the caller is responsible for freeing
  4667. some registers prior to the function call for use by the callee.
  4668. These are called the \emph{caller-saved registers}
  4669. \index{subject}{caller-saved registers}
  4670. and they are
  4671. \begin{lstlisting}
  4672. rax rcx rdx rsi rdi r8 r9 r10 r11
  4673. \end{lstlisting}
  4674. On the other hand, the callee is responsible for preserving the values
  4675. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4676. which are
  4677. \begin{lstlisting}
  4678. rsp rbp rbx r12 r13 r14 r15
  4679. \end{lstlisting}
  4680. We can think about this caller/callee convention from two points of
  4681. view, the caller view and the callee view, as follows:
  4682. \begin{itemize}
  4683. \item The caller should assume that all the caller-saved registers get
  4684. overwritten with arbitrary values by the callee. On the other hand,
  4685. the caller can safely assume that all the callee-saved registers
  4686. retain their original values.
  4687. \item The callee can freely use any of the caller-saved registers.
  4688. However, if the callee wants to use a callee-saved register, the
  4689. callee must arrange to put the original value back in the register
  4690. prior to returning to the caller. This can be accomplished by saving
  4691. the value to the stack in the prelude of the function and restoring
  4692. the value in the conclusion of the function.
  4693. \end{itemize}
  4694. In x86, registers are also used for passing arguments to a function
  4695. and for the return value. In particular, the first six arguments of a
  4696. function are passed in the following six registers, in this order.
  4697. \index{subject}{argument-passing registers}
  4698. \index{subject}{parameter-passing registers}
  4699. \begin{lstlisting}
  4700. rdi rsi rdx rcx r8 r9
  4701. \end{lstlisting}
  4702. If there are more than six arguments, the convention is to use
  4703. space on the frame of the caller for the rest of the
  4704. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4705. need more than six arguments.
  4706. %
  4707. \racket{For now, the only function we care about is \code{read\_int},
  4708. which takes zero arguments.}
  4709. %
  4710. \python{For now, the only functions we care about are \code{read\_int}
  4711. and \code{print\_int}, which take zero and one argument, respectively.}
  4712. %
  4713. The register \code{rax} is used for the return value of a function.
  4714. The next question is how these calling conventions impact register
  4715. allocation. Consider the \LangVar{} program presented in
  4716. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4717. example from the caller point of view and then from the callee point
  4718. of view. We refer to a variable that is in use during a function call
  4719. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4720. The program makes two calls to \READOP{}. The variable \code{x} is
  4721. call-live because it is in use during the second call to \READOP{}; we
  4722. must ensure that the value in \code{x} does not get overwritten during
  4723. the call to \READOP{}. One obvious approach is to save all the values
  4724. that reside in caller-saved registers to the stack prior to each
  4725. function call and to restore them after each call. That way, if the
  4726. register allocator chooses to assign \code{x} to a caller-saved
  4727. register, its value will be preserved across the call to \READOP{}.
  4728. However, saving and restoring to the stack is relatively slow. If
  4729. \code{x} is not used many times, it may be better to assign \code{x}
  4730. to a stack location in the first place. Or better yet, if we can
  4731. arrange for \code{x} to be placed in a callee-saved register, then it
  4732. won't need to be saved and restored during function calls.
  4733. The approach that we recommend for call-live variables is either to
  4734. assign them to callee-saved registers or to spill them to the
  4735. stack. On the other hand, for variables that are not call-live, we try
  4736. the following alternatives in order: (1) look for an available
  4737. caller-saved register (to leave room for other variables in the
  4738. callee-saved register), (2) look for a callee-saved register, and (3)
  4739. spill the variable to the stack.
  4740. It is straightforward to implement this approach in a graph coloring
  4741. register allocator. First, we know which variables are call-live
  4742. because we already need to compute which variables are in use at every
  4743. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  4744. we build the interference graph
  4745. (section~\ref{sec:build-interference}), we can place an edge between
  4746. each of the call-live variables and the caller-saved registers in the
  4747. interference graph. This will prevent the graph coloring algorithm
  4748. from assigning them to caller-saved registers.
  4749. Returning to the example in
  4750. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4751. generated x86 code on the right-hand side. Notice that variable
  4752. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  4753. is already in a safe place during the second call to
  4754. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  4755. \code{rcx}, a caller-saved register, because \code{y} is not a
  4756. call-live variable.
  4757. Next we analyze the example from the callee point of view, focusing on
  4758. the prelude and conclusion of the \code{main} function. As usual, the
  4759. prelude begins with saving the \code{rbp} register to the stack and
  4760. setting the \code{rbp} to the current stack pointer. We now know why
  4761. it is necessary to save the \code{rbp}: it is a callee-saved register.
  4762. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  4763. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  4764. (\code{x}). The other callee-saved registers are not saved in the
  4765. prelude because they are not used. The prelude subtracts 8 bytes from
  4766. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4767. conclusion, we see that \code{rbx} is restored from the stack with a
  4768. \code{popq} instruction.
  4769. \index{subject}{prelude}\index{subject}{conclusion}
  4770. \begin{figure}[tp]
  4771. \begin{tcolorbox}[colback=white]
  4772. \begin{minipage}{0.45\textwidth}
  4773. Example \LangVar{} program:
  4774. %var_test_14.rkt
  4775. {\if\edition\racketEd
  4776. \begin{lstlisting}
  4777. (let ([x (read)])
  4778. (let ([y (read)])
  4779. (+ (+ x y) 42)))
  4780. \end{lstlisting}
  4781. \fi}
  4782. {\if\edition\pythonEd
  4783. \begin{lstlisting}
  4784. x = input_int()
  4785. y = input_int()
  4786. print((x + y) + 42)
  4787. \end{lstlisting}
  4788. \fi}
  4789. \end{minipage}
  4790. \begin{minipage}{0.45\textwidth}
  4791. Generated x86 assembly:
  4792. {\if\edition\racketEd
  4793. \begin{lstlisting}
  4794. start:
  4795. callq read_int
  4796. movq %rax, %rbx
  4797. callq read_int
  4798. movq %rax, %rcx
  4799. addq %rcx, %rbx
  4800. movq %rbx, %rax
  4801. addq $42, %rax
  4802. jmp _conclusion
  4803. .globl main
  4804. main:
  4805. pushq %rbp
  4806. movq %rsp, %rbp
  4807. pushq %rbx
  4808. subq $8, %rsp
  4809. jmp start
  4810. conclusion:
  4811. addq $8, %rsp
  4812. popq %rbx
  4813. popq %rbp
  4814. retq
  4815. \end{lstlisting}
  4816. \fi}
  4817. {\if\edition\pythonEd
  4818. \begin{lstlisting}
  4819. .globl main
  4820. main:
  4821. pushq %rbp
  4822. movq %rsp, %rbp
  4823. pushq %rbx
  4824. subq $8, %rsp
  4825. callq read_int
  4826. movq %rax, %rbx
  4827. callq read_int
  4828. movq %rax, %rcx
  4829. movq %rbx, %rdx
  4830. addq %rcx, %rdx
  4831. movq %rdx, %rcx
  4832. addq $42, %rcx
  4833. movq %rcx, %rdi
  4834. callq print_int
  4835. addq $8, %rsp
  4836. popq %rbx
  4837. popq %rbp
  4838. retq
  4839. \end{lstlisting}
  4840. \fi}
  4841. \end{minipage}
  4842. \end{tcolorbox}
  4843. \caption{An example with function calls.}
  4844. \label{fig:example-calling-conventions}
  4845. \end{figure}
  4846. %\clearpage
  4847. \section{Liveness Analysis}
  4848. \label{sec:liveness-analysis-Lvar}
  4849. \index{subject}{liveness analysis}
  4850. The \code{uncover\_live} \racket{pass}\python{function} performs
  4851. \emph{liveness analysis}; that is, it discovers which variables are
  4852. in use in different regions of a program.
  4853. %
  4854. A variable or register is \emph{live} at a program point if its
  4855. current value is used at some later point in the program. We refer to
  4856. variables, stack locations, and registers collectively as
  4857. \emph{locations}.
  4858. %
  4859. Consider the following code fragment in which there are two writes to
  4860. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4861. time?
  4862. \begin{center}
  4863. \begin{minipage}{0.96\textwidth}
  4864. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4865. movq $5, a
  4866. movq $30, b
  4867. movq a, c
  4868. movq $10, b
  4869. addq b, c
  4870. \end{lstlisting}
  4871. \end{minipage}
  4872. \end{center}
  4873. The answer is no, because \code{a} is live from line 1 to 3 and
  4874. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4875. line 2 is never used because it is overwritten (line 4) before the
  4876. next read (line 5).
  4877. The live locations for each instruction can be computed by traversing
  4878. the instruction sequence back to front (i.e., backward in execution
  4879. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4880. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4881. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4882. locations before instruction $I_k$. \racket{We recommend representing
  4883. these sets with the Racket \code{set} data structure described in
  4884. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4885. with the Python
  4886. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4887. data structure.}
  4888. {\if\edition\racketEd
  4889. \begin{figure}[tp]
  4890. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4891. \small
  4892. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4893. A \emph{set} is an unordered collection of elements without duplicates.
  4894. Here are some of the operations defined on sets.
  4895. \index{subject}{set}
  4896. \begin{description}
  4897. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4898. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4899. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4900. difference of the two sets.
  4901. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4902. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4903. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4904. \end{description}
  4905. \end{tcolorbox}
  4906. %\end{wrapfigure}
  4907. \caption{The \code{set} data structure.}
  4908. \label{fig:set}
  4909. \end{figure}
  4910. \fi}
  4911. The live locations after an instruction are always the same as the
  4912. live locations before the next instruction.
  4913. \index{subject}{live-after} \index{subject}{live-before}
  4914. \begin{equation} \label{eq:live-after-before-next}
  4915. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4916. \end{equation}
  4917. To start things off, there are no live locations after the last
  4918. instruction, so
  4919. \begin{equation}\label{eq:live-last-empty}
  4920. L_{\mathsf{after}}(n) = \emptyset
  4921. \end{equation}
  4922. We then apply the following rule repeatedly, traversing the
  4923. instruction sequence back to front.
  4924. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4925. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4926. \end{equation}
  4927. where $W(k)$ are the locations written to by instruction $I_k$, and
  4928. $R(k)$ are the locations read by instruction $I_k$.
  4929. {\if\edition\racketEd
  4930. %
  4931. There is a special case for \code{jmp} instructions. The locations
  4932. that are live before a \code{jmp} should be the locations in
  4933. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4934. maintaining an alist named \code{label->live} that maps each label to
  4935. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4936. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4937. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4938. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4939. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4940. %
  4941. \fi}
  4942. Let us walk through the previous example, applying these formulas
  4943. starting with the instruction on line 5 of the code fragment. We
  4944. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4945. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4946. $\emptyset$ because it is the last instruction
  4947. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4948. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4949. variables \code{b} and \code{c}
  4950. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4951. \[
  4952. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4953. \]
  4954. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4955. the live-before set from line 5 to be the live-after set for this
  4956. instruction (formula~\eqref{eq:live-after-before-next}).
  4957. \[
  4958. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4959. \]
  4960. This move instruction writes to \code{b} and does not read from any
  4961. variables, so we have the following live-before set
  4962. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4963. \[
  4964. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4965. \]
  4966. The live-before for instruction \code{movq a, c}
  4967. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4968. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4969. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4970. variable that is not live and does not read from a variable.
  4971. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4972. because it writes to variable \code{a}.
  4973. \begin{figure}[tbp]
  4974. \centering
  4975. \begin{tcolorbox}[colback=white]
  4976. \hspace{10pt}
  4977. \begin{minipage}{0.4\textwidth}
  4978. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4979. movq $5, a
  4980. movq $30, b
  4981. movq a, c
  4982. movq $10, b
  4983. addq b, c
  4984. \end{lstlisting}
  4985. \end{minipage}
  4986. \vrule\hspace{10pt}
  4987. \begin{minipage}{0.45\textwidth}
  4988. \begin{align*}
  4989. L_{\mathsf{before}}(1)= \emptyset,
  4990. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4991. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4992. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4993. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4994. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4995. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4996. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4997. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4998. L_{\mathsf{after}}(5)= \emptyset
  4999. \end{align*}
  5000. \end{minipage}
  5001. \end{tcolorbox}
  5002. \caption{Example output of liveness analysis on a short example.}
  5003. \label{fig:liveness-example-0}
  5004. \end{figure}
  5005. \begin{exercise}\normalfont\normalsize
  5006. Perform liveness analysis by hand on the running example in
  5007. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5008. sets for each instruction. Compare your answers to the solution
  5009. shown in figure~\ref{fig:live-eg}.
  5010. \end{exercise}
  5011. \begin{figure}[tp]
  5012. \hspace{20pt}
  5013. \begin{minipage}{0.55\textwidth}
  5014. \begin{tcolorbox}[colback=white]
  5015. {\if\edition\racketEd
  5016. \begin{lstlisting}
  5017. |$\{\ttm{rsp}\}$|
  5018. movq $1, v
  5019. |$\{\ttm{v},\ttm{rsp}\}$|
  5020. movq $42, w
  5021. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5022. movq v, x
  5023. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5024. addq $7, x
  5025. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5026. movq x, y
  5027. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5028. movq x, z
  5029. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5030. addq w, z
  5031. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5032. movq y, t
  5033. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5034. negq t
  5035. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5036. movq z, %rax
  5037. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5038. addq t, %rax
  5039. |$\{\ttm{rax},\ttm{rsp}\}$|
  5040. jmp conclusion
  5041. \end{lstlisting}
  5042. \fi}
  5043. {\if\edition\pythonEd
  5044. \begin{lstlisting}
  5045. movq $1, v
  5046. |$\{\ttm{v}\}$|
  5047. movq $42, w
  5048. |$\{\ttm{w}, \ttm{v}\}$|
  5049. movq v, x
  5050. |$\{\ttm{w}, \ttm{x}\}$|
  5051. addq $7, x
  5052. |$\{\ttm{w}, \ttm{x}\}$|
  5053. movq x, y
  5054. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5055. movq x, z
  5056. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5057. addq w, z
  5058. |$\{\ttm{y}, \ttm{z}\}$|
  5059. movq y, tmp_0
  5060. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5061. negq tmp_0
  5062. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5063. movq z, tmp_1
  5064. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5065. addq tmp_0, tmp_1
  5066. |$\{\ttm{tmp\_1}\}$|
  5067. movq tmp_1, %rdi
  5068. |$\{\ttm{rdi}\}$|
  5069. callq print_int
  5070. |$\{\}$|
  5071. \end{lstlisting}
  5072. \fi}
  5073. \end{tcolorbox}
  5074. \end{minipage}
  5075. \caption{The running example annotated with live-after sets.}
  5076. \label{fig:live-eg}
  5077. \end{figure}
  5078. \begin{exercise}\normalfont\normalsize
  5079. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5080. %
  5081. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5082. field of the \code{Block} structure.}
  5083. %
  5084. \python{Return a dictionary that maps each instruction to its
  5085. live-after set.}
  5086. %
  5087. \racket{We recommend creating an auxiliary function that takes a list
  5088. of instructions and an initial live-after set (typically empty) and
  5089. returns the list of live-after sets.}
  5090. %
  5091. We recommend creating auxiliary functions to (1) compute the set
  5092. of locations that appear in an \Arg{}, (2) compute the locations read
  5093. by an instruction (the $R$ function), and (3) the locations written by
  5094. an instruction (the $W$ function). The \code{callq} instruction should
  5095. include all the caller-saved registers in its write set $W$ because
  5096. the calling convention says that those registers may be written to
  5097. during the function call. Likewise, the \code{callq} instruction
  5098. should include the appropriate argument-passing registers in its
  5099. read set $R$, depending on the arity of the function being
  5100. called. (This is why the abstract syntax for \code{callq} includes the
  5101. arity.)
  5102. \end{exercise}
  5103. %\clearpage
  5104. \section{Build the Interference Graph}
  5105. \label{sec:build-interference}
  5106. {\if\edition\racketEd
  5107. \begin{figure}[tp]
  5108. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5109. \small
  5110. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5111. A \emph{graph} is a collection of vertices and edges where each
  5112. edge connects two vertices. A graph is \emph{directed} if each
  5113. edge points from a source to a target. Otherwise the graph is
  5114. \emph{undirected}.
  5115. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5116. \begin{description}
  5117. %% We currently don't use directed graphs. We instead use
  5118. %% directed multi-graphs. -Jeremy
  5119. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5120. directed graph from a list of edges. Each edge is a list
  5121. containing the source and target vertex.
  5122. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5123. undirected graph from a list of edges. Each edge is represented by
  5124. a list containing two vertices.
  5125. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5126. inserts a vertex into the graph.
  5127. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5128. inserts an edge between the two vertices.
  5129. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5130. returns a sequence of vertices adjacent to the vertex.
  5131. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5132. returns a sequence of all vertices in the graph.
  5133. \end{description}
  5134. \end{tcolorbox}
  5135. %\end{wrapfigure}
  5136. \caption{The Racket \code{graph} package.}
  5137. \label{fig:graph}
  5138. \end{figure}
  5139. \fi}
  5140. On the basis of the liveness analysis, we know where each location is
  5141. live. However, during register allocation, we need to answer
  5142. questions of the specific form: are locations $u$ and $v$ live at the
  5143. same time? (If so, they cannot be assigned to the same register.) To
  5144. make this question more efficient to answer, we create an explicit
  5145. data structure, an \emph{interference
  5146. graph}\index{subject}{interference graph}. An interference graph is
  5147. an undirected graph that has an edge between two locations if they are
  5148. live at the same time, that is, if they interfere with each other.
  5149. %
  5150. \racket{We recommend using the Racket \code{graph} package
  5151. (figure~\ref{fig:graph}) to represent the interference graph.}
  5152. %
  5153. \python{We provide implementations of directed and undirected graph
  5154. data structures in the file \code{graph.py} of the support code.}
  5155. A straightforward way to compute the interference graph is to look at
  5156. the set of live locations between each instruction and add an edge to
  5157. the graph for every pair of variables in the same set. This approach
  5158. is less than ideal for two reasons. First, it can be expensive because
  5159. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5160. locations. Second, in the special case in which two locations hold the
  5161. same value (because one was assigned to the other), they can be live
  5162. at the same time without interfering with each other.
  5163. A better way to compute the interference graph is to focus on
  5164. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5165. must not overwrite something in a live location. So for each
  5166. instruction, we create an edge between the locations being written to
  5167. and the live locations. (However, a location never interferes with
  5168. itself.) For the \key{callq} instruction, we consider all the
  5169. caller-saved registers to have been written to, so an edge is added
  5170. between every live variable and every caller-saved register. Also, for
  5171. \key{movq} there is the special case of two variables holding the same
  5172. value. If a live variable $v$ is the same as the source of the
  5173. \key{movq}, then there is no need to add an edge between $v$ and the
  5174. destination, because they both hold the same value.
  5175. %
  5176. Hence we have the following two rules:
  5177. \begin{enumerate}
  5178. \item If instruction $I_k$ is a move instruction of the form
  5179. \key{movq} $s$\key{,} $d$, then for every $v \in
  5180. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5181. $(d,v)$.
  5182. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5183. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5184. $(d,v)$.
  5185. \end{enumerate}
  5186. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5187. these rules to each instruction. We highlight a few of the
  5188. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5189. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5190. so \code{v} interferes with \code{rsp}.}
  5191. %
  5192. \python{The first instruction is \lstinline{movq $1, v}, and the
  5193. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5194. no interference because $\ttm{v}$ is the destination of the move.}
  5195. %
  5196. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5197. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5198. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5199. %
  5200. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5201. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5202. $\ttm{x}$ interferes with \ttm{w}.}
  5203. %
  5204. \racket{The next instruction is \lstinline{movq x, y}, and the
  5205. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5206. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5207. \ttm{x} because \ttm{x} is the source of the move and therefore
  5208. \ttm{x} and \ttm{y} hold the same value.}
  5209. %
  5210. \python{The next instruction is \lstinline{movq x, y}, and the
  5211. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5212. applies, so \ttm{y} interferes with \ttm{w} but not
  5213. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5214. \ttm{x} and \ttm{y} hold the same value.}
  5215. %
  5216. Figure~\ref{fig:interference-results} lists the interference results
  5217. for all the instructions, and the resulting interference graph is
  5218. shown in figure~\ref{fig:interfere}.
  5219. \begin{figure}[tbp]
  5220. \begin{tcolorbox}[colback=white]
  5221. \begin{quote}
  5222. {\if\edition\racketEd
  5223. \begin{tabular}{ll}
  5224. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5225. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5226. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5227. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5228. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5229. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5230. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5231. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5232. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5233. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5234. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5235. \lstinline!jmp conclusion!& no interference.
  5236. \end{tabular}
  5237. \fi}
  5238. {\if\edition\pythonEd
  5239. \begin{tabular}{ll}
  5240. \lstinline!movq $1, v!& no interference\\
  5241. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5242. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5243. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5244. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5245. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5246. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5247. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5248. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5249. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5250. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5251. \lstinline!movq tmp_1, %rdi! & no interference \\
  5252. \lstinline!callq print_int!& no interference.
  5253. \end{tabular}
  5254. \fi}
  5255. \end{quote}
  5256. \end{tcolorbox}
  5257. \caption{Interference results for the running example.}
  5258. \label{fig:interference-results}
  5259. \end{figure}
  5260. \begin{figure}[tbp]
  5261. \begin{tcolorbox}[colback=white]
  5262. \large
  5263. {\if\edition\racketEd
  5264. \[
  5265. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5266. \node (rax) at (0,0) {$\ttm{rax}$};
  5267. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5268. \node (t1) at (0,2) {$\ttm{t}$};
  5269. \node (z) at (3,2) {$\ttm{z}$};
  5270. \node (x) at (6,2) {$\ttm{x}$};
  5271. \node (y) at (3,0) {$\ttm{y}$};
  5272. \node (w) at (6,0) {$\ttm{w}$};
  5273. \node (v) at (9,0) {$\ttm{v}$};
  5274. \draw (t1) to (rax);
  5275. \draw (t1) to (z);
  5276. \draw (z) to (y);
  5277. \draw (z) to (w);
  5278. \draw (x) to (w);
  5279. \draw (y) to (w);
  5280. \draw (v) to (w);
  5281. \draw (v) to (rsp);
  5282. \draw (w) to (rsp);
  5283. \draw (x) to (rsp);
  5284. \draw (y) to (rsp);
  5285. \path[-.,bend left=15] (z) edge node {} (rsp);
  5286. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5287. \draw (rax) to (rsp);
  5288. \end{tikzpicture}
  5289. \]
  5290. \fi}
  5291. {\if\edition\pythonEd
  5292. \[
  5293. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5294. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5295. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5296. \node (z) at (3,2) {$\ttm{z}$};
  5297. \node (x) at (6,2) {$\ttm{x}$};
  5298. \node (y) at (3,0) {$\ttm{y}$};
  5299. \node (w) at (6,0) {$\ttm{w}$};
  5300. \node (v) at (9,0) {$\ttm{v}$};
  5301. \draw (t0) to (t1);
  5302. \draw (t0) to (z);
  5303. \draw (z) to (y);
  5304. \draw (z) to (w);
  5305. \draw (x) to (w);
  5306. \draw (y) to (w);
  5307. \draw (v) to (w);
  5308. \end{tikzpicture}
  5309. \]
  5310. \fi}
  5311. \end{tcolorbox}
  5312. \caption{The interference graph of the example program.}
  5313. \label{fig:interfere}
  5314. \end{figure}
  5315. %% Our next concern is to choose a data structure for representing the
  5316. %% interference graph. There are many choices for how to represent a
  5317. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  5318. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  5319. %% data structure is to study the algorithm that uses the data structure,
  5320. %% determine what operations need to be performed, and then choose the
  5321. %% data structure that provide the most efficient implementations of
  5322. %% those operations. Often times the choice of data structure can have an
  5323. %% effect on the time complexity of the algorithm, as it does here. If
  5324. %% you skim the next section, you will see that the register allocation
  5325. %% algorithm needs to ask the graph for all its vertices and, given a
  5326. %% vertex, it needs to known all the adjacent vertices. Thus, the
  5327. %% correct choice of graph representation is that of an adjacency
  5328. %% list. There are helper functions in \code{utilities.rkt} for
  5329. %% representing graphs using the adjacency list representation:
  5330. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  5331. %% (Appendix~\ref{appendix:utilities}).
  5332. %% %
  5333. %% \margincomment{\footnotesize To do: change to use the
  5334. %% Racket graph library. \\ --Jeremy}
  5335. %% %
  5336. %% In particular, those functions use a hash table to map each vertex to
  5337. %% the set of adjacent vertices, and the sets are represented using
  5338. %% Racket's \key{set}, which is also a hash table.
  5339. \begin{exercise}\normalfont\normalsize
  5340. \racket{Implement the compiler pass named \code{build\_interference} according
  5341. to the algorithm suggested here. We recommend using the Racket
  5342. \code{graph} package to create and inspect the interference graph.
  5343. The output graph of this pass should be stored in the $\itm{info}$ field of
  5344. the program, under the key \code{conflicts}.}
  5345. %
  5346. \python{Implement a function named \code{build\_interference}
  5347. according to the algorithm suggested above that
  5348. returns the interference graph.}
  5349. \end{exercise}
  5350. \section{Graph Coloring via Sudoku}
  5351. \label{sec:graph-coloring}
  5352. \index{subject}{graph coloring}
  5353. \index{subject}{sudoku}
  5354. \index{subject}{color}
  5355. We come to the main event discussed in this chapter, mapping variables
  5356. to registers and stack locations. Variables that interfere with each
  5357. other must be mapped to different locations. In terms of the
  5358. interference graph, this means that adjacent vertices must be mapped
  5359. to different locations. If we think of locations as colors, the
  5360. register allocation problem becomes the graph coloring
  5361. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5362. The reader may be more familiar with the graph coloring problem than he
  5363. or she realizes; the popular game of sudoku is an instance of the
  5364. graph coloring problem. The following describes how to build a graph
  5365. out of an initial sudoku board.
  5366. \begin{itemize}
  5367. \item There is one vertex in the graph for each sudoku square.
  5368. \item There is an edge between two vertices if the corresponding squares
  5369. are in the same row, in the same column, or in the same $3\times 3$ region.
  5370. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5371. \item On the basis of the initial assignment of numbers to squares on the
  5372. sudoku board, assign the corresponding colors to the corresponding
  5373. vertices in the graph.
  5374. \end{itemize}
  5375. If you can color the remaining vertices in the graph with the nine
  5376. colors, then you have also solved the corresponding game of sudoku.
  5377. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5378. the corresponding graph with colored vertices. Here we use a
  5379. monochrome representation of colors, mapping the sudoku number 1 to
  5380. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5381. of the vertices (the colored ones) because showing edges for all the
  5382. vertices would make the graph unreadable.
  5383. \begin{figure}[tbp]
  5384. \begin{tcolorbox}[colback=white]
  5385. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5386. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5387. \end{tcolorbox}
  5388. \caption{A sudoku game board and the corresponding colored graph.}
  5389. \label{fig:sudoku-graph}
  5390. \end{figure}
  5391. Some techniques for playing sudoku correspond to heuristics used in
  5392. graph coloring algorithms. For example, one of the basic techniques
  5393. for sudoku is called Pencil Marks. The idea is to use a process of
  5394. elimination to determine what numbers are no longer available for a
  5395. square and to write those numbers in the square (writing very
  5396. small). For example, if the number $1$ is assigned to a square, then
  5397. write the pencil mark $1$ in all the squares in the same row, column,
  5398. and region to indicate that $1$ is no longer an option for those other
  5399. squares.
  5400. %
  5401. The Pencil Marks technique corresponds to the notion of
  5402. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5403. saturation of a vertex, in sudoku terms, is the set of numbers that
  5404. are no longer available. In graph terminology, we have the following
  5405. definition:
  5406. \begin{equation*}
  5407. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5408. \text{ and } \mathrm{color}(v) = c \}
  5409. \end{equation*}
  5410. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5411. edge with $u$.
  5412. The Pencil Marks technique leads to a simple strategy for filling in
  5413. numbers: if there is a square with only one possible number left, then
  5414. choose that number! But what if there are no squares with only one
  5415. possibility left? One brute-force approach is to try them all: choose
  5416. the first one, and if that ultimately leads to a solution, great. If
  5417. not, backtrack and choose the next possibility. One good thing about
  5418. Pencil Marks is that it reduces the degree of branching in the search
  5419. tree. Nevertheless, backtracking can be terribly time consuming. One
  5420. way to reduce the amount of backtracking is to use the
  5421. most-constrained-first heuristic (aka minimum remaining
  5422. values)~\citep{Russell2003}. That is, in choosing a square, always
  5423. choose one with the fewest possibilities left (the vertex with the
  5424. highest saturation). The idea is that choosing highly constrained
  5425. squares earlier rather than later is better, because later on there may
  5426. not be any possibilities left in the highly saturated squares.
  5427. However, register allocation is easier than sudoku, because the
  5428. register allocator can fall back to assigning variables to stack
  5429. locations when the registers run out. Thus, it makes sense to replace
  5430. backtracking with greedy search: make the best choice at the time and
  5431. keep going. We still wish to minimize the number of colors needed, so
  5432. we use the most-constrained-first heuristic in the greedy search.
  5433. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5434. algorithm for register allocation based on saturation and the
  5435. most-constrained-first heuristic. It is roughly equivalent to the
  5436. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  5437. Just as in sudoku, the algorithm represents colors with integers. The
  5438. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  5439. for register allocation. The integers $k$ and larger correspond to
  5440. stack locations. The registers that are not used for register
  5441. allocation, such as \code{rax}, are assigned to negative integers. In
  5442. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  5443. %% One might wonder why we include registers at all in the liveness
  5444. %% analysis and interference graph. For example, we never allocate a
  5445. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5446. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5447. %% to use register for passing arguments to functions, it will be
  5448. %% necessary for those registers to appear in the interference graph
  5449. %% because those registers will also be assigned to variables, and we
  5450. %% don't want those two uses to encroach on each other. Regarding
  5451. %% registers such as \code{rax} and \code{rsp} that are not used for
  5452. %% variables, we could omit them from the interference graph but that
  5453. %% would require adding special cases to our algorithm, which would
  5454. %% complicate the logic for little gain.
  5455. \begin{figure}[btp]
  5456. \begin{tcolorbox}[colback=white]
  5457. \centering
  5458. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5459. Algorithm: DSATUR
  5460. Input: A graph |$G$|
  5461. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5462. |$W \gets \mathrm{vertices}(G)$|
  5463. while |$W \neq \emptyset$| do
  5464. pick a vertex |$u$| from |$W$| with the highest saturation,
  5465. breaking ties randomly
  5466. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5467. |$\mathrm{color}[u] \gets c$|
  5468. |$W \gets W - \{u\}$|
  5469. \end{lstlisting}
  5470. \end{tcolorbox}
  5471. \caption{The saturation-based greedy graph coloring algorithm.}
  5472. \label{fig:satur-algo}
  5473. \end{figure}
  5474. {\if\edition\racketEd
  5475. With the DSATUR algorithm in hand, let us return to the running
  5476. example and consider how to color the interference graph shown in
  5477. figure~\ref{fig:interfere}.
  5478. %
  5479. We start by assigning each register node to its own color. For
  5480. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  5481. assigned $-2$. The variables are not yet colored, so they are
  5482. annotated with a dash. We then update the saturation for vertices that
  5483. are adjacent to a register, obtaining the following annotated
  5484. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  5485. it interferes with both \code{rax} and \code{rsp}.
  5486. \[
  5487. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5488. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5489. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5490. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5491. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5492. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5493. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5494. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5495. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5496. \draw (t1) to (rax);
  5497. \draw (t1) to (z);
  5498. \draw (z) to (y);
  5499. \draw (z) to (w);
  5500. \draw (x) to (w);
  5501. \draw (y) to (w);
  5502. \draw (v) to (w);
  5503. \draw (v) to (rsp);
  5504. \draw (w) to (rsp);
  5505. \draw (x) to (rsp);
  5506. \draw (y) to (rsp);
  5507. \path[-.,bend left=15] (z) edge node {} (rsp);
  5508. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5509. \draw (rax) to (rsp);
  5510. \end{tikzpicture}
  5511. \]
  5512. The algorithm says to select a maximally saturated vertex. So, we pick
  5513. $\ttm{t}$ and color it with the first available integer, which is
  5514. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5515. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5516. \[
  5517. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5518. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5519. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5520. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5521. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5522. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5523. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5524. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5525. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5526. \draw (t1) to (rax);
  5527. \draw (t1) to (z);
  5528. \draw (z) to (y);
  5529. \draw (z) to (w);
  5530. \draw (x) to (w);
  5531. \draw (y) to (w);
  5532. \draw (v) to (w);
  5533. \draw (v) to (rsp);
  5534. \draw (w) to (rsp);
  5535. \draw (x) to (rsp);
  5536. \draw (y) to (rsp);
  5537. \path[-.,bend left=15] (z) edge node {} (rsp);
  5538. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5539. \draw (rax) to (rsp);
  5540. \end{tikzpicture}
  5541. \]
  5542. We repeat the process, selecting a maximally saturated vertex,
  5543. choosing \code{z}, and coloring it with the first available number, which
  5544. is $1$. We add $1$ to the saturation for the neighboring vertices
  5545. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5546. \[
  5547. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5548. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5549. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5550. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5551. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5552. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5553. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5554. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5555. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5556. \draw (t1) to (rax);
  5557. \draw (t1) to (z);
  5558. \draw (z) to (y);
  5559. \draw (z) to (w);
  5560. \draw (x) to (w);
  5561. \draw (y) to (w);
  5562. \draw (v) to (w);
  5563. \draw (v) to (rsp);
  5564. \draw (w) to (rsp);
  5565. \draw (x) to (rsp);
  5566. \draw (y) to (rsp);
  5567. \path[-.,bend left=15] (z) edge node {} (rsp);
  5568. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5569. \draw (rax) to (rsp);
  5570. \end{tikzpicture}
  5571. \]
  5572. The most saturated vertices are now \code{w} and \code{y}. We color
  5573. \code{w} with the first available color, which is $0$.
  5574. \[
  5575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5576. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5577. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5578. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5579. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5580. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5581. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5582. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5583. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5584. \draw (t1) to (rax);
  5585. \draw (t1) to (z);
  5586. \draw (z) to (y);
  5587. \draw (z) to (w);
  5588. \draw (x) to (w);
  5589. \draw (y) to (w);
  5590. \draw (v) to (w);
  5591. \draw (v) to (rsp);
  5592. \draw (w) to (rsp);
  5593. \draw (x) to (rsp);
  5594. \draw (y) to (rsp);
  5595. \path[-.,bend left=15] (z) edge node {} (rsp);
  5596. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5597. \draw (rax) to (rsp);
  5598. \end{tikzpicture}
  5599. \]
  5600. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5601. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5602. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5603. and \code{z}, whose colors are $0$ and $1$ respectively.
  5604. \[
  5605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5606. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5607. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5608. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5609. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5610. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5611. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5612. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5613. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5614. \draw (t1) to (rax);
  5615. \draw (t1) to (z);
  5616. \draw (z) to (y);
  5617. \draw (z) to (w);
  5618. \draw (x) to (w);
  5619. \draw (y) to (w);
  5620. \draw (v) to (w);
  5621. \draw (v) to (rsp);
  5622. \draw (w) to (rsp);
  5623. \draw (x) to (rsp);
  5624. \draw (y) to (rsp);
  5625. \path[-.,bend left=15] (z) edge node {} (rsp);
  5626. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5627. \draw (rax) to (rsp);
  5628. \end{tikzpicture}
  5629. \]
  5630. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5631. \[
  5632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5634. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5635. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5636. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5637. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5638. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5639. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5640. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5641. \draw (t1) to (rax);
  5642. \draw (t1) to (z);
  5643. \draw (z) to (y);
  5644. \draw (z) to (w);
  5645. \draw (x) to (w);
  5646. \draw (y) to (w);
  5647. \draw (v) to (w);
  5648. \draw (v) to (rsp);
  5649. \draw (w) to (rsp);
  5650. \draw (x) to (rsp);
  5651. \draw (y) to (rsp);
  5652. \path[-.,bend left=15] (z) edge node {} (rsp);
  5653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5654. \draw (rax) to (rsp);
  5655. \end{tikzpicture}
  5656. \]
  5657. In the last step of the algorithm, we color \code{x} with $1$.
  5658. \[
  5659. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5660. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5661. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5662. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5663. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5664. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5665. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5666. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5667. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5668. \draw (t1) to (rax);
  5669. \draw (t1) to (z);
  5670. \draw (z) to (y);
  5671. \draw (z) to (w);
  5672. \draw (x) to (w);
  5673. \draw (y) to (w);
  5674. \draw (v) to (w);
  5675. \draw (v) to (rsp);
  5676. \draw (w) to (rsp);
  5677. \draw (x) to (rsp);
  5678. \draw (y) to (rsp);
  5679. \path[-.,bend left=15] (z) edge node {} (rsp);
  5680. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5681. \draw (rax) to (rsp);
  5682. \end{tikzpicture}
  5683. \]
  5684. So, we obtain the following coloring:
  5685. \[
  5686. \{
  5687. \ttm{rax} \mapsto -1,
  5688. \ttm{rsp} \mapsto -2,
  5689. \ttm{t} \mapsto 0,
  5690. \ttm{z} \mapsto 1,
  5691. \ttm{x} \mapsto 1,
  5692. \ttm{y} \mapsto 2,
  5693. \ttm{w} \mapsto 0,
  5694. \ttm{v} \mapsto 1
  5695. \}
  5696. \]
  5697. \fi}
  5698. %
  5699. {\if\edition\pythonEd
  5700. %
  5701. With the DSATUR algorithm in hand, let us return to the running
  5702. example and consider how to color the interference graph in
  5703. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5704. to indicate that it has not yet been assigned a color. The saturation
  5705. sets are also shown for each node; all of them start as the empty set.
  5706. (We do not include the register nodes in the graph below because there
  5707. were no interference edges involving registers in this program, but in
  5708. general there can be.)
  5709. %
  5710. \[
  5711. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5712. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5713. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5714. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5715. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5716. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5717. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5718. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5719. \draw (t0) to (t1);
  5720. \draw (t0) to (z);
  5721. \draw (z) to (y);
  5722. \draw (z) to (w);
  5723. \draw (x) to (w);
  5724. \draw (y) to (w);
  5725. \draw (v) to (w);
  5726. \end{tikzpicture}
  5727. \]
  5728. The algorithm says to select a maximally saturated vertex, but they
  5729. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5730. then color it with the first available integer, which is $0$. We mark
  5731. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5732. they interfere with $\ttm{tmp\_0}$.
  5733. \[
  5734. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5735. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5736. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5737. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5738. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5739. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5740. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5741. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5742. \draw (t0) to (t1);
  5743. \draw (t0) to (z);
  5744. \draw (z) to (y);
  5745. \draw (z) to (w);
  5746. \draw (x) to (w);
  5747. \draw (y) to (w);
  5748. \draw (v) to (w);
  5749. \end{tikzpicture}
  5750. \]
  5751. We repeat the process. The most saturated vertices are \code{z} and
  5752. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5753. available number, which is $1$. We add $1$ to the saturation for the
  5754. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5755. \[
  5756. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5757. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5758. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5759. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5760. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5761. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5762. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5763. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5764. \draw (t0) to (t1);
  5765. \draw (t0) to (z);
  5766. \draw (z) to (y);
  5767. \draw (z) to (w);
  5768. \draw (x) to (w);
  5769. \draw (y) to (w);
  5770. \draw (v) to (w);
  5771. \end{tikzpicture}
  5772. \]
  5773. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5774. \code{y}. We color \code{w} with the first available color, which
  5775. is $0$.
  5776. \[
  5777. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5778. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5779. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5780. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5781. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5782. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5783. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5784. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5785. \draw (t0) to (t1);
  5786. \draw (t0) to (z);
  5787. \draw (z) to (y);
  5788. \draw (z) to (w);
  5789. \draw (x) to (w);
  5790. \draw (y) to (w);
  5791. \draw (v) to (w);
  5792. \end{tikzpicture}
  5793. \]
  5794. Now \code{y} is the most saturated, so we color it with $2$.
  5795. \[
  5796. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5797. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5798. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5799. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5800. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5801. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5802. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5803. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5804. \draw (t0) to (t1);
  5805. \draw (t0) to (z);
  5806. \draw (z) to (y);
  5807. \draw (z) to (w);
  5808. \draw (x) to (w);
  5809. \draw (y) to (w);
  5810. \draw (v) to (w);
  5811. \end{tikzpicture}
  5812. \]
  5813. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5814. We choose to color \code{v} with $1$.
  5815. \[
  5816. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5817. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5818. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5819. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5820. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5821. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5822. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5823. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5824. \draw (t0) to (t1);
  5825. \draw (t0) to (z);
  5826. \draw (z) to (y);
  5827. \draw (z) to (w);
  5828. \draw (x) to (w);
  5829. \draw (y) to (w);
  5830. \draw (v) to (w);
  5831. \end{tikzpicture}
  5832. \]
  5833. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5834. \[
  5835. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5836. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5837. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5838. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5839. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5840. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5841. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5842. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5843. \draw (t0) to (t1);
  5844. \draw (t0) to (z);
  5845. \draw (z) to (y);
  5846. \draw (z) to (w);
  5847. \draw (x) to (w);
  5848. \draw (y) to (w);
  5849. \draw (v) to (w);
  5850. \end{tikzpicture}
  5851. \]
  5852. So, we obtain the following coloring:
  5853. \[
  5854. \{ \ttm{tmp\_0} \mapsto 0,
  5855. \ttm{tmp\_1} \mapsto 1,
  5856. \ttm{z} \mapsto 1,
  5857. \ttm{x} \mapsto 1,
  5858. \ttm{y} \mapsto 2,
  5859. \ttm{w} \mapsto 0,
  5860. \ttm{v} \mapsto 1 \}
  5861. \]
  5862. \fi}
  5863. We recommend creating an auxiliary function named \code{color\_graph}
  5864. that takes an interference graph and a list of all the variables in
  5865. the program. This function should return a mapping of variables to
  5866. their colors (represented as natural numbers). By creating this helper
  5867. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5868. when we add support for functions.
  5869. To prioritize the processing of highly saturated nodes inside the
  5870. \code{color\_graph} function, we recommend using the priority queue
  5871. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5872. addition, you will need to maintain a mapping from variables to their
  5873. handles in the priority queue so that you can notify the priority
  5874. queue when their saturation changes.}
  5875. {\if\edition\racketEd
  5876. \begin{figure}[tp]
  5877. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5878. \small
  5879. \begin{tcolorbox}[title=Priority Queue]
  5880. A \emph{priority queue} is a collection of items in which the
  5881. removal of items is governed by priority. In a min queue,
  5882. lower priority items are removed first. An implementation is in
  5883. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5884. queue} \index{subject}{minimum priority queue}
  5885. \begin{description}
  5886. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5887. priority queue that uses the $\itm{cmp}$ predicate to determine
  5888. whether its first argument has lower or equal priority to its
  5889. second argument.
  5890. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5891. items in the queue.
  5892. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5893. the item into the queue and returns a handle for the item in the
  5894. queue.
  5895. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5896. the lowest priority.
  5897. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5898. notifies the queue that the priority has decreased for the item
  5899. associated with the given handle.
  5900. \end{description}
  5901. \end{tcolorbox}
  5902. %\end{wrapfigure}
  5903. \caption{The priority queue data structure.}
  5904. \label{fig:priority-queue}
  5905. \end{figure}
  5906. \fi}
  5907. With the coloring complete, we finalize the assignment of variables to
  5908. registers and stack locations. We map the first $k$ colors to the $k$
  5909. registers and the rest of the colors to stack locations. Suppose for
  5910. the moment that we have just one register to use for register
  5911. allocation, \key{rcx}. Then we have the following map from colors to
  5912. locations.
  5913. \[
  5914. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5915. \]
  5916. Composing this mapping with the coloring, we arrive at the following
  5917. assignment of variables to locations.
  5918. {\if\edition\racketEd
  5919. \begin{gather*}
  5920. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5921. \ttm{w} \mapsto \key{\%rcx}, \,
  5922. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5923. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5924. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5925. \ttm{t} \mapsto \key{\%rcx} \}
  5926. \end{gather*}
  5927. \fi}
  5928. {\if\edition\pythonEd
  5929. \begin{gather*}
  5930. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5931. \ttm{w} \mapsto \key{\%rcx}, \,
  5932. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5933. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5934. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5935. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5936. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5937. \end{gather*}
  5938. \fi}
  5939. Adapt the code from the \code{assign\_homes} pass
  5940. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5941. assigned location. Applying this assignment to our running
  5942. example shown next, on the left, yields the program on the right.
  5943. % why frame size of 32? -JGS
  5944. \begin{center}
  5945. {\if\edition\racketEd
  5946. \begin{minipage}{0.3\textwidth}
  5947. \begin{lstlisting}
  5948. movq $1, v
  5949. movq $42, w
  5950. movq v, x
  5951. addq $7, x
  5952. movq x, y
  5953. movq x, z
  5954. addq w, z
  5955. movq y, t
  5956. negq t
  5957. movq z, %rax
  5958. addq t, %rax
  5959. jmp conclusion
  5960. \end{lstlisting}
  5961. \end{minipage}
  5962. $\Rightarrow\qquad$
  5963. \begin{minipage}{0.45\textwidth}
  5964. \begin{lstlisting}
  5965. movq $1, -8(%rbp)
  5966. movq $42, %rcx
  5967. movq -8(%rbp), -8(%rbp)
  5968. addq $7, -8(%rbp)
  5969. movq -8(%rbp), -16(%rbp)
  5970. movq -8(%rbp), -8(%rbp)
  5971. addq %rcx, -8(%rbp)
  5972. movq -16(%rbp), %rcx
  5973. negq %rcx
  5974. movq -8(%rbp), %rax
  5975. addq %rcx, %rax
  5976. jmp conclusion
  5977. \end{lstlisting}
  5978. \end{minipage}
  5979. \fi}
  5980. {\if\edition\pythonEd
  5981. \begin{minipage}{0.3\textwidth}
  5982. \begin{lstlisting}
  5983. movq $1, v
  5984. movq $42, w
  5985. movq v, x
  5986. addq $7, x
  5987. movq x, y
  5988. movq x, z
  5989. addq w, z
  5990. movq y, tmp_0
  5991. negq tmp_0
  5992. movq z, tmp_1
  5993. addq tmp_0, tmp_1
  5994. movq tmp_1, %rdi
  5995. callq print_int
  5996. \end{lstlisting}
  5997. \end{minipage}
  5998. $\Rightarrow\qquad$
  5999. \begin{minipage}{0.45\textwidth}
  6000. \begin{lstlisting}
  6001. movq $1, -8(%rbp)
  6002. movq $42, %rcx
  6003. movq -8(%rbp), -8(%rbp)
  6004. addq $7, -8(%rbp)
  6005. movq -8(%rbp), -16(%rbp)
  6006. movq -8(%rbp), -8(%rbp)
  6007. addq %rcx, -8(%rbp)
  6008. movq -16(%rbp), %rcx
  6009. negq %rcx
  6010. movq -8(%rbp), -8(%rbp)
  6011. addq %rcx, -8(%rbp)
  6012. movq -8(%rbp), %rdi
  6013. callq print_int
  6014. \end{lstlisting}
  6015. \end{minipage}
  6016. \fi}
  6017. \end{center}
  6018. \begin{exercise}\normalfont\normalsize
  6019. Implement the \code{allocate\_registers} pass.
  6020. Create five programs that exercise all aspects of the register
  6021. allocation algorithm, including spilling variables to the stack.
  6022. %
  6023. {\if\edition\racketEd
  6024. Replace \code{assign\_homes} in the list of \code{passes} in the
  6025. \code{run-tests.rkt} script with the three new passes:
  6026. \code{uncover\_live}, \code{build\_interference}, and
  6027. \code{allocate\_registers}.
  6028. Temporarily remove the call to \code{compiler-tests}.
  6029. Run the script to test the register allocator.
  6030. \fi}
  6031. %
  6032. {\if\edition\pythonEd
  6033. Run the \code{run-tests.py} script to to check whether the
  6034. output programs produce the same result as the input programs.
  6035. \fi}
  6036. \end{exercise}
  6037. \section{Patch Instructions}
  6038. \label{sec:patch-instructions}
  6039. The remaining step in the compilation to x86 is to ensure that the
  6040. instructions have at most one argument that is a memory access.
  6041. %
  6042. In the running example, the instruction \code{movq -8(\%rbp),
  6043. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6044. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6045. then move \code{rax} into \code{-16(\%rbp)}.
  6046. %
  6047. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6048. problematic, but they can simply be deleted. In general, we recommend
  6049. deleting all the trivial moves whose source and destination are the
  6050. same location.
  6051. %
  6052. The following is the output of \code{patch\_instructions} on the
  6053. running example.
  6054. \begin{center}
  6055. {\if\edition\racketEd
  6056. \begin{minipage}{0.4\textwidth}
  6057. \begin{lstlisting}
  6058. movq $1, -8(%rbp)
  6059. movq $42, %rcx
  6060. movq -8(%rbp), -8(%rbp)
  6061. addq $7, -8(%rbp)
  6062. movq -8(%rbp), -16(%rbp)
  6063. movq -8(%rbp), -8(%rbp)
  6064. addq %rcx, -8(%rbp)
  6065. movq -16(%rbp), %rcx
  6066. negq %rcx
  6067. movq -8(%rbp), %rax
  6068. addq %rcx, %rax
  6069. jmp conclusion
  6070. \end{lstlisting}
  6071. \end{minipage}
  6072. $\Rightarrow\qquad$
  6073. \begin{minipage}{0.45\textwidth}
  6074. \begin{lstlisting}
  6075. movq $1, -8(%rbp)
  6076. movq $42, %rcx
  6077. addq $7, -8(%rbp)
  6078. movq -8(%rbp), %rax
  6079. movq %rax, -16(%rbp)
  6080. addq %rcx, -8(%rbp)
  6081. movq -16(%rbp), %rcx
  6082. negq %rcx
  6083. movq -8(%rbp), %rax
  6084. addq %rcx, %rax
  6085. jmp conclusion
  6086. \end{lstlisting}
  6087. \end{minipage}
  6088. \fi}
  6089. {\if\edition\pythonEd
  6090. \begin{minipage}{0.4\textwidth}
  6091. \begin{lstlisting}
  6092. movq $1, -8(%rbp)
  6093. movq $42, %rcx
  6094. movq -8(%rbp), -8(%rbp)
  6095. addq $7, -8(%rbp)
  6096. movq -8(%rbp), -16(%rbp)
  6097. movq -8(%rbp), -8(%rbp)
  6098. addq %rcx, -8(%rbp)
  6099. movq -16(%rbp), %rcx
  6100. negq %rcx
  6101. movq -8(%rbp), -8(%rbp)
  6102. addq %rcx, -8(%rbp)
  6103. movq -8(%rbp), %rdi
  6104. callq print_int
  6105. \end{lstlisting}
  6106. \end{minipage}
  6107. $\Rightarrow\qquad$
  6108. \begin{minipage}{0.45\textwidth}
  6109. \begin{lstlisting}
  6110. movq $1, -8(%rbp)
  6111. movq $42, %rcx
  6112. addq $7, -8(%rbp)
  6113. movq -8(%rbp), %rax
  6114. movq %rax, -16(%rbp)
  6115. addq %rcx, -8(%rbp)
  6116. movq -16(%rbp), %rcx
  6117. negq %rcx
  6118. addq %rcx, -8(%rbp)
  6119. movq -8(%rbp), %rdi
  6120. callq print_int
  6121. \end{lstlisting}
  6122. \end{minipage}
  6123. \fi}
  6124. \end{center}
  6125. \begin{exercise}\normalfont\normalsize
  6126. %
  6127. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6128. %
  6129. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6130. %in the \code{run-tests.rkt} script.
  6131. %
  6132. Run the script to test the \code{patch\_instructions} pass.
  6133. \end{exercise}
  6134. \section{Prelude and Conclusion}
  6135. \label{sec:print-x86-reg-alloc}
  6136. \index{subject}{calling conventions}
  6137. \index{subject}{prelude}\index{subject}{conclusion}
  6138. Recall that this pass generates the prelude and conclusion
  6139. instructions to satisfy the x86 calling conventions
  6140. (section~\ref{sec:calling-conventions}). With the addition of the
  6141. register allocator, the callee-saved registers used by the register
  6142. allocator must be saved in the prelude and restored in the conclusion.
  6143. In the \code{allocate\_registers} pass,
  6144. %
  6145. \racket{add an entry to the \itm{info}
  6146. of \code{X86Program} named \code{used\_callee}}
  6147. %
  6148. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6149. %
  6150. that stores the set of callee-saved registers that were assigned to
  6151. variables. The \code{prelude\_and\_conclusion} pass can then access
  6152. this information to decide which callee-saved registers need to be
  6153. saved and restored.
  6154. %
  6155. When calculating the amount to adjust the \code{rsp} in the prelude,
  6156. make sure to take into account the space used for saving the
  6157. callee-saved registers. Also, remember that the frame needs to be a
  6158. multiple of 16 bytes! We recommend using the following equation for
  6159. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6160. of spilled variables and $C$ be the number of callee-saved registers
  6161. that were allocated to variables. The $\itm{align}$ function rounds a
  6162. number up to the nearest 16 bytes.
  6163. \[
  6164. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6165. \]
  6166. The reason we subtract $8\itm{C}$ in this equation is that the
  6167. prelude uses \code{pushq} to save each of the callee-saved registers,
  6168. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6169. \racket{An overview of all the passes involved in register
  6170. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6171. {\if\edition\racketEd
  6172. \begin{figure}[tbp]
  6173. \begin{tcolorbox}[colback=white]
  6174. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6175. \node (Lvar) at (0,2) {\large \LangVar{}};
  6176. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6177. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6178. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6179. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6180. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6181. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6182. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6183. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6184. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6185. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6186. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6187. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  6188. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6189. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6190. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6191. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6192. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6193. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6194. \end{tikzpicture}
  6195. \end{tcolorbox}
  6196. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6197. \label{fig:reg-alloc-passes}
  6198. \end{figure}
  6199. \fi}
  6200. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6201. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6202. use of registers and the stack, we limit the register allocator for
  6203. this example to use just two registers: \code{rbx} and \code{rcx}. In
  6204. the prelude\index{subject}{prelude} of the \code{main} function, we
  6205. push \code{rbx} onto the stack because it is a callee-saved register
  6206. and it was assigned to a variable by the register allocator. We
  6207. subtract \code{8} from the \code{rsp} at the end of the prelude to
  6208. reserve space for the one spilled variable. After that subtraction,
  6209. the \code{rsp} is aligned to 16 bytes.
  6210. Moving on to the program proper, we see how the registers were
  6211. allocated.
  6212. %
  6213. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  6214. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  6215. %
  6216. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6217. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6218. were assigned to \code{rbx}.}
  6219. %
  6220. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  6221. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6222. callee-save register \code{rbx} onto the stack. The spilled variables
  6223. must be placed lower on the stack than the saved callee-save
  6224. registers, so in this case \racket{\code{w}}\python{z} is placed at
  6225. \code{-16(\%rbp)}.
  6226. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6227. done in the prelude. We move the stack pointer up by \code{8} bytes
  6228. (the room for spilled variables), then pop the old values of
  6229. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6230. \code{retq} to return control to the operating system.
  6231. \begin{figure}[tbp]
  6232. \begin{minipage}{0.55\textwidth}
  6233. \begin{tcolorbox}[colback=white]
  6234. % var_test_28.rkt
  6235. % (use-minimal-set-of-registers! #t)
  6236. % and only rbx rcx
  6237. % tmp 0 rbx
  6238. % z 1 rcx
  6239. % y 0 rbx
  6240. % w 2 16(%rbp)
  6241. % v 0 rbx
  6242. % x 0 rbx
  6243. {\if\edition\racketEd
  6244. \begin{lstlisting}
  6245. start:
  6246. movq $1, %rbx
  6247. movq $42, -16(%rbp)
  6248. addq $7, %rbx
  6249. movq %rbx, %rcx
  6250. addq -16(%rbp), %rcx
  6251. negq %rbx
  6252. movq %rcx, %rax
  6253. addq %rbx, %rax
  6254. jmp conclusion
  6255. .globl main
  6256. main:
  6257. pushq %rbp
  6258. movq %rsp, %rbp
  6259. pushq %rbx
  6260. subq $8, %rsp
  6261. jmp start
  6262. conclusion:
  6263. addq $8, %rsp
  6264. popq %rbx
  6265. popq %rbp
  6266. retq
  6267. \end{lstlisting}
  6268. \fi}
  6269. {\if\edition\pythonEd
  6270. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6271. \begin{lstlisting}
  6272. .globl main
  6273. main:
  6274. pushq %rbp
  6275. movq %rsp, %rbp
  6276. pushq %rbx
  6277. subq $8, %rsp
  6278. movq $1, %rcx
  6279. movq $42, %rbx
  6280. addq $7, %rcx
  6281. movq %rcx, -16(%rbp)
  6282. addq %rbx, -16(%rbp)
  6283. negq %rcx
  6284. movq -16(%rbp), %rbx
  6285. addq %rcx, %rbx
  6286. movq %rbx, %rdi
  6287. callq print_int
  6288. addq $8, %rsp
  6289. popq %rbx
  6290. popq %rbp
  6291. retq
  6292. \end{lstlisting}
  6293. \fi}
  6294. \end{tcolorbox}
  6295. \end{minipage}
  6296. \caption{The x86 output from the running example
  6297. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6298. and \code{rcx}.}
  6299. \label{fig:running-example-x86}
  6300. \end{figure}
  6301. \begin{exercise}\normalfont\normalsize
  6302. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6303. %
  6304. \racket{
  6305. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6306. list of passes and the call to \code{compiler-tests}.}
  6307. %
  6308. Run the script to test the complete compiler for \LangVar{} that
  6309. performs register allocation.
  6310. \end{exercise}
  6311. \section{Challenge: Move Biasing}
  6312. \label{sec:move-biasing}
  6313. \index{subject}{move biasing}
  6314. This section describes an enhancement to the register allocator,
  6315. called move biasing, for students who are looking for an extra
  6316. challenge.
  6317. {\if\edition\racketEd
  6318. To motivate the need for move biasing we return to the running example,
  6319. but this time we use all the general purpose registers. So, we have
  6320. the following mapping of color numbers to registers.
  6321. \[
  6322. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6323. \]
  6324. Using the same assignment of variables to color numbers that was
  6325. produced by the register allocator described in the last section, we
  6326. get the following program.
  6327. \begin{center}
  6328. \begin{minipage}{0.3\textwidth}
  6329. \begin{lstlisting}
  6330. movq $1, v
  6331. movq $42, w
  6332. movq v, x
  6333. addq $7, x
  6334. movq x, y
  6335. movq x, z
  6336. addq w, z
  6337. movq y, t
  6338. negq t
  6339. movq z, %rax
  6340. addq t, %rax
  6341. jmp conclusion
  6342. \end{lstlisting}
  6343. \end{minipage}
  6344. $\Rightarrow\qquad$
  6345. \begin{minipage}{0.45\textwidth}
  6346. \begin{lstlisting}
  6347. movq $1, %rdx
  6348. movq $42, %rcx
  6349. movq %rdx, %rdx
  6350. addq $7, %rdx
  6351. movq %rdx, %rsi
  6352. movq %rdx, %rdx
  6353. addq %rcx, %rdx
  6354. movq %rsi, %rcx
  6355. negq %rcx
  6356. movq %rdx, %rax
  6357. addq %rcx, %rax
  6358. jmp conclusion
  6359. \end{lstlisting}
  6360. \end{minipage}
  6361. \end{center}
  6362. In this output code there are two \key{movq} instructions that
  6363. can be removed because their source and target are the same. However,
  6364. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6365. register, we could instead remove three \key{movq} instructions. We
  6366. can accomplish this by taking into account which variables appear in
  6367. \key{movq} instructions with which other variables.
  6368. \fi}
  6369. {\if\edition\pythonEd
  6370. %
  6371. To motivate the need for move biasing we return to the running example
  6372. and recall that in section~\ref{sec:patch-instructions} we were able to
  6373. remove three trivial move instructions from the running
  6374. example. However, we could remove another trivial move if we were able
  6375. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6376. We say that two variables $p$ and $q$ are \emph{move
  6377. related}\index{subject}{move related} if they participate together in
  6378. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6379. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  6380. if there are multiple variables with the same saturation, prefer
  6381. variables that can be assigned to a color that is the same as the
  6382. color of a move-related variable. Furthermore, when the register
  6383. allocator chooses a color for a variable, it should prefer a color
  6384. that has already been used for a move-related variable (assuming that
  6385. they do not interfere). Of course, this preference should not override
  6386. the preference for registers over stack locations. So, this preference
  6387. should be used as a tie breaker in choosing between registers and
  6388. in choosing between stack locations.
  6389. We recommend representing the move relationships in a graph, similarly
  6390. to how we represented interference. The following is the \emph{move
  6391. graph} for our running example.
  6392. {\if\edition\racketEd
  6393. \[
  6394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6395. \node (rax) at (0,0) {$\ttm{rax}$};
  6396. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6397. \node (t) at (0,2) {$\ttm{t}$};
  6398. \node (z) at (3,2) {$\ttm{z}$};
  6399. \node (x) at (6,2) {$\ttm{x}$};
  6400. \node (y) at (3,0) {$\ttm{y}$};
  6401. \node (w) at (6,0) {$\ttm{w}$};
  6402. \node (v) at (9,0) {$\ttm{v}$};
  6403. \draw (v) to (x);
  6404. \draw (x) to (y);
  6405. \draw (x) to (z);
  6406. \draw (y) to (t);
  6407. \end{tikzpicture}
  6408. \]
  6409. \fi}
  6410. %
  6411. {\if\edition\pythonEd
  6412. \[
  6413. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6414. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6415. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6416. \node (z) at (3,2) {$\ttm{z}$};
  6417. \node (x) at (6,2) {$\ttm{x}$};
  6418. \node (y) at (3,0) {$\ttm{y}$};
  6419. \node (w) at (6,0) {$\ttm{w}$};
  6420. \node (v) at (9,0) {$\ttm{v}$};
  6421. \draw (y) to (t0);
  6422. \draw (z) to (x);
  6423. \draw (z) to (t1);
  6424. \draw (x) to (y);
  6425. \draw (x) to (v);
  6426. \end{tikzpicture}
  6427. \]
  6428. \fi}
  6429. {\if\edition\racketEd
  6430. Now we replay the graph coloring, pausing to see the coloring of
  6431. \code{y}. Recall the following configuration. The most saturated vertices
  6432. were \code{w} and \code{y}.
  6433. \[
  6434. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6435. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6436. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6437. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6438. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6439. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6440. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6441. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6442. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6443. \draw (t1) to (rax);
  6444. \draw (t1) to (z);
  6445. \draw (z) to (y);
  6446. \draw (z) to (w);
  6447. \draw (x) to (w);
  6448. \draw (y) to (w);
  6449. \draw (v) to (w);
  6450. \draw (v) to (rsp);
  6451. \draw (w) to (rsp);
  6452. \draw (x) to (rsp);
  6453. \draw (y) to (rsp);
  6454. \path[-.,bend left=15] (z) edge node {} (rsp);
  6455. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6456. \draw (rax) to (rsp);
  6457. \end{tikzpicture}
  6458. \]
  6459. %
  6460. The last time, we chose to color \code{w} with $0$. This time, we see
  6461. that \code{w} is not move-related to any vertex, but \code{y} is
  6462. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6463. the same color as \code{t}.
  6464. \[
  6465. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6466. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6467. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6468. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6469. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6470. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6471. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6472. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6473. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6474. \draw (t1) to (rax);
  6475. \draw (t1) to (z);
  6476. \draw (z) to (y);
  6477. \draw (z) to (w);
  6478. \draw (x) to (w);
  6479. \draw (y) to (w);
  6480. \draw (v) to (w);
  6481. \draw (v) to (rsp);
  6482. \draw (w) to (rsp);
  6483. \draw (x) to (rsp);
  6484. \draw (y) to (rsp);
  6485. \path[-.,bend left=15] (z) edge node {} (rsp);
  6486. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6487. \draw (rax) to (rsp);
  6488. \end{tikzpicture}
  6489. \]
  6490. Now \code{w} is the most saturated, so we color it $2$.
  6491. \[
  6492. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6493. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6494. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6495. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6496. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6497. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6498. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6499. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6500. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6501. \draw (t1) to (rax);
  6502. \draw (t1) to (z);
  6503. \draw (z) to (y);
  6504. \draw (z) to (w);
  6505. \draw (x) to (w);
  6506. \draw (y) to (w);
  6507. \draw (v) to (w);
  6508. \draw (v) to (rsp);
  6509. \draw (w) to (rsp);
  6510. \draw (x) to (rsp);
  6511. \draw (y) to (rsp);
  6512. \path[-.,bend left=15] (z) edge node {} (rsp);
  6513. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6514. \draw (rax) to (rsp);
  6515. \end{tikzpicture}
  6516. \]
  6517. At this point, vertices \code{x} and \code{v} are most saturated, but
  6518. \code{x} is move related to \code{y} and \code{z}, so we color
  6519. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6520. \[
  6521. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6522. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6523. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6524. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6525. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6526. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6527. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6528. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6529. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6530. \draw (t1) to (rax);
  6531. \draw (t) to (z);
  6532. \draw (z) to (y);
  6533. \draw (z) to (w);
  6534. \draw (x) to (w);
  6535. \draw (y) to (w);
  6536. \draw (v) to (w);
  6537. \draw (v) to (rsp);
  6538. \draw (w) to (rsp);
  6539. \draw (x) to (rsp);
  6540. \draw (y) to (rsp);
  6541. \path[-.,bend left=15] (z) edge node {} (rsp);
  6542. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6543. \draw (rax) to (rsp);
  6544. \end{tikzpicture}
  6545. \]
  6546. \fi}
  6547. %
  6548. {\if\edition\pythonEd
  6549. Now we replay the graph coloring, pausing before the coloring of
  6550. \code{w}. Recall the following configuration. The most saturated vertices
  6551. were \code{tmp\_1}, \code{w}, and \code{y}.
  6552. \[
  6553. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6554. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6555. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6556. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6557. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6558. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6559. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6560. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6561. \draw (t0) to (t1);
  6562. \draw (t0) to (z);
  6563. \draw (z) to (y);
  6564. \draw (z) to (w);
  6565. \draw (x) to (w);
  6566. \draw (y) to (w);
  6567. \draw (v) to (w);
  6568. \end{tikzpicture}
  6569. \]
  6570. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6571. or \code{y}, but note that \code{w} is not move related to any
  6572. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6573. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6574. \code{y} and color it $0$, we can delete another move instruction.
  6575. \[
  6576. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6577. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6578. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6579. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6580. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6581. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6582. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6583. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6584. \draw (t0) to (t1);
  6585. \draw (t0) to (z);
  6586. \draw (z) to (y);
  6587. \draw (z) to (w);
  6588. \draw (x) to (w);
  6589. \draw (y) to (w);
  6590. \draw (v) to (w);
  6591. \end{tikzpicture}
  6592. \]
  6593. Now \code{w} is the most saturated, so we color it $2$.
  6594. \[
  6595. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6596. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6597. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6598. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6599. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6600. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6601. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6602. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6603. \draw (t0) to (t1);
  6604. \draw (t0) to (z);
  6605. \draw (z) to (y);
  6606. \draw (z) to (w);
  6607. \draw (x) to (w);
  6608. \draw (y) to (w);
  6609. \draw (v) to (w);
  6610. \end{tikzpicture}
  6611. \]
  6612. To finish the coloring, \code{x} and \code{v} get $0$ and
  6613. \code{tmp\_1} gets $1$.
  6614. \[
  6615. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6616. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6617. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6618. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6619. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6620. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6621. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6622. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6623. \draw (t0) to (t1);
  6624. \draw (t0) to (z);
  6625. \draw (z) to (y);
  6626. \draw (z) to (w);
  6627. \draw (x) to (w);
  6628. \draw (y) to (w);
  6629. \draw (v) to (w);
  6630. \end{tikzpicture}
  6631. \]
  6632. \fi}
  6633. So, we have the following assignment of variables to registers.
  6634. {\if\edition\racketEd
  6635. \begin{gather*}
  6636. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6637. \ttm{w} \mapsto \key{\%rsi}, \,
  6638. \ttm{x} \mapsto \key{\%rcx}, \,
  6639. \ttm{y} \mapsto \key{\%rcx}, \,
  6640. \ttm{z} \mapsto \key{\%rdx}, \,
  6641. \ttm{t} \mapsto \key{\%rcx} \}
  6642. \end{gather*}
  6643. \fi}
  6644. {\if\edition\pythonEd
  6645. \begin{gather*}
  6646. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6647. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6648. \ttm{x} \mapsto \key{\%rcx}, \,
  6649. \ttm{y} \mapsto \key{\%rcx}, \\
  6650. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6651. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6652. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6653. \end{gather*}
  6654. \fi}
  6655. %
  6656. We apply this register assignment to the running example shown next,
  6657. on the left, to obtain the code in the middle. The
  6658. \code{patch\_instructions} then deletes the trivial moves to obtain
  6659. the code on the right.
  6660. {\if\edition\racketEd
  6661. \begin{minipage}{0.25\textwidth}
  6662. \begin{lstlisting}
  6663. movq $1, v
  6664. movq $42, w
  6665. movq v, x
  6666. addq $7, x
  6667. movq x, y
  6668. movq x, z
  6669. addq w, z
  6670. movq y, t
  6671. negq t
  6672. movq z, %rax
  6673. addq t, %rax
  6674. jmp conclusion
  6675. \end{lstlisting}
  6676. \end{minipage}
  6677. $\Rightarrow\qquad$
  6678. \begin{minipage}{0.25\textwidth}
  6679. \begin{lstlisting}
  6680. movq $1, %rcx
  6681. movq $42, %rsi
  6682. movq %rcx, %rcx
  6683. addq $7, %rcx
  6684. movq %rcx, %rcx
  6685. movq %rcx, %rdx
  6686. addq %rsi, %rdx
  6687. movq %rcx, %rcx
  6688. negq %rcx
  6689. movq %rdx, %rax
  6690. addq %rcx, %rax
  6691. jmp conclusion
  6692. \end{lstlisting}
  6693. \end{minipage}
  6694. $\Rightarrow\qquad$
  6695. \begin{minipage}{0.25\textwidth}
  6696. \begin{lstlisting}
  6697. movq $1, %rcx
  6698. movq $42, %rsi
  6699. addq $7, %rcx
  6700. movq %rcx, %rdx
  6701. addq %rsi, %rdx
  6702. negq %rcx
  6703. movq %rdx, %rax
  6704. addq %rcx, %rax
  6705. jmp conclusion
  6706. \end{lstlisting}
  6707. \end{minipage}
  6708. \fi}
  6709. {\if\edition\pythonEd
  6710. \begin{minipage}{0.20\textwidth}
  6711. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6712. movq $1, v
  6713. movq $42, w
  6714. movq v, x
  6715. addq $7, x
  6716. movq x, y
  6717. movq x, z
  6718. addq w, z
  6719. movq y, tmp_0
  6720. negq tmp_0
  6721. movq z, tmp_1
  6722. addq tmp_0, tmp_1
  6723. movq tmp_1, %rdi
  6724. callq _print_int
  6725. \end{lstlisting}
  6726. \end{minipage}
  6727. ${\Rightarrow\qquad}$
  6728. \begin{minipage}{0.30\textwidth}
  6729. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6730. movq $1, %rcx
  6731. movq $42, -16(%rbp)
  6732. movq %rcx, %rcx
  6733. addq $7, %rcx
  6734. movq %rcx, %rcx
  6735. movq %rcx, -8(%rbp)
  6736. addq -16(%rbp), -8(%rbp)
  6737. movq %rcx, %rcx
  6738. negq %rcx
  6739. movq -8(%rbp), -8(%rbp)
  6740. addq %rcx, -8(%rbp)
  6741. movq -8(%rbp), %rdi
  6742. callq _print_int
  6743. \end{lstlisting}
  6744. \end{minipage}
  6745. ${\Rightarrow\qquad}$
  6746. \begin{minipage}{0.20\textwidth}
  6747. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6748. movq $1, %rcx
  6749. movq $42, -16(%rbp)
  6750. addq $7, %rcx
  6751. movq %rcx, -8(%rbp)
  6752. movq -16(%rbp), %rax
  6753. addq %rax, -8(%rbp)
  6754. negq %rcx
  6755. addq %rcx, -8(%rbp)
  6756. movq -8(%rbp), %rdi
  6757. callq print_int
  6758. \end{lstlisting}
  6759. \end{minipage}
  6760. \fi}
  6761. \begin{exercise}\normalfont\normalsize
  6762. Change your implementation of \code{allocate\_registers} to take move
  6763. biasing into account. Create two new tests that include at least one
  6764. opportunity for move biasing, and visually inspect the output x86
  6765. programs to make sure that your move biasing is working properly. Make
  6766. sure that your compiler still passes all the tests.
  6767. \end{exercise}
  6768. %To do: another neat challenge would be to do
  6769. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6770. %% \subsection{Output of the Running Example}
  6771. %% \label{sec:reg-alloc-output}
  6772. % challenge: prioritize variables based on execution frequencies
  6773. % and the number of uses of a variable
  6774. % challenge: enhance the coloring algorithm using Chaitin's
  6775. % approach of prioritizing high-degree variables
  6776. % by removing low-degree variables (coloring them later)
  6777. % from the interference graph
  6778. \section{Further Reading}
  6779. \label{sec:register-allocation-further-reading}
  6780. Early register allocation algorithms were developed for Fortran
  6781. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6782. of graph coloring began in the late 1970s and early 1980s with the
  6783. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6784. algorithm is based on the following observation of
  6785. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6786. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6787. $v$ removed is also $k$ colorable. To see why, suppose that the
  6788. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6789. different colors, but because there are fewer than $k$ neighbors, there
  6790. will be one or more colors left over to use for coloring $v$ in $G$.
  6791. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6792. less than $k$ from the graph and recursively colors the rest of the
  6793. graph. Upon returning from the recursion, it colors $v$ with one of
  6794. the available colors and returns. \citet{Chaitin:1982vn} augments
  6795. this algorithm to handle spilling as follows. If there are no vertices
  6796. of degree lower than $k$ then pick a vertex at random, spill it,
  6797. remove it from the graph, and proceed recursively to color the rest of
  6798. the graph.
  6799. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6800. move-related and that don't interfere with each other, in a process
  6801. called \emph{coalescing}. Although coalescing decreases the number of
  6802. moves, it can make the graph more difficult to
  6803. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6804. which two variables are merged only if they have fewer than $k$
  6805. neighbors of high degree. \citet{George:1996aa} observed that
  6806. conservative coalescing is sometimes too conservative and made it more
  6807. aggressive by iterating the coalescing with the removal of low-degree
  6808. vertices.
  6809. %
  6810. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6811. also proposed \emph{biased coloring}, in which a variable is assigned to
  6812. the same color as another move-related variable if possible, as
  6813. discussed in section~\ref{sec:move-biasing}.
  6814. %
  6815. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6816. performs coalescing, graph coloring, and spill code insertion until
  6817. all variables have been assigned a location.
  6818. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6819. spilled variables that don't have to be: a high-degree variable can be
  6820. colorable if many of its neighbors are assigned the same color.
  6821. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6822. high-degree vertex is not immediately spilled. Instead the decision is
  6823. deferred until after the recursive call, at which point it is apparent
  6824. whether there is actually an available color or not. We observe that
  6825. this algorithm is equivalent to the smallest-last ordering
  6826. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6827. be registers and the rest to be stack locations.
  6828. %% biased coloring
  6829. Earlier editions of the compiler course at Indiana University
  6830. \citep{Dybvig:2010aa} were based on the algorithm of
  6831. \citet{Briggs:1994kx}.
  6832. The smallest-last ordering algorithm is one of many \emph{greedy}
  6833. coloring algorithms. A greedy coloring algorithm visits all the
  6834. vertices in a particular order and assigns each one the first
  6835. available color. An \emph{offline} greedy algorithm chooses the
  6836. ordering up front, prior to assigning colors. The algorithm of
  6837. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6838. ordering does not depend on the colors assigned. Other orderings are
  6839. possible. For example, \citet{Chow:1984ys} ordered variables according
  6840. to an estimate of runtime cost.
  6841. An \emph{online} greedy coloring algorithm uses information about the
  6842. current assignment of colors to influence the order in which the
  6843. remaining vertices are colored. The saturation-based algorithm
  6844. described in this chapter is one such algorithm. We choose to use
  6845. saturation-based coloring because it is fun to introduce graph
  6846. coloring via sudoku!
  6847. A register allocator may choose to map each variable to just one
  6848. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6849. variable to one or more locations. The latter can be achieved by
  6850. \emph{live range splitting}, where a variable is replaced by several
  6851. variables that each handle part of its live
  6852. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6853. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6854. %% replacement algorithm, bottom-up local
  6855. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6856. %% Cooper: top-down (priority bassed), bottom-up
  6857. %% top-down
  6858. %% order variables by priority (estimated cost)
  6859. %% caveat: split variables into two groups:
  6860. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6861. %% color the constrained ones first
  6862. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6863. %% cite J. Cocke for an algorithm that colors variables
  6864. %% in a high-degree first ordering
  6865. %Register Allocation via Usage Counts, Freiburghouse CACM
  6866. \citet{Palsberg:2007si} observed that many of the interference graphs
  6867. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6868. that is, every cycle with four or more edges has an edge that is not
  6869. part of the cycle but that connects two vertices on the cycle. Such
  6870. graphs can be optimally colored by the greedy algorithm with a vertex
  6871. ordering determined by maximum cardinality search.
  6872. In situations in which compile time is of utmost importance, such as
  6873. in just-in-time compilers, graph coloring algorithms can be too
  6874. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6875. be more appropriate.
  6876. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6877. \chapter{Booleans and Conditionals}
  6878. \label{ch:Lif}
  6879. \index{subject}{Boolean}
  6880. \index{subject}{control flow}
  6881. \index{subject}{conditional expression}
  6882. \setcounter{footnote}{0}
  6883. The \LangVar{} language has only a single kind of value, the
  6884. integers. In this chapter we add a second kind of value, the Booleans,
  6885. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6886. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6887. and \FALSE{}, respectively. The \LangIf{} language includes several
  6888. operations that involve Booleans (\key{and}, \key{not},
  6889. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6890. expression \python{and statement}. With the addition of \key{if},
  6891. programs can have nontrivial control flow which
  6892. %
  6893. \racket{impacts \code{explicate\_control} and liveness analysis}
  6894. %
  6895. \python{impacts liveness analysis and motivates a new pass named
  6896. \code{explicate\_control}}.
  6897. %
  6898. Also, because we now have two kinds of values, we need to handle
  6899. programs that apply an operation to the wrong kind of value, such as
  6900. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6901. There are two language design options for such situations. One option
  6902. is to signal an error and the other is to provide a wider
  6903. interpretation of the operation. \racket{The Racket
  6904. language}\python{Python} uses a mixture of these two options,
  6905. depending on the operation and the kind of value. For example, the
  6906. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6907. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6908. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6909. %
  6910. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6911. in Racket because \code{car} expects a pair.}
  6912. %
  6913. \python{On the other hand, \code{1[0]} results in a runtime error
  6914. in Python because an ``\code{int} object is not subscriptable''.}
  6915. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6916. design choices as \racket{Racket}\python{Python}, except that much of the
  6917. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6918. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6919. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6920. \python{MyPy} reports a compile-time error
  6921. %
  6922. \racket{because Racket expects the type of the argument to be of the form
  6923. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6924. %
  6925. \python{stating that a ``value of type \code{int} is not indexable''.}
  6926. The \LangIf{} language performs type checking during compilation just as
  6927. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6928. the alternative choice, that is, a dynamically typed language like
  6929. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6930. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6931. restrictive, for example, rejecting \racket{\code{(not
  6932. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6933. fairly simple because the focus of this book is on compilation and not
  6934. type systems, about which there are already several excellent
  6935. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6936. This chapter is organized as follows. We begin by defining the syntax
  6937. and interpreter for the \LangIf{} language
  6938. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6939. checking and define a type checker for \LangIf{}
  6940. (section~\ref{sec:type-check-Lif}).
  6941. %
  6942. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6943. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6944. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6945. %
  6946. The remaining sections of this chapter discuss how Booleans and
  6947. conditional control flow require changes to the existing compiler
  6948. passes and the addition of new ones. We introduce the \code{shrink}
  6949. pass to translate some operators into others, thereby reducing the
  6950. number of operators that need to be handled in later passes.
  6951. %
  6952. The main event of this chapter is the \code{explicate\_control} pass
  6953. that is responsible for translating \code{if}s into conditional
  6954. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6955. %
  6956. Regarding register allocation, there is the interesting question of
  6957. how to handle conditional \code{goto}s during liveness analysis.
  6958. \section{The \LangIf{} Language}
  6959. \label{sec:lang-if}
  6960. Definitions of the concrete syntax and abstract syntax of the
  6961. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6962. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6963. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6964. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6965. %
  6966. \python{, and the \code{if} statement}. We expand the set of
  6967. operators to include
  6968. \begin{enumerate}
  6969. \item the logical operators \key{and}, \key{or}, and \key{not},
  6970. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6971. for comparing integers or Booleans for equality, and
  6972. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6973. comparing integers.
  6974. \end{enumerate}
  6975. \racket{We reorganize the abstract syntax for the primitive
  6976. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6977. rule for all of them. This means that the grammar no longer checks
  6978. whether the arity of an operators matches the number of
  6979. arguments. That responsibility is moved to the type checker for
  6980. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6981. \newcommand{\LifGrammarRacket}{
  6982. \begin{array}{lcl}
  6983. \Type &::=& \key{Boolean} \\
  6984. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6985. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6986. \Exp &::=& \itm{bool}
  6987. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6988. \MID (\key{not}\;\Exp) \\
  6989. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6990. \end{array}
  6991. }
  6992. \newcommand{\LifASTRacket}{
  6993. \begin{array}{lcl}
  6994. \Type &::=& \key{Boolean} \\
  6995. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6996. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6997. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6998. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6999. \end{array}
  7000. }
  7001. \newcommand{\LintOpAST}{
  7002. \begin{array}{rcl}
  7003. \Type &::=& \key{Integer} \\
  7004. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7005. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7006. \end{array}
  7007. }
  7008. \newcommand{\LifGrammarPython}{
  7009. \begin{array}{rcl}
  7010. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7011. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7012. \MID \key{not}~\Exp \\
  7013. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7014. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7015. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7016. \end{array}
  7017. }
  7018. \newcommand{\LifASTPython}{
  7019. \begin{array}{lcl}
  7020. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7021. \itm{unaryop} &::=& \code{Not()} \\
  7022. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7023. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7024. \Exp &::=& \BOOL{\itm{bool}}
  7025. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7026. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7027. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7028. \end{array}
  7029. }
  7030. \begin{figure}[tp]
  7031. \centering
  7032. \begin{tcolorbox}[colback=white]
  7033. {\if\edition\racketEd
  7034. \[
  7035. \begin{array}{l}
  7036. \gray{\LintGrammarRacket{}} \\ \hline
  7037. \gray{\LvarGrammarRacket{}} \\ \hline
  7038. \LifGrammarRacket{} \\
  7039. \begin{array}{lcl}
  7040. \LangIfM{} &::=& \Exp
  7041. \end{array}
  7042. \end{array}
  7043. \]
  7044. \fi}
  7045. {\if\edition\pythonEd
  7046. \[
  7047. \begin{array}{l}
  7048. \gray{\LintGrammarPython} \\ \hline
  7049. \gray{\LvarGrammarPython} \\ \hline
  7050. \LifGrammarPython \\
  7051. \begin{array}{rcl}
  7052. \LangIfM{} &::=& \Stmt^{*}
  7053. \end{array}
  7054. \end{array}
  7055. \]
  7056. \fi}
  7057. \end{tcolorbox}
  7058. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7059. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7060. \label{fig:Lif-concrete-syntax}
  7061. \end{figure}
  7062. \begin{figure}[tp]
  7063. %\begin{minipage}{0.66\textwidth}
  7064. \begin{tcolorbox}[colback=white]
  7065. \centering
  7066. {\if\edition\racketEd
  7067. \[
  7068. \begin{array}{l}
  7069. \gray{\LintOpAST} \\ \hline
  7070. \gray{\LvarASTRacket{}} \\ \hline
  7071. \LifASTRacket{} \\
  7072. \begin{array}{lcl}
  7073. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7074. \end{array}
  7075. \end{array}
  7076. \]
  7077. \fi}
  7078. {\if\edition\pythonEd
  7079. \[
  7080. \begin{array}{l}
  7081. \gray{\LintASTPython} \\ \hline
  7082. \gray{\LvarASTPython} \\ \hline
  7083. \LifASTPython \\
  7084. \begin{array}{lcl}
  7085. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7086. \end{array}
  7087. \end{array}
  7088. \]
  7089. \fi}
  7090. \end{tcolorbox}
  7091. %\end{minipage}
  7092. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  7093. \index{subject}{IfExp@\IFNAME{}}
  7094. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  7095. \index{subject}{and@\ANDNAME{}}
  7096. \index{subject}{or@\ORNAME{}}
  7097. \index{subject}{not@\NOTNAME{}}
  7098. \index{subject}{equal@\EQNAME{}}
  7099. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7100. \racket{
  7101. \index{subject}{lessthan@\texttt{<}}
  7102. \index{subject}{lessthaneq@\texttt{<=}}
  7103. \index{subject}{greaterthan@\texttt{>}}
  7104. \index{subject}{greaterthaneq@\texttt{>=}}
  7105. }
  7106. \python{
  7107. \index{subject}{BoolOp@\texttt{BoolOp}}
  7108. \index{subject}{Compare@\texttt{Compare}}
  7109. \index{subject}{Lt@\texttt{Lt}}
  7110. \index{subject}{LtE@\texttt{LtE}}
  7111. \index{subject}{Gt@\texttt{Gt}}
  7112. \index{subject}{GtE@\texttt{GtE}}
  7113. }
  7114. \caption{The abstract syntax of \LangIf{}.}
  7115. \label{fig:Lif-syntax}
  7116. \end{figure}
  7117. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7118. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7119. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7120. evaluate to the corresponding Boolean values. The conditional
  7121. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7122. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7123. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7124. \code{or}, and \code{not} behave according to propositional logic. In
  7125. addition, the \code{and} and \code{or} operations perform
  7126. \emph{short-circuit evaluation}.
  7127. %
  7128. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7129. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7130. %
  7131. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7132. evaluated if $e_1$ evaluates to \TRUE{}.
  7133. \racket{With the increase in the number of primitive operations, the
  7134. interpreter would become repetitive without some care. We refactor
  7135. the case for \code{Prim}, moving the code that differs with each
  7136. operation into the \code{interp\_op} method shown in
  7137. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7138. \code{or} operations separately because of their short-circuiting
  7139. behavior.}
  7140. \begin{figure}[tbp]
  7141. \begin{tcolorbox}[colback=white]
  7142. {\if\edition\racketEd
  7143. \begin{lstlisting}
  7144. (define interp-Lif-class
  7145. (class interp-Lvar-class
  7146. (super-new)
  7147. (define/public (interp_op op) ...)
  7148. (define/override ((interp_exp env) e)
  7149. (define recur (interp_exp env))
  7150. (match e
  7151. [(Bool b) b]
  7152. [(If cnd thn els)
  7153. (match (recur cnd)
  7154. [#t (recur thn)]
  7155. [#f (recur els)])]
  7156. [(Prim 'and (list e1 e2))
  7157. (match (recur e1)
  7158. [#t (match (recur e2) [#t #t] [#f #f])]
  7159. [#f #f])]
  7160. [(Prim 'or (list e1 e2))
  7161. (define v1 (recur e1))
  7162. (match v1
  7163. [#t #t]
  7164. [#f (match (recur e2) [#t #t] [#f #f])])]
  7165. [(Prim op args)
  7166. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7167. [else ((super interp_exp env) e)]))
  7168. ))
  7169. (define (interp_Lif p)
  7170. (send (new interp-Lif-class) interp_program p))
  7171. \end{lstlisting}
  7172. \fi}
  7173. {\if\edition\pythonEd
  7174. \begin{lstlisting}
  7175. class InterpLif(InterpLvar):
  7176. def interp_exp(self, e, env):
  7177. match e:
  7178. case IfExp(test, body, orelse):
  7179. if self.interp_exp(test, env):
  7180. return self.interp_exp(body, env)
  7181. else:
  7182. return self.interp_exp(orelse, env)
  7183. case UnaryOp(Not(), v):
  7184. return not self.interp_exp(v, env)
  7185. case BoolOp(And(), values):
  7186. if self.interp_exp(values[0], env):
  7187. return self.interp_exp(values[1], env)
  7188. else:
  7189. return False
  7190. case BoolOp(Or(), values):
  7191. if self.interp_exp(values[0], env):
  7192. return True
  7193. else:
  7194. return self.interp_exp(values[1], env)
  7195. case Compare(left, [cmp], [right]):
  7196. l = self.interp_exp(left, env)
  7197. r = self.interp_exp(right, env)
  7198. return self.interp_cmp(cmp)(l, r)
  7199. case _:
  7200. return super().interp_exp(e, env)
  7201. def interp_stmts(self, ss, env):
  7202. if len(ss) == 0:
  7203. return
  7204. match ss[0]:
  7205. case If(test, body, orelse):
  7206. if self.interp_exp(test, env):
  7207. return self.interp_stmts(body + ss[1:], env)
  7208. else:
  7209. return self.interp_stmts(orelse + ss[1:], env)
  7210. case _:
  7211. return super().interp_stmts(ss, env)
  7212. ...
  7213. \end{lstlisting}
  7214. \fi}
  7215. \end{tcolorbox}
  7216. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7217. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7218. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7219. \label{fig:interp-Lif}
  7220. \end{figure}
  7221. {\if\edition\racketEd
  7222. \begin{figure}[tbp]
  7223. \begin{tcolorbox}[colback=white]
  7224. \begin{lstlisting}
  7225. (define/public (interp_op op)
  7226. (match op
  7227. ['+ fx+]
  7228. ['- fx-]
  7229. ['read read-fixnum]
  7230. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7231. ['eq? (lambda (v1 v2)
  7232. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7233. (and (boolean? v1) (boolean? v2))
  7234. (and (vector? v1) (vector? v2)))
  7235. (eq? v1 v2)]))]
  7236. ['< (lambda (v1 v2)
  7237. (cond [(and (fixnum? v1) (fixnum? v2))
  7238. (< v1 v2)]))]
  7239. ['<= (lambda (v1 v2)
  7240. (cond [(and (fixnum? v1) (fixnum? v2))
  7241. (<= v1 v2)]))]
  7242. ['> (lambda (v1 v2)
  7243. (cond [(and (fixnum? v1) (fixnum? v2))
  7244. (> v1 v2)]))]
  7245. ['>= (lambda (v1 v2)
  7246. (cond [(and (fixnum? v1) (fixnum? v2))
  7247. (>= v1 v2)]))]
  7248. [else (error 'interp_op "unknown operator")]))
  7249. \end{lstlisting}
  7250. \end{tcolorbox}
  7251. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7252. \label{fig:interp-op-Lif}
  7253. \end{figure}
  7254. \fi}
  7255. {\if\edition\pythonEd
  7256. \begin{figure}
  7257. \begin{tcolorbox}[colback=white]
  7258. \begin{lstlisting}
  7259. class InterpLif(InterpLvar):
  7260. ...
  7261. def interp_cmp(self, cmp):
  7262. match cmp:
  7263. case Lt():
  7264. return lambda x, y: x < y
  7265. case LtE():
  7266. return lambda x, y: x <= y
  7267. case Gt():
  7268. return lambda x, y: x > y
  7269. case GtE():
  7270. return lambda x, y: x >= y
  7271. case Eq():
  7272. return lambda x, y: x == y
  7273. case NotEq():
  7274. return lambda x, y: x != y
  7275. \end{lstlisting}
  7276. \end{tcolorbox}
  7277. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7278. \label{fig:interp-cmp-Lif}
  7279. \end{figure}
  7280. \fi}
  7281. \section{Type Checking \LangIf{} Programs}
  7282. \label{sec:type-check-Lif}
  7283. \index{subject}{type checking}
  7284. \index{subject}{semantic analysis}
  7285. It is helpful to think about type checking in two complementary
  7286. ways. A type checker predicts the type of value that will be produced
  7287. by each expression in the program. For \LangIf{}, we have just two types,
  7288. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  7289. {\if\edition\racketEd
  7290. \begin{lstlisting}
  7291. (+ 10 (- (+ 12 20)))
  7292. \end{lstlisting}
  7293. \fi}
  7294. {\if\edition\pythonEd
  7295. \begin{lstlisting}
  7296. 10 + -(12 + 20)
  7297. \end{lstlisting}
  7298. \fi}
  7299. \noindent produces a value of type \INTTY{}, whereas
  7300. {\if\edition\racketEd
  7301. \begin{lstlisting}
  7302. (and (not #f) #t)
  7303. \end{lstlisting}
  7304. \fi}
  7305. {\if\edition\pythonEd
  7306. \begin{lstlisting}
  7307. (not False) and True
  7308. \end{lstlisting}
  7309. \fi}
  7310. \noindent produces a value of type \BOOLTY{}.
  7311. A second way to think about type checking is that it enforces a set of
  7312. rules about which operators can be applied to which kinds of
  7313. values. For example, our type checker for \LangIf{} signals an error
  7314. for the following expression:
  7315. %
  7316. {\if\edition\racketEd
  7317. \begin{lstlisting}
  7318. (not (+ 10 (- (+ 12 20))))
  7319. \end{lstlisting}
  7320. \fi}
  7321. {\if\edition\pythonEd
  7322. \begin{lstlisting}
  7323. not (10 + -(12 + 20))
  7324. \end{lstlisting}
  7325. \fi}
  7326. \noindent The subexpression
  7327. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7328. \python{\code{(10 + -(12 + 20))}}
  7329. has type \INTTY{}, but the type checker enforces the rule that the
  7330. argument of \code{not} must be an expression of type \BOOLTY{}.
  7331. We implement type checking using classes and methods because they
  7332. provide the open recursion needed to reuse code as we extend the type
  7333. checker in subsequent chapters, analogous to the use of classes and methods
  7334. for the interpreters (section~\ref{sec:extensible-interp}).
  7335. We separate the type checker for the \LangVar{} subset into its own
  7336. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7337. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7338. from the type checker for \LangVar{}. These type checkers are in the
  7339. files
  7340. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7341. and
  7342. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7343. of the support code.
  7344. %
  7345. Each type checker is a structurally recursive function over the AST.
  7346. Given an input expression \code{e}, the type checker either signals an
  7347. error or returns \racket{an expression and} its type.
  7348. %
  7349. \racket{It returns an expression because there are situations in which
  7350. we want to change or update the expression.}
  7351. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7352. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7353. constant is \INTTY{}. To handle variables, the type checker uses the
  7354. environment \code{env} to map variables to types.
  7355. %
  7356. \racket{Consider the case for \key{let}. We type check the
  7357. initializing expression to obtain its type \key{T} and then
  7358. associate type \code{T} with the variable \code{x} in the
  7359. environment used to type check the body of the \key{let}. Thus,
  7360. when the type checker encounters a use of variable \code{x}, it can
  7361. find its type in the environment.}
  7362. %
  7363. \python{Consider the case for assignment. We type check the
  7364. initializing expression to obtain its type \key{t}. If the variable
  7365. \code{lhs.id} is already in the environment because there was a
  7366. prior assignment, we check that this initializer has the same type
  7367. as the prior one. If this is the first assignment to the variable,
  7368. we associate type \code{t} with the variable \code{lhs.id} in the
  7369. environment. Thus, when the type checker encounters a use of
  7370. variable \code{x}, it can find its type in the environment.}
  7371. %
  7372. \racket{Regarding primitive operators, we recursively analyze the
  7373. arguments and then invoke \code{type\_check\_op} to check whether
  7374. the argument types are allowed.}
  7375. %
  7376. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7377. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7378. \racket{Several auxiliary methods are used in the type checker. The
  7379. method \code{operator-types} defines a dictionary that maps the
  7380. operator names to their parameter and return types. The
  7381. \code{type-equal?} method determines whether two types are equal,
  7382. which for now simply dispatches to \code{equal?} (deep
  7383. equality). The \code{check-type-equal?} method triggers an error if
  7384. the two types are not equal. The \code{type-check-op} method looks
  7385. up the operator in the \code{operator-types} dictionary and then
  7386. checks whether the argument types are equal to the parameter types.
  7387. The result is the return type of the operator.}
  7388. %
  7389. \python{The auxiliary method \code{check\_type\_equal} triggers
  7390. an error if the two types are not equal.}
  7391. \begin{figure}[tbp]
  7392. \begin{tcolorbox}[colback=white]
  7393. {\if\edition\racketEd
  7394. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7395. (define type-check-Lvar-class
  7396. (class object%
  7397. (super-new)
  7398. (define/public (operator-types)
  7399. '((+ . ((Integer Integer) . Integer))
  7400. (- . ((Integer Integer) . Integer))
  7401. (read . (() . Integer))))
  7402. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7403. (define/public (check-type-equal? t1 t2 e)
  7404. (unless (type-equal? t1 t2)
  7405. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7406. (define/public (type-check-op op arg-types e)
  7407. (match (dict-ref (operator-types) op)
  7408. [`(,param-types . ,return-type)
  7409. (for ([at arg-types] [pt param-types])
  7410. (check-type-equal? at pt e))
  7411. return-type]
  7412. [else (error 'type-check-op "unrecognized ~a" op)]))
  7413. (define/public (type-check-exp env)
  7414. (lambda (e)
  7415. (match e
  7416. [(Int n) (values (Int n) 'Integer)]
  7417. [(Var x) (values (Var x) (dict-ref env x))]
  7418. [(Let x e body)
  7419. (define-values (e^ Te) ((type-check-exp env) e))
  7420. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7421. (values (Let x e^ b) Tb)]
  7422. [(Prim op es)
  7423. (define-values (new-es ts)
  7424. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7425. (values (Prim op new-es) (type-check-op op ts e))]
  7426. [else (error 'type-check-exp "couldn't match" e)])))
  7427. (define/public (type-check-program e)
  7428. (match e
  7429. [(Program info body)
  7430. (define-values (body^ Tb) ((type-check-exp '()) body))
  7431. (check-type-equal? Tb 'Integer body)
  7432. (Program info body^)]
  7433. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7434. ))
  7435. (define (type-check-Lvar p)
  7436. (send (new type-check-Lvar-class) type-check-program p))
  7437. \end{lstlisting}
  7438. \fi}
  7439. {\if\edition\pythonEd
  7440. \begin{lstlisting}[escapechar=`]
  7441. class TypeCheckLvar:
  7442. def check_type_equal(self, t1, t2, e):
  7443. if t1 != t2:
  7444. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7445. raise Exception(msg)
  7446. def type_check_exp(self, e, env):
  7447. match e:
  7448. case BinOp(left, (Add() | Sub()), right):
  7449. l = self.type_check_exp(left, env)
  7450. check_type_equal(l, int, left)
  7451. r = self.type_check_exp(right, env)
  7452. check_type_equal(r, int, right)
  7453. return int
  7454. case UnaryOp(USub(), v):
  7455. t = self.type_check_exp(v, env)
  7456. check_type_equal(t, int, v)
  7457. return int
  7458. case Name(id):
  7459. return env[id]
  7460. case Constant(value) if isinstance(value, int):
  7461. return int
  7462. case Call(Name('input_int'), []):
  7463. return int
  7464. def type_check_stmts(self, ss, env):
  7465. if len(ss) == 0:
  7466. return
  7467. match ss[0]:
  7468. case Assign([lhs], value):
  7469. t = self.type_check_exp(value, env)
  7470. if lhs.id in env:
  7471. check_type_equal(env[lhs.id], t, value)
  7472. else:
  7473. env[lhs.id] = t
  7474. return self.type_check_stmts(ss[1:], env)
  7475. case Expr(Call(Name('print'), [arg])):
  7476. t = self.type_check_exp(arg, env)
  7477. check_type_equal(t, int, arg)
  7478. return self.type_check_stmts(ss[1:], env)
  7479. case Expr(value):
  7480. self.type_check_exp(value, env)
  7481. return self.type_check_stmts(ss[1:], env)
  7482. def type_check_P(self, p):
  7483. match p:
  7484. case Module(body):
  7485. self.type_check_stmts(body, {})
  7486. \end{lstlisting}
  7487. \fi}
  7488. \end{tcolorbox}
  7489. \caption{Type checker for the \LangVar{} language.}
  7490. \label{fig:type-check-Lvar}
  7491. \end{figure}
  7492. \begin{figure}[tbp]
  7493. \begin{tcolorbox}[colback=white]
  7494. {\if\edition\racketEd
  7495. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7496. (define type-check-Lif-class
  7497. (class type-check-Lvar-class
  7498. (super-new)
  7499. (inherit check-type-equal?)
  7500. (define/override (operator-types)
  7501. (append '((and . ((Boolean Boolean) . Boolean))
  7502. (or . ((Boolean Boolean) . Boolean))
  7503. (< . ((Integer Integer) . Boolean))
  7504. (<= . ((Integer Integer) . Boolean))
  7505. (> . ((Integer Integer) . Boolean))
  7506. (>= . ((Integer Integer) . Boolean))
  7507. (not . ((Boolean) . Boolean)))
  7508. (super operator-types)))
  7509. (define/override (type-check-exp env)
  7510. (lambda (e)
  7511. (match e
  7512. [(Bool b) (values (Bool b) 'Boolean)]
  7513. [(Prim 'eq? (list e1 e2))
  7514. (define-values (e1^ T1) ((type-check-exp env) e1))
  7515. (define-values (e2^ T2) ((type-check-exp env) e2))
  7516. (check-type-equal? T1 T2 e)
  7517. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7518. [(If cnd thn els)
  7519. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7520. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7521. (define-values (els^ Te) ((type-check-exp env) els))
  7522. (check-type-equal? Tc 'Boolean e)
  7523. (check-type-equal? Tt Te e)
  7524. (values (If cnd^ thn^ els^) Te)]
  7525. [else ((super type-check-exp env) e)])))
  7526. ))
  7527. (define (type-check-Lif p)
  7528. (send (new type-check-Lif-class) type-check-program p))
  7529. \end{lstlisting}
  7530. \fi}
  7531. {\if\edition\pythonEd
  7532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7533. class TypeCheckLif(TypeCheckLvar):
  7534. def type_check_exp(self, e, env):
  7535. match e:
  7536. case Constant(value) if isinstance(value, bool):
  7537. return bool
  7538. case BinOp(left, Sub(), right):
  7539. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7540. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7541. return int
  7542. case UnaryOp(Not(), v):
  7543. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7544. return bool
  7545. case BoolOp(op, values):
  7546. left = values[0] ; right = values[1]
  7547. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7548. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7549. return bool
  7550. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7551. or isinstance(cmp, NotEq):
  7552. l = self.type_check_exp(left, env)
  7553. r = self.type_check_exp(right, env)
  7554. check_type_equal(l, r, e)
  7555. return bool
  7556. case Compare(left, [cmp], [right]):
  7557. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7558. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7559. return bool
  7560. case IfExp(test, body, orelse):
  7561. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7562. b = self.type_check_exp(body, env)
  7563. o = self.type_check_exp(orelse, env)
  7564. check_type_equal(b, o, e)
  7565. return b
  7566. case _:
  7567. return super().type_check_exp(e, env)
  7568. def type_check_stmts(self, ss, env):
  7569. if len(ss) == 0:
  7570. return
  7571. match ss[0]:
  7572. case If(test, body, orelse):
  7573. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7574. b = self.type_check_stmts(body, env)
  7575. o = self.type_check_stmts(orelse, env)
  7576. check_type_equal(b, o, ss[0])
  7577. return self.type_check_stmts(ss[1:], env)
  7578. case _:
  7579. return super().type_check_stmts(ss, env)
  7580. \end{lstlisting}
  7581. \fi}
  7582. \end{tcolorbox}
  7583. \caption{Type checker for the \LangIf{} language.}
  7584. \label{fig:type-check-Lif}
  7585. \end{figure}
  7586. The definition of the type checker for \LangIf{} is shown in
  7587. figure~\ref{fig:type-check-Lif}.
  7588. %
  7589. The type of a Boolean constant is \BOOLTY{}.
  7590. %
  7591. \racket{The \code{operator-types} function adds dictionary entries for
  7592. the new operators.}
  7593. %
  7594. \python{Logical not requires its argument to be a \BOOLTY{} and
  7595. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7596. %
  7597. The equality operator requires the two arguments to have the same type,
  7598. and therefore we handle it separately from the other operators.
  7599. %
  7600. \python{The other comparisons (less-than, etc.) require their
  7601. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7602. %
  7603. The condition of an \code{if} must
  7604. be of \BOOLTY{} type, and the two branches must have the same type.
  7605. \begin{exercise}\normalfont\normalsize
  7606. Create ten new test programs in \LangIf{}. Half the programs should
  7607. have a type error. For those programs, create an empty file with the
  7608. same base name and with file extension \code{.tyerr}. For example, if
  7609. the test
  7610. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7611. is expected to error, then create
  7612. an empty file named \code{cond\_test\_14.tyerr}.
  7613. %
  7614. \racket{This indicates to \code{interp-tests} and
  7615. \code{compiler-tests} that a type error is expected. }
  7616. %
  7617. The other half of the test programs should not have type errors.
  7618. %
  7619. \racket{In the \code{run-tests.rkt} script, change the second argument
  7620. of \code{interp-tests} and \code{compiler-tests} to
  7621. \code{type-check-Lif}, which causes the type checker to run prior to
  7622. the compiler passes. Temporarily change the \code{passes} to an
  7623. empty list and run the script, thereby checking that the new test
  7624. programs either type check or do not, as intended.}
  7625. %
  7626. Run the test script to check that these test programs type check as
  7627. expected.
  7628. \end{exercise}
  7629. \clearpage
  7630. \section{The \LangCIf{} Intermediate Language}
  7631. \label{sec:Cif}
  7632. {\if\edition\racketEd
  7633. %
  7634. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7635. comparison operators to the \Exp{} nonterminal and the literals
  7636. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7637. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7638. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7639. comparison operation and the branches are \code{goto} statements,
  7640. making it straightforward to compile \code{if} statements to x86. The
  7641. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7642. expressions. A \code{goto} statement transfers control to the $\Tail$
  7643. expression corresponding to its label.
  7644. %
  7645. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7646. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7647. defines its abstract syntax.
  7648. %
  7649. \fi}
  7650. %
  7651. {\if\edition\pythonEd
  7652. %
  7653. The output of \key{explicate\_control} is a language similar to the
  7654. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7655. \code{goto} statements, so we name it \LangCIf{}.
  7656. %
  7657. The \LangCIf{} language supports the same operators as \LangIf{} but
  7658. the arguments of operators are restricted to atomic expressions. The
  7659. \LangCIf{} language does not include \code{if} expressions but it does
  7660. include a restricted form of \code{if} statement. The condition must be
  7661. a comparison and the two branches may only contain \code{goto}
  7662. statements. These restrictions make it easier to translate \code{if}
  7663. statements to x86. The \LangCIf{} language also adds a \code{return}
  7664. statement to finish the program with a specified value.
  7665. %
  7666. The \key{CProgram} construct contains a dictionary mapping labels to
  7667. lists of statements that end with a \code{return} statement, a
  7668. \code{goto}, or a conditional \code{goto}.
  7669. %% Statement lists of this
  7670. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7671. %% is a control transfer at the end and control only enters at the
  7672. %% beginning of the list, which is marked by the label.
  7673. %
  7674. A \code{goto} statement transfers control to the sequence of statements
  7675. associated with its label.
  7676. %
  7677. The concrete syntax for \LangCIf{} is defined in
  7678. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7679. in figure~\ref{fig:c1-syntax}.
  7680. %
  7681. \fi}
  7682. %
  7683. \newcommand{\CifGrammarRacket}{
  7684. \begin{array}{lcl}
  7685. \Atm &::=& \itm{bool} \\
  7686. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7687. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7688. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7689. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7690. \end{array}
  7691. }
  7692. \newcommand{\CifASTRacket}{
  7693. \begin{array}{lcl}
  7694. \Atm &::=& \BOOL{\itm{bool}} \\
  7695. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7696. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7697. \Tail &::= & \GOTO{\itm{label}} \\
  7698. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7699. \end{array}
  7700. }
  7701. \newcommand{\CifGrammarPython}{
  7702. \begin{array}{lcl}
  7703. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7704. \Exp &::= & \Atm \MID \CREAD{}
  7705. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7706. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7707. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7708. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7709. &\MID& \CASSIGN{\Var}{\Exp}
  7710. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7711. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7712. \end{array}
  7713. }
  7714. \newcommand{\CifASTPython}{
  7715. \begin{array}{lcl}
  7716. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7717. \Exp &::= & \Atm \MID \READ{} \\
  7718. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7719. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7720. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7721. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7722. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7723. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7724. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7725. \end{array}
  7726. }
  7727. \begin{figure}[tbp]
  7728. \begin{tcolorbox}[colback=white]
  7729. \small
  7730. {\if\edition\racketEd
  7731. \[
  7732. \begin{array}{l}
  7733. \gray{\CvarGrammarRacket} \\ \hline
  7734. \CifGrammarRacket \\
  7735. \begin{array}{lcl}
  7736. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7737. \end{array}
  7738. \end{array}
  7739. \]
  7740. \fi}
  7741. {\if\edition\pythonEd
  7742. \[
  7743. \begin{array}{l}
  7744. \CifGrammarPython \\
  7745. \begin{array}{lcl}
  7746. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7747. \end{array}
  7748. \end{array}
  7749. \]
  7750. \fi}
  7751. \end{tcolorbox}
  7752. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7753. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7754. \label{fig:c1-concrete-syntax}
  7755. \end{figure}
  7756. \begin{figure}[tp]
  7757. \begin{tcolorbox}[colback=white]
  7758. \small
  7759. {\if\edition\racketEd
  7760. \[
  7761. \begin{array}{l}
  7762. \gray{\CvarASTRacket} \\ \hline
  7763. \CifASTRacket \\
  7764. \begin{array}{lcl}
  7765. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7766. \end{array}
  7767. \end{array}
  7768. \]
  7769. \fi}
  7770. {\if\edition\pythonEd
  7771. \[
  7772. \begin{array}{l}
  7773. \CifASTPython \\
  7774. \begin{array}{lcl}
  7775. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7776. \end{array}
  7777. \end{array}
  7778. \]
  7779. \fi}
  7780. \end{tcolorbox}
  7781. \racket{
  7782. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7783. }
  7784. \index{subject}{Goto@\texttt{Goto}}
  7785. \index{subject}{Return@\texttt{Return}}
  7786. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7787. (figure~\ref{fig:c0-syntax})}.}
  7788. \label{fig:c1-syntax}
  7789. \end{figure}
  7790. \section{The \LangXIf{} Language}
  7791. \label{sec:x86-if}
  7792. \index{subject}{x86} To implement the new logical operations, the
  7793. comparison operations, and the \key{if} expression\python{ and
  7794. statement}, we delve further into the x86
  7795. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7796. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7797. subset of x86, which includes instructions for logical operations,
  7798. comparisons, and \racket{conditional} jumps.
  7799. %
  7800. \python{The abstract syntax for an \LangXIf{} program contains a
  7801. dictionary mapping labels to sequences of instructions, each of
  7802. which we refer to as a \emph{basic block}\index{subject}{basic
  7803. block}.}
  7804. One challenge is that x86 does not provide an instruction that
  7805. directly implements logical negation (\code{not} in \LangIf{} and
  7806. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7807. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7808. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7809. bit of its arguments, and writes the results into its second argument.
  7810. Recall the following truth table for exclusive-or:
  7811. \begin{center}
  7812. \begin{tabular}{l|cc}
  7813. & 0 & 1 \\ \hline
  7814. 0 & 0 & 1 \\
  7815. 1 & 1 & 0
  7816. \end{tabular}
  7817. \end{center}
  7818. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7819. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7820. for the bit $1$, the result is the opposite of the second bit. Thus,
  7821. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7822. the first argument, as follows, where $\Arg$ is the translation of
  7823. $\Atm$ to x86:
  7824. \[
  7825. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7826. \qquad\Rightarrow\qquad
  7827. \begin{array}{l}
  7828. \key{movq}~ \Arg\key{,} \Var\\
  7829. \key{xorq}~ \key{\$1,} \Var
  7830. \end{array}
  7831. \]
  7832. \newcommand{\GrammarXIf}{
  7833. \begin{array}{lcl}
  7834. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7835. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7836. \Arg &::=& \key{\%}\itm{bytereg}\\
  7837. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7838. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7839. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7840. \MID \key{set}cc~\Arg
  7841. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7842. &\MID& \key{j}cc~\itm{label} \\
  7843. \end{array}
  7844. }
  7845. \begin{figure}[tp]
  7846. \begin{tcolorbox}[colback=white]
  7847. \[
  7848. \begin{array}{l}
  7849. \gray{\GrammarXInt} \\ \hline
  7850. \GrammarXIf \\
  7851. \begin{array}{lcl}
  7852. \LangXIfM{} &::= & \key{.globl main} \\
  7853. & & \key{main:} \; \Instr\ldots
  7854. \end{array}
  7855. \end{array}
  7856. \]
  7857. \end{tcolorbox}
  7858. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7859. \label{fig:x86-1-concrete}
  7860. \end{figure}
  7861. \newcommand{\ASTXIfRacket}{
  7862. \begin{array}{lcl}
  7863. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7864. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7865. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7866. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7867. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7868. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7869. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7870. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7871. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7872. \end{array}
  7873. }
  7874. \begin{figure}[tp]
  7875. \begin{tcolorbox}[colback=white]
  7876. \small
  7877. {\if\edition\racketEd
  7878. \[\arraycolsep=3pt
  7879. \begin{array}{l}
  7880. \gray{\ASTXIntRacket} \\ \hline
  7881. \ASTXIfRacket \\
  7882. \begin{array}{lcl}
  7883. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7884. \end{array}
  7885. \end{array}
  7886. \]
  7887. \fi}
  7888. %
  7889. {\if\edition\pythonEd
  7890. \[
  7891. \begin{array}{lcl}
  7892. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7893. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7894. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7895. \MID \BYTEREG{\itm{bytereg}} \\
  7896. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7897. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7898. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7899. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7900. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7901. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7902. \MID \PUSHQ{\Arg}} \\
  7903. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7904. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7905. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7906. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7907. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7908. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7909. \Block &::= & \Instr^{+} \\
  7910. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7911. \end{array}
  7912. \]
  7913. \fi}
  7914. \end{tcolorbox}
  7915. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7916. \label{fig:x86-1}
  7917. \end{figure}
  7918. Next we consider the x86 instructions that are relevant for compiling
  7919. the comparison operations. The \key{cmpq} instruction compares its two
  7920. arguments to determine whether one argument is less than, equal to, or
  7921. greater than the other argument. The \key{cmpq} instruction is unusual
  7922. regarding the order of its arguments and where the result is
  7923. placed. The argument order is backward: if you want to test whether
  7924. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7925. \key{cmpq} is placed in the special EFLAGS register. This register
  7926. cannot be accessed directly, but it can be queried by a number of
  7927. instructions, including the \key{set} instruction. The instruction
  7928. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7929. depending on whether the contents of the EFLAGS register matches the
  7930. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7931. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7932. The \key{set} instruction has a quirk in that its destination argument
  7933. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7934. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7935. register. Thankfully, the \key{movzbq} instruction can be used to
  7936. move from a single-byte register to a normal 64-bit register. The
  7937. abstract syntax for the \code{set} instruction differs from the
  7938. concrete syntax in that it separates the instruction name from the
  7939. condition code.
  7940. \python{The x86 instructions for jumping are relevant to the
  7941. compilation of \key{if} expressions.}
  7942. %
  7943. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7944. counter to the address of the instruction after the specified
  7945. label.}
  7946. %
  7947. \racket{The x86 instruction for conditional jump is relevant to the
  7948. compilation of \key{if} expressions.}
  7949. %
  7950. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7951. counter to point to the instruction after \itm{label}, depending on
  7952. whether the result in the EFLAGS register matches the condition code
  7953. \itm{cc}; otherwise, the jump instruction falls through to the next
  7954. instruction. Like the abstract syntax for \code{set}, the abstract
  7955. syntax for conditional jump separates the instruction name from the
  7956. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7957. corresponds to \code{jle foo}. Because the conditional jump instruction
  7958. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7959. a \key{cmpq} instruction to set the EFLAGS register.
  7960. \section{Shrink the \LangIf{} Language}
  7961. \label{sec:shrink-Lif}
  7962. The \LangIf{} language includes several features that are easily
  7963. expressible with other features. For example, \code{and} and \code{or}
  7964. are expressible using \code{if} as follows.
  7965. \begin{align*}
  7966. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7967. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7968. \end{align*}
  7969. By performing these translations in the front end of the compiler,
  7970. subsequent passes of the compiler do not need to deal with these features,
  7971. thus making the passes shorter.
  7972. On the other hand, translations sometimes reduce the efficiency of the
  7973. generated code by increasing the number of instructions. For example,
  7974. expressing subtraction in terms of negation
  7975. \[
  7976. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7977. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7978. \]
  7979. produces code with two x86 instructions (\code{negq} and \code{addq})
  7980. instead of just one (\code{subq}).
  7981. \begin{exercise}\normalfont\normalsize
  7982. %
  7983. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7984. the language by translating them to \code{if} expressions in \LangIf{}.
  7985. %
  7986. Create four test programs that involve these operators.
  7987. %
  7988. {\if\edition\racketEd
  7989. In the \code{run-tests.rkt} script, add the following entry for
  7990. \code{shrink} to the list of passes (it should be the only pass at
  7991. this point).
  7992. \begin{lstlisting}
  7993. (list "shrink" shrink interp_Lif type-check-Lif)
  7994. \end{lstlisting}
  7995. This instructs \code{interp-tests} to run the interpreter
  7996. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7997. output of \code{shrink}.
  7998. \fi}
  7999. %
  8000. Run the script to test your compiler on all the test programs.
  8001. \end{exercise}
  8002. {\if\edition\racketEd
  8003. \section{Uniquify Variables}
  8004. \label{sec:uniquify-Lif}
  8005. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8006. \code{if} expressions.
  8007. \begin{exercise}\normalfont\normalsize
  8008. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8009. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8010. \begin{lstlisting}
  8011. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8012. \end{lstlisting}
  8013. Run the script to test your compiler.
  8014. \end{exercise}
  8015. \fi}
  8016. \section{Remove Complex Operands}
  8017. \label{sec:remove-complex-opera-Lif}
  8018. The output language of \code{remove\_complex\_operands} is
  8019. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8020. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8021. but the \code{if} expression is not. All three subexpressions of an
  8022. \code{if} are allowed to be complex expressions, but the operands of
  8023. the \code{not} operator and comparison operators must be atomic.
  8024. %
  8025. \python{We add a new language form, the \code{Begin} expression, to aid
  8026. in the translation of \code{if} expressions. When we recursively
  8027. process the two branches of the \code{if}, we generate temporary
  8028. variables and their initializing expressions. However, these
  8029. expressions may contain side effects and should only be executed
  8030. when the condition of the \code{if} is true (for the ``then''
  8031. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8032. a way to initialize the temporary variables within the two branches
  8033. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8034. form execute the statements $ss$ and then returns the result of
  8035. expression $e$.}
  8036. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8037. the new features in \LangIf{}. In recursively processing
  8038. subexpressions, recall that you should invoke \code{rco\_atom} when
  8039. the output needs to be an \Atm{} (as specified in the grammar for
  8040. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8041. \Exp{}. Regarding \code{if}, it is particularly important
  8042. \textbf{not} to replace its condition with a temporary variable, because
  8043. that would interfere with the generation of high-quality output in the
  8044. upcoming \code{explicate\_control} pass.
  8045. \newcommand{\LifMonadASTRacket}{
  8046. \begin{array}{rcl}
  8047. \Atm &::=& \BOOL{\itm{bool}}\\
  8048. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8049. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8050. \MID \IF{\Exp}{\Exp}{\Exp}
  8051. \end{array}
  8052. }
  8053. \newcommand{\LifMonadASTPython}{
  8054. \begin{array}{rcl}
  8055. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8056. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8057. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8058. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8059. \Atm &::=& \BOOL{\itm{bool}}\\
  8060. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8061. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8062. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8063. \end{array}
  8064. }
  8065. \begin{figure}[tp]
  8066. \centering
  8067. \begin{tcolorbox}[colback=white]
  8068. {\if\edition\racketEd
  8069. \[
  8070. \begin{array}{l}
  8071. \gray{\LvarMonadASTRacket} \\ \hline
  8072. \LifMonadASTRacket \\
  8073. \begin{array}{rcl}
  8074. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8075. \end{array}
  8076. \end{array}
  8077. \]
  8078. \fi}
  8079. {\if\edition\pythonEd
  8080. \[
  8081. \begin{array}{l}
  8082. \gray{\LvarMonadASTPython} \\ \hline
  8083. \LifMonadASTPython \\
  8084. \begin{array}{rcl}
  8085. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8086. \end{array}
  8087. \end{array}
  8088. \]
  8089. \fi}
  8090. \end{tcolorbox}
  8091. \python{\index{subject}{Begin@\texttt{Begin}}}
  8092. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8093. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8094. \label{fig:Lif-anf-syntax}
  8095. \end{figure}
  8096. \begin{exercise}\normalfont\normalsize
  8097. %
  8098. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8099. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8100. %
  8101. Create three new \LangIf{} programs that exercise the interesting
  8102. code in this pass.
  8103. %
  8104. {\if\edition\racketEd
  8105. In the \code{run-tests.rkt} script, add the following entry to the
  8106. list of \code{passes} and then run the script to test your compiler.
  8107. \begin{lstlisting}
  8108. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8109. \end{lstlisting}
  8110. \fi}
  8111. \end{exercise}
  8112. \section{Explicate Control}
  8113. \label{sec:explicate-control-Lif}
  8114. \racket{Recall that the purpose of \code{explicate\_control} is to
  8115. make the order of evaluation explicit in the syntax of the program.
  8116. With the addition of \key{if}, this becomes more interesting.}
  8117. %
  8118. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8119. %
  8120. The main challenge to overcome is that the condition of an \key{if}
  8121. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8122. condition must be a comparison.
  8123. As a motivating example, consider the following program that has an
  8124. \key{if} expression nested in the condition of another \key{if}:%
  8125. \python{\footnote{Programmers rarely write nested \code{if}
  8126. expressions, but it is not uncommon for the condition of an
  8127. \code{if} statement to be a call of a function that also contains an
  8128. \code{if} statement. When such a function is inlined, the result is
  8129. a nested \code{if} that requires the techniques discussed in this
  8130. section.}}
  8131. % cond_test_41.rkt, if_lt_eq.py
  8132. \begin{center}
  8133. \begin{minipage}{0.96\textwidth}
  8134. {\if\edition\racketEd
  8135. \begin{lstlisting}
  8136. (let ([x (read)])
  8137. (let ([y (read)])
  8138. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8139. (+ y 2)
  8140. (+ y 10))))
  8141. \end{lstlisting}
  8142. \fi}
  8143. {\if\edition\pythonEd
  8144. \begin{lstlisting}
  8145. x = input_int()
  8146. y = input_int()
  8147. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8148. \end{lstlisting}
  8149. \fi}
  8150. \end{minipage}
  8151. \end{center}
  8152. %
  8153. The naive way to compile \key{if} and the comparison operations would
  8154. be to handle each of them in isolation, regardless of their context.
  8155. Each comparison would be translated into a \key{cmpq} instruction
  8156. followed by several instructions to move the result from the EFLAGS
  8157. register into a general purpose register or stack location. Each
  8158. \key{if} would be translated into a \key{cmpq} instruction followed by
  8159. a conditional jump. The generated code for the inner \key{if} in this
  8160. example would be as follows:
  8161. \begin{center}
  8162. \begin{minipage}{0.96\textwidth}
  8163. \begin{lstlisting}
  8164. cmpq $1, x
  8165. setl %al
  8166. movzbq %al, tmp
  8167. cmpq $1, tmp
  8168. je then_branch_1
  8169. jmp else_branch_1
  8170. \end{lstlisting}
  8171. \end{minipage}
  8172. \end{center}
  8173. Notice that the three instructions starting with \code{setl} are
  8174. redundant: the conditional jump could come immediately after the first
  8175. \code{cmpq}.
  8176. Our goal is to compile \key{if} expressions so that the relevant
  8177. comparison instruction appears directly before the conditional jump.
  8178. For example, we want to generate the following code for the inner
  8179. \code{if}:
  8180. \begin{center}
  8181. \begin{minipage}{0.96\textwidth}
  8182. \begin{lstlisting}
  8183. cmpq $1, x
  8184. jl then_branch_1
  8185. jmp else_branch_1
  8186. \end{lstlisting}
  8187. \end{minipage}
  8188. \end{center}
  8189. One way to achieve this goal is to reorganize the code at the level of
  8190. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8191. the following code:
  8192. \begin{center}
  8193. \begin{minipage}{0.96\textwidth}
  8194. {\if\edition\racketEd
  8195. \begin{lstlisting}
  8196. (let ([x (read)])
  8197. (let ([y (read)])
  8198. (if (< x 1)
  8199. (if (eq? x 0)
  8200. (+ y 2)
  8201. (+ y 10))
  8202. (if (eq? x 2)
  8203. (+ y 2)
  8204. (+ y 10)))))
  8205. \end{lstlisting}
  8206. \fi}
  8207. {\if\edition\pythonEd
  8208. \begin{lstlisting}
  8209. x = input_int()
  8210. y = input_int()
  8211. print(((y + 2) if x == 0 else (y + 10)) \
  8212. if (x < 1) \
  8213. else ((y + 2) if (x == 2) else (y + 10)))
  8214. \end{lstlisting}
  8215. \fi}
  8216. \end{minipage}
  8217. \end{center}
  8218. Unfortunately, this approach duplicates the two branches from the
  8219. outer \code{if}, and a compiler must never duplicate code! After all,
  8220. the two branches could be very large expressions.
  8221. How can we apply this transformation without duplicating code? In
  8222. other words, how can two different parts of a program refer to one
  8223. piece of code?
  8224. %
  8225. The answer is that we must move away from abstract syntax \emph{trees}
  8226. and instead use \emph{graphs}.
  8227. %
  8228. At the level of x86 assembly, this is straightforward because we can
  8229. label the code for each branch and insert jumps in all the places that
  8230. need to execute the branch. In this way, jump instructions are edges
  8231. in the graph and the basic blocks are the nodes.
  8232. %
  8233. Likewise, our language \LangCIf{} provides the ability to label a
  8234. sequence of statements and to jump to a label via \code{goto}.
  8235. As a preview of what \code{explicate\_control} will do,
  8236. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8237. \code{explicate\_control} on this example. Note how the condition of
  8238. every \code{if} is a comparison operation and that we have not
  8239. duplicated any code but instead have used labels and \code{goto} to
  8240. enable sharing of code.
  8241. \begin{figure}[tbp]
  8242. \begin{tcolorbox}[colback=white]
  8243. {\if\edition\racketEd
  8244. \begin{tabular}{lll}
  8245. \begin{minipage}{0.4\textwidth}
  8246. % cond_test_41.rkt
  8247. \begin{lstlisting}
  8248. (let ([x (read)])
  8249. (let ([y (read)])
  8250. (if (if (< x 1)
  8251. (eq? x 0)
  8252. (eq? x 2))
  8253. (+ y 2)
  8254. (+ y 10))))
  8255. \end{lstlisting}
  8256. \end{minipage}
  8257. &
  8258. $\Rightarrow$
  8259. &
  8260. \begin{minipage}{0.55\textwidth}
  8261. \begin{lstlisting}
  8262. start:
  8263. x = (read);
  8264. y = (read);
  8265. if (< x 1)
  8266. goto block_4;
  8267. else
  8268. goto block_5;
  8269. block_4:
  8270. if (eq? x 0)
  8271. goto block_2;
  8272. else
  8273. goto block_3;
  8274. block_5:
  8275. if (eq? x 2)
  8276. goto block_2;
  8277. else
  8278. goto block_3;
  8279. block_2:
  8280. return (+ y 2);
  8281. block_3:
  8282. return (+ y 10);
  8283. \end{lstlisting}
  8284. \end{minipage}
  8285. \end{tabular}
  8286. \fi}
  8287. {\if\edition\pythonEd
  8288. \begin{tabular}{lll}
  8289. \begin{minipage}{0.4\textwidth}
  8290. % cond_test_41.rkt
  8291. \begin{lstlisting}
  8292. x = input_int()
  8293. y = input_int()
  8294. print(y + 2 \
  8295. if (x == 0 \
  8296. if x < 1 \
  8297. else x == 2) \
  8298. else y + 10)
  8299. \end{lstlisting}
  8300. \end{minipage}
  8301. &
  8302. $\Rightarrow$
  8303. &
  8304. \begin{minipage}{0.55\textwidth}
  8305. \begin{lstlisting}
  8306. start:
  8307. x = input_int()
  8308. y = input_int()
  8309. if x < 1:
  8310. goto block_8
  8311. else:
  8312. goto block_9
  8313. block_8:
  8314. if x == 0:
  8315. goto block_4
  8316. else:
  8317. goto block_5
  8318. block_9:
  8319. if x == 2:
  8320. goto block_6
  8321. else:
  8322. goto block_7
  8323. block_4:
  8324. goto block_2
  8325. block_5:
  8326. goto block_3
  8327. block_6:
  8328. goto block_2
  8329. block_7:
  8330. goto block_3
  8331. block_2:
  8332. tmp_0 = y + 2
  8333. goto block_1
  8334. block_3:
  8335. tmp_0 = y + 10
  8336. goto block_1
  8337. block_1:
  8338. print(tmp_0)
  8339. return 0
  8340. \end{lstlisting}
  8341. \end{minipage}
  8342. \end{tabular}
  8343. \fi}
  8344. \end{tcolorbox}
  8345. \caption{Translation from \LangIf{} to \LangCIf{}
  8346. via the \code{explicate\_control}.}
  8347. \label{fig:explicate-control-s1-38}
  8348. \end{figure}
  8349. {\if\edition\racketEd
  8350. %
  8351. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8352. \code{explicate\_control} for \LangVar{} using two recursive
  8353. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8354. former function translates expressions in tail position, whereas the
  8355. latter function translates expressions on the right-hand side of a
  8356. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8357. have a new kind of position to deal with: the predicate position of
  8358. the \key{if}. We need another function, \code{explicate\_pred}, that
  8359. decides how to compile an \key{if} by analyzing its condition. So,
  8360. \code{explicate\_pred} takes an \LangIf{} expression and two
  8361. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8362. and outputs a tail. In the following paragraphs we discuss specific
  8363. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8364. \code{explicate\_pred} functions.
  8365. %
  8366. \fi}
  8367. %
  8368. {\if\edition\pythonEd
  8369. %
  8370. We recommend implementing \code{explicate\_control} using the
  8371. following four auxiliary functions.
  8372. \begin{description}
  8373. \item[\code{explicate\_effect}] generates code for expressions as
  8374. statements, so their result is ignored and only their side effects
  8375. matter.
  8376. \item[\code{explicate\_assign}] generates code for expressions
  8377. on the right-hand side of an assignment.
  8378. \item[\code{explicate\_pred}] generates code for an \code{if}
  8379. expression or statement by analyzing the condition expression.
  8380. \item[\code{explicate\_stmt}] generates code for statements.
  8381. \end{description}
  8382. These four functions should build the dictionary of basic blocks. The
  8383. following auxiliary function can be used to create a new basic block
  8384. from a list of statements. It returns a \code{goto} statement that
  8385. jumps to the new basic block.
  8386. \begin{center}
  8387. \begin{minipage}{\textwidth}
  8388. \begin{lstlisting}
  8389. def create_block(stmts, basic_blocks):
  8390. label = label_name(generate_name('block'))
  8391. basic_blocks[label] = stmts
  8392. return Goto(label)
  8393. \end{lstlisting}
  8394. \end{minipage}
  8395. \end{center}
  8396. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8397. \code{explicate\_control} pass.
  8398. The \code{explicate\_effect} function has three parameters: 1) the
  8399. expression to be compiled, 2) the already-compiled code for this
  8400. expression's \emph{continuation}, that is, the list of statements that
  8401. should execute after this expression, and 3) the dictionary of
  8402. generated basic blocks. The \code{explicate\_effect} function returns
  8403. a list of \LangCIf{} statements and it may add to the dictionary of
  8404. basic blocks.
  8405. %
  8406. Let's consider a few of the cases for the expression to be compiled.
  8407. If the expression to be compiled is a constant, then it can be
  8408. discarded because it has no side effects. If it's a \CREAD{}, then it
  8409. has a side-effect and should be preserved. So the expression should be
  8410. translated into a statement using the \code{Expr} AST class. If the
  8411. expression to be compiled is an \code{if} expression, we translate the
  8412. two branches using \code{explicate\_effect} and then translate the
  8413. condition expression using \code{explicate\_pred}, which generates
  8414. code for the entire \code{if}.
  8415. The \code{explicate\_assign} function has four parameters: 1) the
  8416. right-hand side of the assignment, 2) the left-hand side of the
  8417. assignment (the variable), 3) the continuation, and 4) the dictionary
  8418. of basic blocks. The \code{explicate\_assign} function returns a list
  8419. of \LangCIf{} statements and it may add to the dictionary of basic
  8420. blocks.
  8421. When the right-hand side is an \code{if} expression, there is some
  8422. work to do. In particular, the two branches should be translated using
  8423. \code{explicate\_assign} and the condition expression should be
  8424. translated using \code{explicate\_pred}. Otherwise we can simply
  8425. generate an assignment statement, with the given left and right-hand
  8426. sides, concatenated with its continuation.
  8427. \begin{figure}[tbp]
  8428. \begin{tcolorbox}[colback=white]
  8429. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8430. def explicate_effect(e, cont, basic_blocks):
  8431. match e:
  8432. case IfExp(test, body, orelse):
  8433. ...
  8434. case Call(func, args):
  8435. ...
  8436. case Begin(body, result):
  8437. ...
  8438. case _:
  8439. ...
  8440. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8441. match rhs:
  8442. case IfExp(test, body, orelse):
  8443. ...
  8444. case Begin(body, result):
  8445. ...
  8446. case _:
  8447. return [Assign([lhs], rhs)] + cont
  8448. def explicate_pred(cnd, thn, els, basic_blocks):
  8449. match cnd:
  8450. case Compare(left, [op], [right]):
  8451. goto_thn = create_block(thn, basic_blocks)
  8452. goto_els = create_block(els, basic_blocks)
  8453. return [If(cnd, [goto_thn], [goto_els])]
  8454. case Constant(True):
  8455. return thn;
  8456. case Constant(False):
  8457. return els;
  8458. case UnaryOp(Not(), operand):
  8459. ...
  8460. case IfExp(test, body, orelse):
  8461. ...
  8462. case Begin(body, result):
  8463. ...
  8464. case _:
  8465. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8466. [create_block(els, basic_blocks)],
  8467. [create_block(thn, basic_blocks)])]
  8468. def explicate_stmt(s, cont, basic_blocks):
  8469. match s:
  8470. case Assign([lhs], rhs):
  8471. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8472. case Expr(value):
  8473. return explicate_effect(value, cont, basic_blocks)
  8474. case If(test, body, orelse):
  8475. ...
  8476. def explicate_control(p):
  8477. match p:
  8478. case Module(body):
  8479. new_body = [Return(Constant(0))]
  8480. basic_blocks = {}
  8481. for s in reversed(body):
  8482. new_body = explicate_stmt(s, new_body, basic_blocks)
  8483. basic_blocks[label_name('start')] = new_body
  8484. return CProgram(basic_blocks)
  8485. \end{lstlisting}
  8486. \end{tcolorbox}
  8487. \caption{Skeleton for the \code{explicate\_control} pass.}
  8488. \label{fig:explicate-control-Lif}
  8489. \end{figure}
  8490. \fi}
  8491. {\if\edition\racketEd
  8492. \subsection{Explicate Tail and Assign}
  8493. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8494. additional cases for Boolean constants and \key{if}. The cases for
  8495. \code{if} should recursively compile the two branches using either
  8496. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8497. cases should then invoke \code{explicate\_pred} on the condition
  8498. expression, passing in the generated code for the two branches. For
  8499. example, consider the following program with an \code{if} in tail
  8500. position.
  8501. % cond_test_6.rkt
  8502. \begin{lstlisting}
  8503. (let ([x (read)])
  8504. (if (eq? x 0) 42 777))
  8505. \end{lstlisting}
  8506. The two branches are recursively compiled to return statements. We
  8507. then delegate to \code{explicate\_pred}, passing the condition
  8508. \code{(eq? x 0)} and the two return statements. We return to this
  8509. example shortly when we discuss \code{explicate\_pred}.
  8510. Next let us consider a program with an \code{if} on the right-hand
  8511. side of a \code{let}.
  8512. \begin{lstlisting}
  8513. (let ([y (read)])
  8514. (let ([x (if (eq? y 0) 40 777)])
  8515. (+ x 2)))
  8516. \end{lstlisting}
  8517. Note that the body of the inner \code{let} will have already been
  8518. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8519. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8520. to recursively process both branches of the \code{if}, and we do not
  8521. want to duplicate code, so we generate the following block using an
  8522. auxiliary function named \code{create\_block}, discussed in the next
  8523. section.
  8524. \begin{lstlisting}
  8525. block_6:
  8526. return (+ x 2)
  8527. \end{lstlisting}
  8528. We then use \code{goto block\_6;} as the \code{cont} argument for
  8529. compiling the branches. So the two branches compile to
  8530. \begin{center}
  8531. \begin{minipage}{0.2\textwidth}
  8532. \begin{lstlisting}
  8533. x = 40;
  8534. goto block_6;
  8535. \end{lstlisting}
  8536. \end{minipage}
  8537. \hspace{0.5in} and \hspace{0.5in}
  8538. \begin{minipage}{0.2\textwidth}
  8539. \begin{lstlisting}
  8540. x = 777;
  8541. goto block_6;
  8542. \end{lstlisting}
  8543. \end{minipage}
  8544. \end{center}
  8545. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8546. \code{(eq? y 0)} and the previously presented code for the branches.
  8547. \subsection{Create Block}
  8548. We recommend implementing the \code{create\_block} auxiliary function
  8549. as follows, using a global variable \code{basic-blocks} to store a
  8550. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8551. that \code{create\_block} generates a new label and then associates
  8552. the given \code{tail} with the new label in the \code{basic-blocks}
  8553. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8554. new label. However, if the given \code{tail} is already a \code{Goto},
  8555. then there is no need to generate a new label and entry in
  8556. \code{basic-blocks}; we can simply return that \code{Goto}.
  8557. %
  8558. \begin{lstlisting}
  8559. (define (create_block tail)
  8560. (match tail
  8561. [(Goto label) (Goto label)]
  8562. [else
  8563. (let ([label (gensym 'block)])
  8564. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8565. (Goto label))]))
  8566. \end{lstlisting}
  8567. \fi}
  8568. {\if\edition\racketEd
  8569. \subsection{Explicate Predicate}
  8570. \begin{figure}[tbp]
  8571. \begin{tcolorbox}[colback=white]
  8572. \begin{lstlisting}
  8573. (define (explicate_pred cnd thn els)
  8574. (match cnd
  8575. [(Var x) ___]
  8576. [(Let x rhs body) ___]
  8577. [(Prim 'not (list e)) ___]
  8578. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8579. (IfStmt (Prim op es) (create_block thn)
  8580. (create_block els))]
  8581. [(Bool b) (if b thn els)]
  8582. [(If cnd^ thn^ els^) ___]
  8583. [else (error "explicate_pred unhandled case" cnd)]))
  8584. \end{lstlisting}
  8585. \end{tcolorbox}
  8586. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8587. \label{fig:explicate-pred}
  8588. \end{figure}
  8589. \fi}
  8590. \racket{The skeleton for the \code{explicate\_pred} function is given
  8591. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  8592. (1) \code{cnd}, the condition expression of the \code{if};
  8593. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  8594. and (3) \code{els}, the code generated by
  8595. explicate for the \emph{else} branch. The \code{explicate\_pred}
  8596. function should match on \code{cnd} with a case for
  8597. every kind of expression that can have type \BOOLTY{}.}
  8598. %
  8599. \python{The \code{explicate\_pred} function has four parameters: 1)
  8600. the condition expression, 2) the generated statements for the
  8601. ``then'' branch, 3) the generated statements for the ``else''
  8602. branch, and 4) the dictionary of basic blocks. The
  8603. \code{explicate\_pred} function returns a list of \LangCIf{}
  8604. statements and it may add to the dictionary of basic blocks.}
  8605. Consider the case for comparison operators. We translate the
  8606. comparison to an \code{if} statement whose branches are \code{goto}
  8607. statements created by applying \code{create\_block} to the code
  8608. generated for the \code{thn} and \code{els} branches. Let us
  8609. illustrate this translation by returning to the program with an
  8610. \code{if} expression in tail position, shown next. We invoke
  8611. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  8612. \python{\code{x == 0}}.
  8613. %
  8614. {\if\edition\racketEd
  8615. \begin{lstlisting}
  8616. (let ([x (read)])
  8617. (if (eq? x 0) 42 777))
  8618. \end{lstlisting}
  8619. \fi}
  8620. %
  8621. {\if\edition\pythonEd
  8622. \begin{lstlisting}
  8623. x = input_int()
  8624. 42 if x == 0 else 777
  8625. \end{lstlisting}
  8626. \fi}
  8627. %
  8628. \noindent The two branches \code{42} and \code{777} were already
  8629. compiled to \code{return} statements, from which we now create the
  8630. following blocks:
  8631. %
  8632. \begin{center}
  8633. \begin{minipage}{\textwidth}
  8634. \begin{lstlisting}
  8635. block_1:
  8636. return 42;
  8637. block_2:
  8638. return 777;
  8639. \end{lstlisting}
  8640. \end{minipage}
  8641. \end{center}
  8642. %
  8643. After that, \code{explicate\_pred} compiles the comparison
  8644. \racket{\code{(eq? x 0)}}
  8645. \python{\code{x == 0}}
  8646. to the following \code{if} statement:
  8647. %
  8648. {\if\edition\racketEd
  8649. \begin{center}
  8650. \begin{minipage}{\textwidth}
  8651. \begin{lstlisting}
  8652. if (eq? x 0)
  8653. goto block_1;
  8654. else
  8655. goto block_2;
  8656. \end{lstlisting}
  8657. \end{minipage}
  8658. \end{center}
  8659. \fi}
  8660. {\if\edition\pythonEd
  8661. \begin{center}
  8662. \begin{minipage}{\textwidth}
  8663. \begin{lstlisting}
  8664. if x == 0:
  8665. goto block_1;
  8666. else
  8667. goto block_2;
  8668. \end{lstlisting}
  8669. \end{minipage}
  8670. \end{center}
  8671. \fi}
  8672. Next consider the case for Boolean constants. We perform a kind of
  8673. partial evaluation\index{subject}{partial evaluation} and output
  8674. either the \code{thn} or \code{els} branch, depending on whether the
  8675. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8676. following program:
  8677. {\if\edition\racketEd
  8678. \begin{lstlisting}
  8679. (if #t 42 777)
  8680. \end{lstlisting}
  8681. \fi}
  8682. {\if\edition\pythonEd
  8683. \begin{lstlisting}
  8684. 42 if True else 777
  8685. \end{lstlisting}
  8686. \fi}
  8687. %
  8688. \noindent Again, the two branches \code{42} and \code{777} were
  8689. compiled to \code{return} statements, so \code{explicate\_pred}
  8690. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8691. code for the \emph{then} branch.
  8692. \begin{lstlisting}
  8693. return 42;
  8694. \end{lstlisting}
  8695. This case demonstrates that we sometimes discard the \code{thn} or
  8696. \code{els} blocks that are input to \code{explicate\_pred}.
  8697. The case for \key{if} expressions in \code{explicate\_pred} is
  8698. particularly illuminating because it deals with the challenges
  8699. discussed previously regarding nested \key{if} expressions
  8700. (figure~\ref{fig:explicate-control-s1-38}). The
  8701. \racket{\lstinline{thn^}}\python{\code{body}} and
  8702. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8703. \key{if} inherit their context from the current one, that is,
  8704. predicate context. So, you should recursively apply
  8705. \code{explicate\_pred} to the
  8706. \racket{\lstinline{thn^}}\python{\code{body}} and
  8707. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8708. those recursive calls, pass \code{thn} and \code{els} as the extra
  8709. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8710. inside each recursive call. As discussed previously, to avoid
  8711. duplicating code, we need to add them to the dictionary of basic
  8712. blocks so that we can instead refer to them by name and execute them
  8713. with a \key{goto}.
  8714. {\if\edition\pythonEd
  8715. %
  8716. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8717. three parameters: 1) the statement to be compiled, 2) the code for its
  8718. continuation, and 3) the dictionary of basic blocks. The
  8719. \code{explicate\_stmt} returns a list of statements and it may add to
  8720. the dictionary of basic blocks. The cases for assignment and an
  8721. expression-statement are given in full in the skeleton code: they
  8722. simply dispatch to \code{explicate\_assign} and
  8723. \code{explicate\_effect}, respectively. The case for \code{if}
  8724. statements is not given, and is similar to the case for \code{if}
  8725. expressions.
  8726. The \code{explicate\_control} function itself is given in
  8727. figure~\ref{fig:explicate-control-Lif}. It applies
  8728. \code{explicate\_stmt} to each statement in the program, from back to
  8729. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8730. used as the continuation parameter in the next call to
  8731. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8732. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8733. the dictionary of basic blocks, labeling it as the ``start'' block.
  8734. %
  8735. \fi}
  8736. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8737. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8738. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8739. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8740. %% results from the two recursive calls. We complete the case for
  8741. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8742. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8743. %% the result $B_5$.
  8744. %% \[
  8745. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8746. %% \quad\Rightarrow\quad
  8747. %% B_5
  8748. %% \]
  8749. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8750. %% inherit the current context, so they are in tail position. Thus, the
  8751. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8752. %% \code{explicate\_tail}.
  8753. %% %
  8754. %% We need to pass $B_0$ as the accumulator argument for both of these
  8755. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8756. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8757. %% to the control-flow graph and obtain a promised goto $G_0$.
  8758. %% %
  8759. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8760. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8761. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8762. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8763. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8764. %% \[
  8765. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8766. %% \]
  8767. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8768. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8769. %% should not be confused with the labels for the blocks that appear in
  8770. %% the generated code. We initially construct unlabeled blocks; we only
  8771. %% attach labels to blocks when we add them to the control-flow graph, as
  8772. %% we see in the next case.
  8773. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8774. %% function. The context of the \key{if} is an assignment to some
  8775. %% variable $x$ and then the control continues to some promised block
  8776. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8777. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8778. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8779. %% branches of the \key{if} inherit the current context, so they are in
  8780. %% assignment positions. Let $B_2$ be the result of applying
  8781. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8782. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8783. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8784. %% the result of applying \code{explicate\_pred} to the predicate
  8785. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8786. %% translates to the promise $B_4$.
  8787. %% \[
  8788. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8789. %% \]
  8790. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8791. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8792. \code{remove\_complex\_operands} pass and then the
  8793. \code{explicate\_control} pass on the example program. We walk through
  8794. the output program.
  8795. %
  8796. Following the order of evaluation in the output of
  8797. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8798. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8799. in the predicate of the inner \key{if}. In the output of
  8800. \code{explicate\_control}, in the
  8801. block labeled \code{start}, two assignment statements are followed by an
  8802. \code{if} statement that branches to \code{block\_4} or
  8803. \code{block\_5}. The blocks associated with those labels contain the
  8804. translations of the code
  8805. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8806. and
  8807. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8808. respectively. In particular, we start \code{block\_4} with the
  8809. comparison
  8810. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8811. and then branch to \code{block\_2} or \code{block\_3},
  8812. which correspond to the two branches of the outer \key{if}, that is,
  8813. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8814. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8815. %
  8816. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8817. %
  8818. \python{The \code{block\_1} corresponds to the \code{print} statement
  8819. at the end of the program.}
  8820. {\if\edition\racketEd
  8821. \subsection{Interactions between Explicate and Shrink}
  8822. The way in which the \code{shrink} pass transforms logical operations
  8823. such as \code{and} and \code{or} can impact the quality of code
  8824. generated by \code{explicate\_control}. For example, consider the
  8825. following program:
  8826. % cond_test_21.rkt, and_eq_input.py
  8827. \begin{lstlisting}
  8828. (if (and (eq? (read) 0) (eq? (read) 1))
  8829. 0
  8830. 42)
  8831. \end{lstlisting}
  8832. The \code{and} operation should transform into something that the
  8833. \code{explicate\_pred} function can analyze and descend through to
  8834. reach the underlying \code{eq?} conditions. Ideally, for this program
  8835. your \code{explicate\_control} pass should generate code similar to
  8836. the following:
  8837. \begin{center}
  8838. \begin{minipage}{\textwidth}
  8839. \begin{lstlisting}
  8840. start:
  8841. tmp1 = (read);
  8842. if (eq? tmp1 0) goto block40;
  8843. else goto block39;
  8844. block40:
  8845. tmp2 = (read);
  8846. if (eq? tmp2 1) goto block38;
  8847. else goto block39;
  8848. block38:
  8849. return 0;
  8850. block39:
  8851. return 42;
  8852. \end{lstlisting}
  8853. \end{minipage}
  8854. \end{center}
  8855. \fi}
  8856. \begin{exercise}\normalfont\normalsize
  8857. \racket{
  8858. Implement the pass \code{explicate\_control} by adding the cases for
  8859. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8860. \code{explicate\_assign} functions. Implement the auxiliary function
  8861. \code{explicate\_pred} for predicate contexts.}
  8862. \python{Implement \code{explicate\_control} pass with its
  8863. four auxiliary functions.}
  8864. %
  8865. Create test cases that exercise all the new cases in the code for
  8866. this pass.
  8867. %
  8868. {\if\edition\racketEd
  8869. Add the following entry to the list of \code{passes} in
  8870. \code{run-tests.rkt}:
  8871. \begin{lstlisting}
  8872. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8873. \end{lstlisting}
  8874. and then run \code{run-tests.rkt} to test your compiler.
  8875. \fi}
  8876. \end{exercise}
  8877. \section{Select Instructions}
  8878. \label{sec:select-Lif}
  8879. \index{subject}{instruction selection}
  8880. The \code{select\_instructions} pass translates \LangCIf{} to
  8881. \LangXIfVar{}.
  8882. %
  8883. \racket{Recall that we implement this pass using three auxiliary
  8884. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8885. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8886. %
  8887. \racket{For $\Atm$, we have new cases for the Booleans.}
  8888. %
  8889. \python{We begin with the Boolean constants.}
  8890. We take the usual approach of encoding them as integers.
  8891. \[
  8892. \TRUE{} \quad\Rightarrow\quad \key{1}
  8893. \qquad\qquad
  8894. \FALSE{} \quad\Rightarrow\quad \key{0}
  8895. \]
  8896. For translating statements, we discuss some of the cases. The
  8897. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8898. discussed at the beginning of this section. Given an assignment, if
  8899. the left-hand-side variable is the same as the argument of \code{not},
  8900. then just the \code{xorq} instruction suffices.
  8901. \[
  8902. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8903. \quad\Rightarrow\quad
  8904. \key{xorq}~\key{\$}1\key{,}~\Var
  8905. \]
  8906. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8907. semantics of x86. In the following translation, let $\Arg$ be the
  8908. result of translating $\Atm$ to x86.
  8909. \[
  8910. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8911. \quad\Rightarrow\quad
  8912. \begin{array}{l}
  8913. \key{movq}~\Arg\key{,}~\Var\\
  8914. \key{xorq}~\key{\$}1\key{,}~\Var
  8915. \end{array}
  8916. \]
  8917. Next consider the cases for equality comparisons. Translating this
  8918. operation to x86 is slightly involved due to the unusual nature of the
  8919. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8920. We recommend translating an assignment with an equality on the
  8921. right-hand side into a sequence of three instructions. \\
  8922. \begin{tabular}{lll}
  8923. \begin{minipage}{0.4\textwidth}
  8924. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8925. \end{minipage}
  8926. &
  8927. $\Rightarrow$
  8928. &
  8929. \begin{minipage}{0.4\textwidth}
  8930. \begin{lstlisting}
  8931. cmpq |$\Arg_2$|, |$\Arg_1$|
  8932. sete %al
  8933. movzbq %al, |$\Var$|
  8934. \end{lstlisting}
  8935. \end{minipage}
  8936. \end{tabular} \\
  8937. The translations for the other comparison operators are similar to
  8938. this but use different condition codes for the \code{set} instruction.
  8939. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8940. \key{goto} and \key{if} statements. Both are straightforward to
  8941. translate to x86.}
  8942. %
  8943. A \key{goto} statement becomes a jump instruction.
  8944. \[
  8945. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8946. \]
  8947. %
  8948. An \key{if} statement becomes a compare instruction followed by a
  8949. conditional jump (for the \emph{then} branch), and the fall-through is to
  8950. a regular jump (for the \emph{else} branch).\\
  8951. \begin{tabular}{lll}
  8952. \begin{minipage}{0.4\textwidth}
  8953. \begin{lstlisting}
  8954. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8955. goto |$\ell_1$||$\racket{\key{;}}$|
  8956. else|$\python{\key{:}}$|
  8957. goto |$\ell_2$||$\racket{\key{;}}$|
  8958. \end{lstlisting}
  8959. \end{minipage}
  8960. &
  8961. $\Rightarrow$
  8962. &
  8963. \begin{minipage}{0.4\textwidth}
  8964. \begin{lstlisting}
  8965. cmpq |$\Arg_2$|, |$\Arg_1$|
  8966. je |$\ell_1$|
  8967. jmp |$\ell_2$|
  8968. \end{lstlisting}
  8969. \end{minipage}
  8970. \end{tabular} \\
  8971. Again, the translations for the other comparison operators are similar to this
  8972. but use different condition codes for the conditional jump instruction.
  8973. \python{Regarding the \key{return} statement, we recommend treating it
  8974. as an assignment to the \key{rax} register followed by a jump to the
  8975. conclusion of the \code{main} function.}
  8976. \begin{exercise}\normalfont\normalsize
  8977. Expand your \code{select\_instructions} pass to handle the new
  8978. features of the \LangCIf{} language.
  8979. %
  8980. {\if\edition\racketEd
  8981. Add the following entry to the list of \code{passes} in
  8982. \code{run-tests.rkt}
  8983. \begin{lstlisting}
  8984. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8985. \end{lstlisting}
  8986. \fi}
  8987. %
  8988. Run the script to test your compiler on all the test programs.
  8989. \end{exercise}
  8990. \section{Register Allocation}
  8991. \label{sec:register-allocation-Lif}
  8992. \index{subject}{register allocation}
  8993. The changes required for compiling \LangIf{} affect liveness analysis,
  8994. building the interference graph, and assigning homes, but the graph
  8995. coloring algorithm itself does not change.
  8996. \subsection{Liveness Analysis}
  8997. \label{sec:liveness-analysis-Lif}
  8998. \index{subject}{liveness analysis}
  8999. Recall that for \LangVar{} we implemented liveness analysis for a
  9000. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9001. the addition of \key{if} expressions to \LangIf{},
  9002. \code{explicate\_control} produces many basic blocks.
  9003. %% We recommend that you create a new auxiliary function named
  9004. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9005. %% control-flow graph.
  9006. The first question is, in what order should we process the basic blocks?
  9007. Recall that to perform liveness analysis on a basic block we need to
  9008. know the live-after set for the last instruction in the block. If a
  9009. basic block has no successors (i.e., contains no jumps to other
  9010. blocks), then it has an empty live-after set and we can immediately
  9011. apply liveness analysis to it. If a basic block has some successors,
  9012. then we need to complete liveness analysis on those blocks
  9013. first. These ordering constraints are the reverse of a
  9014. \emph{topological order}\index{subject}{topological order} on a graph
  9015. representation of the program. In particular, the \emph{control flow
  9016. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9017. of a program has a node for each basic block and an edge for each jump
  9018. from one block to another. It is straightforward to generate a CFG
  9019. from the dictionary of basic blocks. One then transposes the CFG and
  9020. applies the topological sort algorithm.
  9021. %
  9022. %
  9023. \racket{We recommend using the \code{tsort} and \code{transpose}
  9024. functions of the Racket \code{graph} package to accomplish this.}
  9025. %
  9026. \python{We provide implementations of \code{topological\_sort} and
  9027. \code{transpose} in the file \code{graph.py} of the support code.}
  9028. %
  9029. As an aside, a topological ordering is only guaranteed to exist if the
  9030. graph does not contain any cycles. This is the case for the
  9031. control-flow graphs that we generate from \LangIf{} programs.
  9032. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9033. and learn how to handle cycles in the control-flow graph.
  9034. \racket{You need to construct a directed graph to represent the
  9035. control-flow graph. Do not use the \code{directed-graph} of the
  9036. \code{graph} package because that allows at most one edge
  9037. between each pair of vertices, whereas a control-flow graph may have
  9038. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9039. file in the support code implements a graph representation that
  9040. allows multiple edges between a pair of vertices.}
  9041. {\if\edition\racketEd
  9042. The next question is how to analyze jump instructions. Recall that in
  9043. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9044. \code{label->live} that maps each label to the set of live locations
  9045. at the beginning of its block. We use \code{label->live} to determine
  9046. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9047. that we have many basic blocks, \code{label->live} needs to be updated
  9048. as we process the blocks. In particular, after performing liveness
  9049. analysis on a block, we take the live-before set of its first
  9050. instruction and associate that with the block's label in the
  9051. \code{label->live} alist.
  9052. \fi}
  9053. %
  9054. {\if\edition\pythonEd
  9055. %
  9056. The next question is how to analyze jump instructions. The locations
  9057. that are live before a \code{jmp} should be the locations in
  9058. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9059. maintaining a dictionary named \code{live\_before\_block} that maps each
  9060. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9061. block. After performing liveness analysis on each block, we take the
  9062. live-before set of its first instruction and associate that with the
  9063. block's label in the \code{live\_before\_block} dictionary.
  9064. %
  9065. \fi}
  9066. In \LangXIfVar{} we also have the conditional jump
  9067. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9068. this instruction is particularly interesting because during
  9069. compilation, we do not know which way a conditional jump will go. Thus
  9070. we do not know whether to use the live-before set for the block
  9071. associated with the $\itm{label}$ or the live-before set for the
  9072. following instruction. However, there is no harm to the correctness
  9073. of the generated code if we classify more locations as live than the
  9074. ones that are truly live during one particular execution of the
  9075. instruction. Thus, we can take the union of the live-before sets from
  9076. the following instruction and from the mapping for $\itm{label}$ in
  9077. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9078. The auxiliary functions for computing the variables in an
  9079. instruction's argument and for computing the variables read-from ($R$)
  9080. or written-to ($W$) by an instruction need to be updated to handle the
  9081. new kinds of arguments and instructions in \LangXIfVar{}.
  9082. \begin{exercise}\normalfont\normalsize
  9083. {\if\edition\racketEd
  9084. %
  9085. Update the \code{uncover\_live} pass to apply liveness analysis to
  9086. every basic block in the program.
  9087. %
  9088. Add the following entry to the list of \code{passes} in the
  9089. \code{run-tests.rkt} script:
  9090. \begin{lstlisting}
  9091. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9092. \end{lstlisting}
  9093. \fi}
  9094. {\if\edition\pythonEd
  9095. %
  9096. Update the \code{uncover\_live} function to perform liveness analysis,
  9097. in reverse topological order, on all the basic blocks in the
  9098. program.
  9099. %
  9100. \fi}
  9101. % Check that the live-after sets that you generate for
  9102. % example X matches the following... -Jeremy
  9103. \end{exercise}
  9104. \subsection{Build the Interference Graph}
  9105. \label{sec:build-interference-Lif}
  9106. Many of the new instructions in \LangXIfVar{} can be handled in the
  9107. same way as the instructions in \LangXVar{}.
  9108. % Thus, if your code was
  9109. % already quite general, it will not need to be changed to handle the
  9110. % new instructions. If your code is not general enough, we recommend that
  9111. % you change your code to be more general. For example, you can factor
  9112. % out the computing of the the read and write sets for each kind of
  9113. % instruction into auxiliary functions.
  9114. %
  9115. Some instructions, such as the \key{movzbq} instruction, require special care,
  9116. similar to the \key{movq} instruction. Refer to rule number 1 in
  9117. section~\ref{sec:build-interference}.
  9118. \begin{exercise}\normalfont\normalsize
  9119. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9120. {\if\edition\racketEd
  9121. Add the following entries to the list of \code{passes} in the
  9122. \code{run-tests.rkt} script:
  9123. \begin{lstlisting}
  9124. (list "build_interference" build_interference interp-pseudo-x86-1)
  9125. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9126. \end{lstlisting}
  9127. \fi}
  9128. % Check that the interference graph that you generate for
  9129. % example X matches the following graph G... -Jeremy
  9130. \end{exercise}
  9131. \section{Patch Instructions}
  9132. The new instructions \key{cmpq} and \key{movzbq} have some special
  9133. restrictions that need to be handled in the \code{patch\_instructions}
  9134. pass.
  9135. %
  9136. The second argument of the \key{cmpq} instruction must not be an
  9137. immediate value (such as an integer). So, if you are comparing two
  9138. immediates, we recommend inserting a \key{movq} instruction to put the
  9139. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9140. one memory reference.
  9141. %
  9142. The second argument of the \key{movzbq} must be a register.
  9143. \begin{exercise}\normalfont\normalsize
  9144. %
  9145. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9146. %
  9147. {\if\edition\racketEd
  9148. Add the following entry to the list of \code{passes} in
  9149. \code{run-tests.rkt}, and then run this script to test your compiler.
  9150. \begin{lstlisting}
  9151. (list "patch_instructions" patch_instructions interp-x86-1)
  9152. \end{lstlisting}
  9153. \fi}
  9154. \end{exercise}
  9155. {\if\edition\pythonEd
  9156. \section{Prelude and Conclusion}
  9157. \label{sec:prelude-conclusion-cond}
  9158. The generation of the \code{main} function with its prelude and
  9159. conclusion must change to accommodate how the program now consists of
  9160. one or more basic blocks. After the prelude in \code{main}, jump to
  9161. the \code{start} block. Place the conclusion in a basic block labeled
  9162. with \code{conclusion}.
  9163. \fi}
  9164. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9165. \LangIf{} translated to x86, showing the results of
  9166. \code{explicate\_control}, \code{select\_instructions}, and the final
  9167. x86 assembly.
  9168. \begin{figure}[tbp]
  9169. \begin{tcolorbox}[colback=white]
  9170. {\if\edition\racketEd
  9171. \begin{tabular}{lll}
  9172. \begin{minipage}{0.4\textwidth}
  9173. % cond_test_20.rkt, eq_input.py
  9174. \begin{lstlisting}
  9175. (if (eq? (read) 1) 42 0)
  9176. \end{lstlisting}
  9177. $\Downarrow$
  9178. \begin{lstlisting}
  9179. start:
  9180. tmp7951 = (read);
  9181. if (eq? tmp7951 1)
  9182. goto block7952;
  9183. else
  9184. goto block7953;
  9185. block7952:
  9186. return 42;
  9187. block7953:
  9188. return 0;
  9189. \end{lstlisting}
  9190. $\Downarrow$
  9191. \begin{lstlisting}
  9192. start:
  9193. callq read_int
  9194. movq %rax, tmp7951
  9195. cmpq $1, tmp7951
  9196. je block7952
  9197. jmp block7953
  9198. block7953:
  9199. movq $0, %rax
  9200. jmp conclusion
  9201. block7952:
  9202. movq $42, %rax
  9203. jmp conclusion
  9204. \end{lstlisting}
  9205. \end{minipage}
  9206. &
  9207. $\Rightarrow\qquad$
  9208. \begin{minipage}{0.4\textwidth}
  9209. \begin{lstlisting}
  9210. start:
  9211. callq read_int
  9212. movq %rax, %rcx
  9213. cmpq $1, %rcx
  9214. je block7952
  9215. jmp block7953
  9216. block7953:
  9217. movq $0, %rax
  9218. jmp conclusion
  9219. block7952:
  9220. movq $42, %rax
  9221. jmp conclusion
  9222. .globl main
  9223. main:
  9224. pushq %rbp
  9225. movq %rsp, %rbp
  9226. pushq %r13
  9227. pushq %r12
  9228. pushq %rbx
  9229. pushq %r14
  9230. subq $0, %rsp
  9231. jmp start
  9232. conclusion:
  9233. addq $0, %rsp
  9234. popq %r14
  9235. popq %rbx
  9236. popq %r12
  9237. popq %r13
  9238. popq %rbp
  9239. retq
  9240. \end{lstlisting}
  9241. \end{minipage}
  9242. \end{tabular}
  9243. \fi}
  9244. {\if\edition\pythonEd
  9245. \begin{tabular}{lll}
  9246. \begin{minipage}{0.4\textwidth}
  9247. % cond_test_20.rkt, eq_input.py
  9248. \begin{lstlisting}
  9249. print(42 if input_int() == 1 else 0)
  9250. \end{lstlisting}
  9251. $\Downarrow$
  9252. \begin{lstlisting}
  9253. start:
  9254. tmp_0 = input_int()
  9255. if tmp_0 == 1:
  9256. goto block_3
  9257. else:
  9258. goto block_4
  9259. block_3:
  9260. tmp_1 = 42
  9261. goto block_2
  9262. block_4:
  9263. tmp_1 = 0
  9264. goto block_2
  9265. block_2:
  9266. print(tmp_1)
  9267. return 0
  9268. \end{lstlisting}
  9269. $\Downarrow$
  9270. \begin{lstlisting}
  9271. start:
  9272. callq read_int
  9273. movq %rax, tmp_0
  9274. cmpq 1, tmp_0
  9275. je block_3
  9276. jmp block_4
  9277. block_3:
  9278. movq 42, tmp_1
  9279. jmp block_2
  9280. block_4:
  9281. movq 0, tmp_1
  9282. jmp block_2
  9283. block_2:
  9284. movq tmp_1, %rdi
  9285. callq print_int
  9286. movq 0, %rax
  9287. jmp conclusion
  9288. \end{lstlisting}
  9289. \end{minipage}
  9290. &
  9291. $\Rightarrow\qquad$
  9292. \begin{minipage}{0.4\textwidth}
  9293. \begin{lstlisting}
  9294. .globl main
  9295. main:
  9296. pushq %rbp
  9297. movq %rsp, %rbp
  9298. subq $0, %rsp
  9299. jmp start
  9300. start:
  9301. callq read_int
  9302. movq %rax, %rcx
  9303. cmpq $1, %rcx
  9304. je block_3
  9305. jmp block_4
  9306. block_3:
  9307. movq $42, %rcx
  9308. jmp block_2
  9309. block_4:
  9310. movq $0, %rcx
  9311. jmp block_2
  9312. block_2:
  9313. movq %rcx, %rdi
  9314. callq print_int
  9315. movq $0, %rax
  9316. jmp conclusion
  9317. conclusion:
  9318. addq $0, %rsp
  9319. popq %rbp
  9320. retq
  9321. \end{lstlisting}
  9322. \end{minipage}
  9323. \end{tabular}
  9324. \fi}
  9325. \end{tcolorbox}
  9326. \caption{Example compilation of an \key{if} expression to x86, showing
  9327. the results of \code{explicate\_control},
  9328. \code{select\_instructions}, and the final x86 assembly code. }
  9329. \label{fig:if-example-x86}
  9330. \end{figure}
  9331. \begin{figure}[tbp]
  9332. \begin{tcolorbox}[colback=white]
  9333. {\if\edition\racketEd
  9334. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9335. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9336. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9337. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9338. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9339. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9340. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9341. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9342. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9343. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9344. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9345. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9346. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9347. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9348. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9349. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  9350. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9351. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9352. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9353. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9354. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9355. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9356. \end{tikzpicture}
  9357. \fi}
  9358. {\if\edition\pythonEd
  9359. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9360. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9361. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9362. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9363. \node (C-1) at (0,0) {\large \LangCIf{}};
  9364. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9365. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9366. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9367. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9368. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9369. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9370. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  9371. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9372. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9373. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9374. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9375. \end{tikzpicture}
  9376. \fi}
  9377. \end{tcolorbox}
  9378. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9379. \label{fig:Lif-passes}
  9380. \end{figure}
  9381. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9382. compilation of \LangIf{}.
  9383. \section{Challenge: Optimize Blocks and Remove Jumps}
  9384. \label{sec:opt-jumps}
  9385. We discuss two optional challenges that involve optimizing the
  9386. control-flow of the program.
  9387. \subsection{Optimize Blocks}
  9388. The algorithm for \code{explicate\_control} that we discussed in
  9389. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9390. blocks. It creates a basic block whenever a continuation \emph{might}
  9391. get used more than once (e.g., whenever the \code{cont} parameter is
  9392. passed into two or more recursive calls). However, some continuation
  9393. arguments may not be used at all. For example, consider the case for
  9394. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9395. \code{els} continuation.
  9396. %
  9397. {\if\edition\racketEd
  9398. The following example program falls into this
  9399. case, and it creates two unused blocks.
  9400. \begin{center}
  9401. \begin{tabular}{lll}
  9402. \begin{minipage}{0.4\textwidth}
  9403. % cond_test_82.rkt
  9404. \begin{lstlisting}
  9405. (let ([y (if #t
  9406. (read)
  9407. (if (eq? (read) 0)
  9408. 777
  9409. (let ([x (read)])
  9410. (+ 1 x))))])
  9411. (+ y 2))
  9412. \end{lstlisting}
  9413. \end{minipage}
  9414. &
  9415. $\Rightarrow$
  9416. &
  9417. \begin{minipage}{0.55\textwidth}
  9418. \begin{lstlisting}
  9419. start:
  9420. y = (read);
  9421. goto block_5;
  9422. block_5:
  9423. return (+ y 2);
  9424. block_6:
  9425. y = 777;
  9426. goto block_5;
  9427. block_7:
  9428. x = (read);
  9429. y = (+ 1 x2);
  9430. goto block_5;
  9431. \end{lstlisting}
  9432. \end{minipage}
  9433. \end{tabular}
  9434. \end{center}
  9435. \fi}
  9436. The question is, how can we decide whether to create a basic block?
  9437. \emph{Lazy evaluation}\index{subject}{lazy
  9438. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9439. delaying the creation of a basic block until the point in time at which
  9440. we know that it will be used.
  9441. %
  9442. {\if\edition\racketEd
  9443. %
  9444. Racket provides support for
  9445. lazy evaluation with the
  9446. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9447. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9448. \index{subject}{delay} creates a
  9449. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9450. expressions is postponed. When \key{(force}
  9451. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9452. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9453. result of $e_n$ is cached in the promise and returned. If \code{force}
  9454. is applied again to the same promise, then the cached result is
  9455. returned. If \code{force} is applied to an argument that is not a
  9456. promise, \code{force} simply returns the argument.
  9457. %
  9458. \fi}
  9459. %
  9460. {\if\edition\pythonEd
  9461. %
  9462. While Python does not provide direct support for lazy evaluation, it
  9463. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9464. by wrapping it inside a function with no parameters. We can
  9465. \emph{force} its evaluation by calling the function. However, in some
  9466. cases of \code{explicate\_pred}, etc., we will return a list of
  9467. statements and in other cases we will return a function that computes
  9468. a list of statements. We use the term \emph{promise} to refer to a
  9469. value that may be delayed. To uniformly deal with
  9470. promises, we define the following \code{force} function that checks
  9471. whether its input is delayed (i.e., whether it is a function) and then
  9472. either 1) calls the function, or 2) returns the input.
  9473. \begin{lstlisting}
  9474. def force(promise):
  9475. if isinstance(promise, types.FunctionType):
  9476. return promise()
  9477. else:
  9478. return promise
  9479. \end{lstlisting}
  9480. %
  9481. \fi}
  9482. We use promises for the input and output of the functions
  9483. \code{explicate\_pred}, \code{explicate\_assign},
  9484. %
  9485. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9486. %
  9487. So, instead of taking and returning \racket{$\Tail$
  9488. expressions}\python{lists of statements}, they take and return
  9489. promises. Furthermore, when we come to a situation in which a
  9490. continuation might be used more than once, as in the case for
  9491. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9492. that creates a basic block for each continuation (if there is not
  9493. already one) and then returns a \code{goto} statement to that basic
  9494. block. When we come to a situation in which we have a promise but need an
  9495. actual piece of code, for example, to create a larger piece of code with a
  9496. constructor such as \code{Seq}, then insert a call to \code{force}.
  9497. %
  9498. {\if\edition\racketEd
  9499. %
  9500. Also, we must modify the \code{create\_block} function to begin with
  9501. \code{delay} to create a promise. When forced, this promise forces the
  9502. original promise. If that returns a \code{Goto} (because the block was
  9503. already added to \code{basic-blocks}), then we return the
  9504. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9505. return a \code{Goto} to the new label.
  9506. \begin{center}
  9507. \begin{minipage}{\textwidth}
  9508. \begin{lstlisting}
  9509. (define (create_block tail)
  9510. (delay
  9511. (define t (force tail))
  9512. (match t
  9513. [(Goto label) (Goto label)]
  9514. [else
  9515. (let ([label (gensym 'block)])
  9516. (set! basic-blocks (cons (cons label t) basic-blocks))
  9517. (Goto label))])))
  9518. \end{lstlisting}
  9519. \end{minipage}
  9520. \end{center}
  9521. \fi}
  9522. {\if\edition\pythonEd
  9523. %
  9524. Here is the new version of the \code{create\_block} auxiliary function
  9525. that works on promises and that checks whether the block consists of a
  9526. solitary \code{goto} statement.\\
  9527. \begin{minipage}{\textwidth}
  9528. \begin{lstlisting}
  9529. def create_block(promise, basic_blocks):
  9530. stmts = force(promise)
  9531. match stmts:
  9532. case [Goto(l)]:
  9533. return Goto(l)
  9534. case _:
  9535. label = label_name(generate_name('block'))
  9536. basic_blocks[label] = stmts
  9537. return Goto(label)
  9538. \end{lstlisting}
  9539. \end{minipage}
  9540. \fi}
  9541. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9542. improved \code{explicate\_control} on this example. As you can
  9543. see, the number of basic blocks has been reduced from four blocks (see
  9544. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9545. \begin{figure}[tbp]
  9546. \begin{tcolorbox}[colback=white]
  9547. {\if\edition\racketEd
  9548. \begin{tabular}{lll}
  9549. \begin{minipage}{0.4\textwidth}
  9550. % cond_test_82.rkt
  9551. \begin{lstlisting}
  9552. (let ([y (if #t
  9553. (read)
  9554. (if (eq? (read) 0)
  9555. 777
  9556. (let ([x (read)])
  9557. (+ 1 x))))])
  9558. (+ y 2))
  9559. \end{lstlisting}
  9560. \end{minipage}
  9561. &
  9562. $\Rightarrow$
  9563. &
  9564. \begin{minipage}{0.55\textwidth}
  9565. \begin{lstlisting}
  9566. start:
  9567. y = (read);
  9568. goto block_5;
  9569. block_5:
  9570. return (+ y 2);
  9571. \end{lstlisting}
  9572. \end{minipage}
  9573. \end{tabular}
  9574. \fi}
  9575. {\if\edition\pythonEd
  9576. \begin{tabular}{lll}
  9577. \begin{minipage}{0.4\textwidth}
  9578. % cond_test_41.rkt
  9579. \begin{lstlisting}
  9580. x = input_int()
  9581. y = input_int()
  9582. print(y + 2 \
  9583. if (x == 0 \
  9584. if x < 1 \
  9585. else x == 2) \
  9586. else y + 10)
  9587. \end{lstlisting}
  9588. \end{minipage}
  9589. &
  9590. $\Rightarrow$
  9591. &
  9592. \begin{minipage}{0.55\textwidth}
  9593. \begin{lstlisting}
  9594. start:
  9595. x = input_int()
  9596. y = input_int()
  9597. if x < 1:
  9598. goto block_4
  9599. else:
  9600. goto block_5
  9601. block_4:
  9602. if x == 0:
  9603. goto block_2
  9604. else:
  9605. goto block_3
  9606. block_5:
  9607. if x == 2:
  9608. goto block_2
  9609. else:
  9610. goto block_3
  9611. block_2:
  9612. tmp_0 = y + 2
  9613. goto block_1
  9614. block_3:
  9615. tmp_0 = y + 10
  9616. goto block_1
  9617. block_1:
  9618. print(tmp_0)
  9619. return 0
  9620. \end{lstlisting}
  9621. \end{minipage}
  9622. \end{tabular}
  9623. \fi}
  9624. \end{tcolorbox}
  9625. \caption{Translation from \LangIf{} to \LangCIf{}
  9626. via the improved \code{explicate\_control}.}
  9627. \label{fig:explicate-control-challenge}
  9628. \end{figure}
  9629. %% Recall that in the example output of \code{explicate\_control} in
  9630. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9631. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9632. %% block. The first goal of this challenge assignment is to remove those
  9633. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9634. %% \code{explicate\_control} on the left and shows the result of bypassing
  9635. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9636. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9637. %% \code{block55}. The optimized code on the right of
  9638. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9639. %% \code{then} branch jumping directly to \code{block55}. The story is
  9640. %% similar for the \code{else} branch, as well as for the two branches in
  9641. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9642. %% have been optimized in this way, there are no longer any jumps to
  9643. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9644. %% \begin{figure}[tbp]
  9645. %% \begin{tabular}{lll}
  9646. %% \begin{minipage}{0.4\textwidth}
  9647. %% \begin{lstlisting}
  9648. %% block62:
  9649. %% tmp54 = (read);
  9650. %% if (eq? tmp54 2) then
  9651. %% goto block59;
  9652. %% else
  9653. %% goto block60;
  9654. %% block61:
  9655. %% tmp53 = (read);
  9656. %% if (eq? tmp53 0) then
  9657. %% goto block57;
  9658. %% else
  9659. %% goto block58;
  9660. %% block60:
  9661. %% goto block56;
  9662. %% block59:
  9663. %% goto block55;
  9664. %% block58:
  9665. %% goto block56;
  9666. %% block57:
  9667. %% goto block55;
  9668. %% block56:
  9669. %% return (+ 700 77);
  9670. %% block55:
  9671. %% return (+ 10 32);
  9672. %% start:
  9673. %% tmp52 = (read);
  9674. %% if (eq? tmp52 1) then
  9675. %% goto block61;
  9676. %% else
  9677. %% goto block62;
  9678. %% \end{lstlisting}
  9679. %% \end{minipage}
  9680. %% &
  9681. %% $\Rightarrow$
  9682. %% &
  9683. %% \begin{minipage}{0.55\textwidth}
  9684. %% \begin{lstlisting}
  9685. %% block62:
  9686. %% tmp54 = (read);
  9687. %% if (eq? tmp54 2) then
  9688. %% goto block55;
  9689. %% else
  9690. %% goto block56;
  9691. %% block61:
  9692. %% tmp53 = (read);
  9693. %% if (eq? tmp53 0) then
  9694. %% goto block55;
  9695. %% else
  9696. %% goto block56;
  9697. %% block56:
  9698. %% return (+ 700 77);
  9699. %% block55:
  9700. %% return (+ 10 32);
  9701. %% start:
  9702. %% tmp52 = (read);
  9703. %% if (eq? tmp52 1) then
  9704. %% goto block61;
  9705. %% else
  9706. %% goto block62;
  9707. %% \end{lstlisting}
  9708. %% \end{minipage}
  9709. %% \end{tabular}
  9710. %% \caption{Optimize jumps by removing trivial blocks.}
  9711. %% \label{fig:optimize-jumps}
  9712. %% \end{figure}
  9713. %% The name of this pass is \code{optimize-jumps}. We recommend
  9714. %% implementing this pass in two phases. The first phrase builds a hash
  9715. %% table that maps labels to possibly improved labels. The second phase
  9716. %% changes the target of each \code{goto} to use the improved label. If
  9717. %% the label is for a trivial block, then the hash table should map the
  9718. %% label to the first non-trivial block that can be reached from this
  9719. %% label by jumping through trivial blocks. If the label is for a
  9720. %% non-trivial block, then the hash table should map the label to itself;
  9721. %% we do not want to change jumps to non-trivial blocks.
  9722. %% The first phase can be accomplished by constructing an empty hash
  9723. %% table, call it \code{short-cut}, and then iterating over the control
  9724. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9725. %% then update the hash table, mapping the block's source to the target
  9726. %% of the \code{goto}. Also, the hash table may already have mapped some
  9727. %% labels to the block's source, to you must iterate through the hash
  9728. %% table and update all of those so that they instead map to the target
  9729. %% of the \code{goto}.
  9730. %% For the second phase, we recommend iterating through the $\Tail$ of
  9731. %% each block in the program, updating the target of every \code{goto}
  9732. %% according to the mapping in \code{short-cut}.
  9733. \begin{exercise}\normalfont\normalsize
  9734. Implement the improvements to the \code{explicate\_control} pass.
  9735. Check that it removes trivial blocks in a few example programs. Then
  9736. check that your compiler still passes all your tests.
  9737. \end{exercise}
  9738. \subsection{Remove Jumps}
  9739. There is an opportunity for removing jumps that is apparent in the
  9740. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9741. ends with a jump to \code{block\_5}, and there are no other jumps to
  9742. \code{block\_5} in the rest of the program. In this situation we can
  9743. avoid the runtime overhead of this jump by merging \code{block\_5}
  9744. into the preceding block, which in this case is the \code{start} block.
  9745. Figure~\ref{fig:remove-jumps} shows the output of
  9746. \code{allocate\_registers} on the left and the result of this
  9747. optimization on the right.
  9748. \begin{figure}[tbp]
  9749. \begin{tcolorbox}[colback=white]
  9750. {\if\edition\racketEd
  9751. \begin{tabular}{lll}
  9752. \begin{minipage}{0.5\textwidth}
  9753. % cond_test_82.rkt
  9754. \begin{lstlisting}
  9755. start:
  9756. callq read_int
  9757. movq %rax, %rcx
  9758. jmp block_5
  9759. block_5:
  9760. movq %rcx, %rax
  9761. addq $2, %rax
  9762. jmp conclusion
  9763. \end{lstlisting}
  9764. \end{minipage}
  9765. &
  9766. $\Rightarrow\qquad$
  9767. \begin{minipage}{0.4\textwidth}
  9768. \begin{lstlisting}
  9769. start:
  9770. callq read_int
  9771. movq %rax, %rcx
  9772. movq %rcx, %rax
  9773. addq $2, %rax
  9774. jmp conclusion
  9775. \end{lstlisting}
  9776. \end{minipage}
  9777. \end{tabular}
  9778. \fi}
  9779. {\if\edition\pythonEd
  9780. \begin{tabular}{lll}
  9781. \begin{minipage}{0.5\textwidth}
  9782. % cond_test_20.rkt
  9783. \begin{lstlisting}
  9784. start:
  9785. callq read_int
  9786. movq %rax, tmp_0
  9787. cmpq 1, tmp_0
  9788. je block_3
  9789. jmp block_4
  9790. block_3:
  9791. movq 42, tmp_1
  9792. jmp block_2
  9793. block_4:
  9794. movq 0, tmp_1
  9795. jmp block_2
  9796. block_2:
  9797. movq tmp_1, %rdi
  9798. callq print_int
  9799. movq 0, %rax
  9800. jmp conclusion
  9801. \end{lstlisting}
  9802. \end{minipage}
  9803. &
  9804. $\Rightarrow\qquad$
  9805. \begin{minipage}{0.4\textwidth}
  9806. \begin{lstlisting}
  9807. start:
  9808. callq read_int
  9809. movq %rax, tmp_0
  9810. cmpq 1, tmp_0
  9811. je block_3
  9812. movq 0, tmp_1
  9813. jmp block_2
  9814. block_3:
  9815. movq 42, tmp_1
  9816. jmp block_2
  9817. block_2:
  9818. movq tmp_1, %rdi
  9819. callq print_int
  9820. movq 0, %rax
  9821. jmp conclusion
  9822. \end{lstlisting}
  9823. \end{minipage}
  9824. \end{tabular}
  9825. \fi}
  9826. \end{tcolorbox}
  9827. \caption{Merging basic blocks by removing unnecessary jumps.}
  9828. \label{fig:remove-jumps}
  9829. \end{figure}
  9830. \begin{exercise}\normalfont\normalsize
  9831. %
  9832. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9833. into their preceding basic block, when there is only one preceding
  9834. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9835. %
  9836. {\if\edition\racketEd
  9837. In the \code{run-tests.rkt} script, add the following entry to the
  9838. list of \code{passes} between \code{allocate\_registers}
  9839. and \code{patch\_instructions}:
  9840. \begin{lstlisting}
  9841. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9842. \end{lstlisting}
  9843. \fi}
  9844. %
  9845. Run the script to test your compiler.
  9846. %
  9847. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9848. blocks on several test programs.
  9849. \end{exercise}
  9850. \section{Further Reading}
  9851. \label{sec:cond-further-reading}
  9852. The algorithm for the \code{explicate\_control} pass is based on the
  9853. \code{expose-basic-blocks} pass in the course notes of
  9854. \citet{Dybvig:2010aa}.
  9855. %
  9856. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9857. \citet{Appel:2003fk}, and is related to translations into continuation
  9858. passing
  9859. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9860. %
  9861. The treatment of conditionals in the \code{explicate\_control} pass is
  9862. similar to short-cut boolean
  9863. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9864. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9865. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9866. \chapter{Loops and Dataflow Analysis}
  9867. \label{ch:Lwhile}
  9868. \setcounter{footnote}{0}
  9869. % TODO: define R'_8
  9870. % TODO: multi-graph
  9871. {\if\edition\racketEd
  9872. %
  9873. In this chapter we study two features that are the hallmarks of
  9874. imperative programming languages: loops and assignments to local
  9875. variables. The following example demonstrates these new features by
  9876. computing the sum of the first five positive integers:
  9877. % similar to loop_test_1.rkt
  9878. \begin{lstlisting}
  9879. (let ([sum 0])
  9880. (let ([i 5])
  9881. (begin
  9882. (while (> i 0)
  9883. (begin
  9884. (set! sum (+ sum i))
  9885. (set! i (- i 1))))
  9886. sum)))
  9887. \end{lstlisting}
  9888. The \code{while} loop consists of a condition and a
  9889. body.\footnote{The \code{while} loop is not a built-in
  9890. feature of the Racket language, but Racket includes many looping
  9891. constructs and it is straightforward to define \code{while} as a
  9892. macro.} The body is evaluated repeatedly so long as the condition
  9893. remains true.
  9894. %
  9895. The \code{set!} consists of a variable and a right-hand side
  9896. expression. The \code{set!} updates value of the variable to the
  9897. value of the right-hand side.
  9898. %
  9899. The primary purpose of both the \code{while} loop and \code{set!} is
  9900. to cause side effects, so they do not give a meaningful result
  9901. value. Instead, their result is the \code{\#<void>} value. The
  9902. expression \code{(void)} is an explicit way to create the
  9903. \code{\#<void>} value, and it has type \code{Void}. The
  9904. \code{\#<void>} value can be passed around just like other values
  9905. inside an \LangLoop{} program, and it can be compared for equality with
  9906. another \code{\#<void>} value. However, there are no other operations
  9907. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9908. Racket defines the \code{void?} predicate that returns \code{\#t}
  9909. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9910. %
  9911. \footnote{Racket's \code{Void} type corresponds to what is often
  9912. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9913. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9914. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9915. %
  9916. With the addition of side effect-producing features such as
  9917. \code{while} loop and \code{set!}, it is helpful to include a language
  9918. feature for sequencing side effects: the \code{begin} expression. It
  9919. consists of one or more subexpressions that are evaluated
  9920. left to right.
  9921. %
  9922. \fi}
  9923. {\if\edition\pythonEd
  9924. %
  9925. In this chapter we study loops, one of the hallmarks of imperative
  9926. programming languages. The following example demonstrates the
  9927. \code{while} loop by computing the sum of the first five positive
  9928. integers.
  9929. \begin{lstlisting}
  9930. sum = 0
  9931. i = 5
  9932. while i > 0:
  9933. sum = sum + i
  9934. i = i - 1
  9935. print(sum)
  9936. \end{lstlisting}
  9937. The \code{while} loop consists of a condition expression and a body (a
  9938. sequence of statements). The body is evaluated repeatedly so long as
  9939. the condition remains true.
  9940. %
  9941. \fi}
  9942. \section{The \LangLoop{} Language}
  9943. \newcommand{\LwhileGrammarRacket}{
  9944. \begin{array}{lcl}
  9945. \Type &::=& \key{Void}\\
  9946. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9947. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9948. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9949. \end{array}
  9950. }
  9951. \newcommand{\LwhileASTRacket}{
  9952. \begin{array}{lcl}
  9953. \Type &::=& \key{Void}\\
  9954. \Exp &::=& \SETBANG{\Var}{\Exp}
  9955. \MID \BEGIN{\Exp^{*}}{\Exp}
  9956. \MID \WHILE{\Exp}{\Exp}
  9957. \MID \VOID{}
  9958. \end{array}
  9959. }
  9960. \newcommand{\LwhileGrammarPython}{
  9961. \begin{array}{rcl}
  9962. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9963. \end{array}
  9964. }
  9965. \newcommand{\LwhileASTPython}{
  9966. \begin{array}{lcl}
  9967. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9968. \end{array}
  9969. }
  9970. \begin{figure}[tp]
  9971. \centering
  9972. \begin{tcolorbox}[colback=white]
  9973. \small
  9974. {\if\edition\racketEd
  9975. \[
  9976. \begin{array}{l}
  9977. \gray{\LintGrammarRacket{}} \\ \hline
  9978. \gray{\LvarGrammarRacket{}} \\ \hline
  9979. \gray{\LifGrammarRacket{}} \\ \hline
  9980. \LwhileGrammarRacket \\
  9981. \begin{array}{lcl}
  9982. \LangLoopM{} &::=& \Exp
  9983. \end{array}
  9984. \end{array}
  9985. \]
  9986. \fi}
  9987. {\if\edition\pythonEd
  9988. \[
  9989. \begin{array}{l}
  9990. \gray{\LintGrammarPython} \\ \hline
  9991. \gray{\LvarGrammarPython} \\ \hline
  9992. \gray{\LifGrammarPython} \\ \hline
  9993. \LwhileGrammarPython \\
  9994. \begin{array}{rcl}
  9995. \LangLoopM{} &::=& \Stmt^{*}
  9996. \end{array}
  9997. \end{array}
  9998. \]
  9999. \fi}
  10000. \end{tcolorbox}
  10001. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10002. \label{fig:Lwhile-concrete-syntax}
  10003. \end{figure}
  10004. \begin{figure}[tp]
  10005. \centering
  10006. \begin{tcolorbox}[colback=white]
  10007. \small
  10008. {\if\edition\racketEd
  10009. \[
  10010. \begin{array}{l}
  10011. \gray{\LintOpAST} \\ \hline
  10012. \gray{\LvarASTRacket{}} \\ \hline
  10013. \gray{\LifASTRacket{}} \\ \hline
  10014. \LwhileASTRacket{} \\
  10015. \begin{array}{lcl}
  10016. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10017. \end{array}
  10018. \end{array}
  10019. \]
  10020. \fi}
  10021. {\if\edition\pythonEd
  10022. \[
  10023. \begin{array}{l}
  10024. \gray{\LintASTPython} \\ \hline
  10025. \gray{\LvarASTPython} \\ \hline
  10026. \gray{\LifASTPython} \\ \hline
  10027. \LwhileASTPython \\
  10028. \begin{array}{lcl}
  10029. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10030. \end{array}
  10031. \end{array}
  10032. \]
  10033. \fi}
  10034. \end{tcolorbox}
  10035. \python{
  10036. \index{subject}{While@\texttt{While}}
  10037. }
  10038. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10039. \label{fig:Lwhile-syntax}
  10040. \end{figure}
  10041. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10042. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10043. shows the definition of its abstract syntax.
  10044. %
  10045. The definitional interpreter for \LangLoop{} is shown in
  10046. figure~\ref{fig:interp-Lwhile}.
  10047. %
  10048. {\if\edition\racketEd
  10049. %
  10050. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10051. and \code{Void}, and we make changes to the cases for \code{Var} and
  10052. \code{Let} regarding variables. To support assignment to variables and
  10053. to make their lifetimes indefinite (see the second example in
  10054. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10055. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10056. value.
  10057. %
  10058. Now we discuss the new cases. For \code{SetBang}, we find the
  10059. variable in the environment to obtain a boxed value, and then we change
  10060. it using \code{set-box!} to the result of evaluating the right-hand
  10061. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10062. %
  10063. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10064. if the result is true, (2) evaluate the body.
  10065. The result value of a \code{while} loop is also \code{\#<void>}.
  10066. %
  10067. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10068. subexpressions \itm{es} for their effects and then evaluates
  10069. and returns the result from \itm{body}.
  10070. %
  10071. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10072. %
  10073. \fi}
  10074. {\if\edition\pythonEd
  10075. %
  10076. We add a new case for \code{While} in the \code{interp\_stmts}
  10077. function, where we repeatedly interpret the \code{body} so long as the
  10078. \code{test} expression remains true.
  10079. %
  10080. \fi}
  10081. \begin{figure}[tbp]
  10082. \begin{tcolorbox}[colback=white]
  10083. {\if\edition\racketEd
  10084. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10085. (define interp-Lwhile-class
  10086. (class interp-Lif-class
  10087. (super-new)
  10088. (define/override ((interp-exp env) e)
  10089. (define recur (interp-exp env))
  10090. (match e
  10091. [(Let x e body)
  10092. (define new-env (dict-set env x (box (recur e))))
  10093. ((interp-exp new-env) body)]
  10094. [(Var x) (unbox (dict-ref env x))]
  10095. [(SetBang x rhs)
  10096. (set-box! (dict-ref env x) (recur rhs))]
  10097. [(WhileLoop cnd body)
  10098. (define (loop)
  10099. (cond [(recur cnd) (recur body) (loop)]
  10100. [else (void)]))
  10101. (loop)]
  10102. [(Begin es body)
  10103. (for ([e es]) (recur e))
  10104. (recur body)]
  10105. [(Void) (void)]
  10106. [else ((super interp-exp env) e)]))
  10107. ))
  10108. (define (interp-Lwhile p)
  10109. (send (new interp-Lwhile-class) interp-program p))
  10110. \end{lstlisting}
  10111. \fi}
  10112. {\if\edition\pythonEd
  10113. \begin{lstlisting}
  10114. class InterpLwhile(InterpLif):
  10115. def interp_stmts(self, ss, env):
  10116. if len(ss) == 0:
  10117. return
  10118. match ss[0]:
  10119. case While(test, body, []):
  10120. while self.interp_exp(test, env):
  10121. self.interp_stmts(body, env)
  10122. return self.interp_stmts(ss[1:], env)
  10123. case _:
  10124. return super().interp_stmts(ss, env)
  10125. \end{lstlisting}
  10126. \fi}
  10127. \end{tcolorbox}
  10128. \caption{Interpreter for \LangLoop{}.}
  10129. \label{fig:interp-Lwhile}
  10130. \end{figure}
  10131. The definition of the type checker for \LangLoop{} is shown in
  10132. figure~\ref{fig:type-check-Lwhile}.
  10133. %
  10134. {\if\edition\racketEd
  10135. %
  10136. The type checking of the \code{SetBang} expression requires the type
  10137. of the variable and the right-hand side to agree. The result type is
  10138. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10139. and the result type is \code{Void}. For \code{Begin}, the result type
  10140. is the type of its last subexpression.
  10141. %
  10142. \fi}
  10143. %
  10144. {\if\edition\pythonEd
  10145. %
  10146. A \code{while} loop is well typed if the type of the \code{test}
  10147. expression is \code{bool} and the statements in the \code{body} are
  10148. well typed.
  10149. %
  10150. \fi}
  10151. \begin{figure}[tbp]
  10152. \begin{tcolorbox}[colback=white]
  10153. {\if\edition\racketEd
  10154. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10155. (define type-check-Lwhile-class
  10156. (class type-check-Lif-class
  10157. (super-new)
  10158. (inherit check-type-equal?)
  10159. (define/override (type-check-exp env)
  10160. (lambda (e)
  10161. (define recur (type-check-exp env))
  10162. (match e
  10163. [(SetBang x rhs)
  10164. (define-values (rhs^ rhsT) (recur rhs))
  10165. (define varT (dict-ref env x))
  10166. (check-type-equal? rhsT varT e)
  10167. (values (SetBang x rhs^) 'Void)]
  10168. [(WhileLoop cnd body)
  10169. (define-values (cnd^ Tc) (recur cnd))
  10170. (check-type-equal? Tc 'Boolean e)
  10171. (define-values (body^ Tbody) ((type-check-exp env) body))
  10172. (values (WhileLoop cnd^ body^) 'Void)]
  10173. [(Begin es body)
  10174. (define-values (es^ ts)
  10175. (for/lists (l1 l2) ([e es]) (recur e)))
  10176. (define-values (body^ Tbody) (recur body))
  10177. (values (Begin es^ body^) Tbody)]
  10178. [else ((super type-check-exp env) e)])))
  10179. ))
  10180. (define (type-check-Lwhile p)
  10181. (send (new type-check-Lwhile-class) type-check-program p))
  10182. \end{lstlisting}
  10183. \fi}
  10184. {\if\edition\pythonEd
  10185. \begin{lstlisting}
  10186. class TypeCheckLwhile(TypeCheckLif):
  10187. def type_check_stmts(self, ss, env):
  10188. if len(ss) == 0:
  10189. return
  10190. match ss[0]:
  10191. case While(test, body, []):
  10192. test_t = self.type_check_exp(test, env)
  10193. check_type_equal(bool, test_t, test)
  10194. body_t = self.type_check_stmts(body, env)
  10195. return self.type_check_stmts(ss[1:], env)
  10196. case _:
  10197. return super().type_check_stmts(ss, env)
  10198. \end{lstlisting}
  10199. \fi}
  10200. \end{tcolorbox}
  10201. \caption{Type checker for the \LangLoop{} language.}
  10202. \label{fig:type-check-Lwhile}
  10203. \end{figure}
  10204. {\if\edition\racketEd
  10205. %
  10206. At first glance, the translation of these language features to x86
  10207. seems straightforward because the \LangCIf{} intermediate language
  10208. already supports all the ingredients that we need: assignment,
  10209. \code{goto}, conditional branching, and sequencing. However, there are
  10210. complications that arise, which we discuss in the next section. After
  10211. that we introduce the changes necessary to the existing passes.
  10212. %
  10213. \fi}
  10214. {\if\edition\pythonEd
  10215. %
  10216. At first glance, the translation of \code{while} loops to x86 seems
  10217. straightforward because the \LangCIf{} intermediate language already
  10218. supports \code{goto} and conditional branching. However, there are
  10219. complications that arise which we discuss in the next section. After
  10220. that we introduce the changes necessary to the existing passes.
  10221. %
  10222. \fi}
  10223. \section{Cyclic Control Flow and Dataflow Analysis}
  10224. \label{sec:dataflow-analysis}
  10225. Up until this point, the programs generated in
  10226. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10227. \code{while} loop introduces a cycle. Does that matter?
  10228. %
  10229. Indeed, it does. Recall that for register allocation, the compiler
  10230. performs liveness analysis to determine which variables can share the
  10231. same register. To accomplish this, we analyzed the control-flow graph
  10232. in reverse topological order
  10233. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10234. well defined only for acyclic graphs.
  10235. Let us return to the example of computing the sum of the first five
  10236. positive integers. Here is the program after instruction selection but
  10237. before register allocation.
  10238. \begin{center}
  10239. {\if\edition\racketEd
  10240. \begin{minipage}{0.45\textwidth}
  10241. \begin{lstlisting}
  10242. (define (main) : Integer
  10243. mainstart:
  10244. movq $0, sum
  10245. movq $5, i
  10246. jmp block5
  10247. block5:
  10248. movq i, tmp3
  10249. cmpq tmp3, $0
  10250. jl block7
  10251. jmp block8
  10252. \end{lstlisting}
  10253. \end{minipage}
  10254. \begin{minipage}{0.45\textwidth}
  10255. \begin{lstlisting}
  10256. block7:
  10257. addq i, sum
  10258. movq $1, tmp4
  10259. negq tmp4
  10260. addq tmp4, i
  10261. jmp block5
  10262. block8:
  10263. movq $27, %rax
  10264. addq sum, %rax
  10265. jmp mainconclusion
  10266. )
  10267. \end{lstlisting}
  10268. \end{minipage}
  10269. \fi}
  10270. {\if\edition\pythonEd
  10271. \begin{minipage}{0.45\textwidth}
  10272. \begin{lstlisting}
  10273. mainstart:
  10274. movq $0, sum
  10275. movq $5, i
  10276. jmp block5
  10277. block5:
  10278. cmpq $0, i
  10279. jg block7
  10280. jmp block8
  10281. \end{lstlisting}
  10282. \end{minipage}
  10283. \begin{minipage}{0.45\textwidth}
  10284. \begin{lstlisting}
  10285. block7:
  10286. addq i, sum
  10287. subq $1, i
  10288. jmp block5
  10289. block8:
  10290. movq sum, %rdi
  10291. callq print_int
  10292. movq $0, %rax
  10293. jmp mainconclusion
  10294. \end{lstlisting}
  10295. \end{minipage}
  10296. \fi}
  10297. \end{center}
  10298. Recall that liveness analysis works backward, starting at the end
  10299. of each function. For this example we could start with \code{block8}
  10300. because we know what is live at the beginning of the conclusion:
  10301. only \code{rax} and \code{rsp}. So the live-before set
  10302. for \code{block8} is \code{\{rsp,sum\}}.
  10303. %
  10304. Next we might try to analyze \code{block5} or \code{block7}, but
  10305. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10306. we are stuck.
  10307. The way out of this impasse is to realize that we can compute an
  10308. underapproximation of each live-before set by starting with empty
  10309. live-after sets. By \emph{underapproximation}, we mean that the set
  10310. contains only variables that are live for some execution of the
  10311. program, but the set may be missing some variables that are live.
  10312. Next, the underapproximations for each block can be improved by (1)
  10313. updating the live-after set for each block using the approximate
  10314. live-before sets from the other blocks, and (2) performing liveness
  10315. analysis again on each block. In fact, by iterating this process, the
  10316. underapproximations eventually become the correct solutions!
  10317. %
  10318. This approach of iteratively analyzing a control-flow graph is
  10319. applicable to many static analysis problems and goes by the name
  10320. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10321. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10322. Washington.
  10323. Let us apply this approach to the previously presented example. We use
  10324. the empty set for the initial live-before set for each block. Let
  10325. $m_0$ be the following mapping from label names to sets of locations
  10326. (variables and registers):
  10327. \begin{center}
  10328. \begin{lstlisting}
  10329. mainstart: {}, block5: {}, block7: {}, block8: {}
  10330. \end{lstlisting}
  10331. \end{center}
  10332. Using the above live-before approximations, we determine the
  10333. live-after for each block and then apply liveness analysis to each
  10334. block. This produces our next approximation $m_1$ of the live-before
  10335. sets.
  10336. \begin{center}
  10337. \begin{lstlisting}
  10338. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10339. \end{lstlisting}
  10340. \end{center}
  10341. For the second round, the live-after for \code{mainstart} is the
  10342. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10343. the liveness analysis for \code{mainstart} computes the empty set. The
  10344. live-after for \code{block5} is the union of the live-before sets for
  10345. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  10346. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  10347. sum\}}. The live-after for \code{block7} is the live-before for
  10348. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10349. So the liveness analysis for \code{block7} remains \code{\{i,
  10350. sum\}}. Together these yield the following approximation $m_2$ of
  10351. the live-before sets:
  10352. \begin{center}
  10353. \begin{lstlisting}
  10354. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10355. \end{lstlisting}
  10356. \end{center}
  10357. In the preceding iteration, only \code{block5} changed, so we can
  10358. limit our attention to \code{mainstart} and \code{block7}, the two
  10359. blocks that jump to \code{block5}. As a result, the live-before sets
  10360. for \code{mainstart} and \code{block7} are updated to include
  10361. \code{rsp}, yielding the following approximation $m_3$:
  10362. \begin{center}
  10363. \begin{lstlisting}
  10364. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10365. \end{lstlisting}
  10366. \end{center}
  10367. Because \code{block7} changed, we analyze \code{block5} once more, but
  10368. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10369. our approximations have converged, so $m_3$ is the solution.
  10370. This iteration process is guaranteed to converge to a solution by the
  10371. Kleene fixed-point theorem, a general theorem about functions on
  10372. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10373. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10374. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10375. join operator
  10376. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10377. ordering}\index{subject}{join}\footnote{Technically speaking, we
  10378. will be working with join semilattices.} When two elements are
  10379. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10380. as much information as $m_i$, so we can think of $m_j$ as a
  10381. better-than-or-equal-to approximation in relation to $m_i$. The
  10382. bottom element $\bot$ represents the complete lack of information,
  10383. that is, the worst approximation. The join operator takes two lattice
  10384. elements and combines their information; that is, it produces the
  10385. least upper bound of the two.\index{subject}{least upper bound}
  10386. A dataflow analysis typically involves two lattices: one lattice to
  10387. represent abstract states and another lattice that aggregates the
  10388. abstract states of all the blocks in the control-flow graph. For
  10389. liveness analysis, an abstract state is a set of locations. We form
  10390. the lattice $L$ by taking its elements to be sets of locations, the
  10391. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10392. set, and the join operator to be set union.
  10393. %
  10394. We form a second lattice $M$ by taking its elements to be mappings
  10395. from the block labels to sets of locations (elements of $L$). We
  10396. order the mappings point-wise, using the ordering of $L$. So, given any
  10397. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10398. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10399. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10400. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10401. We can think of one iteration of liveness analysis applied to the
  10402. whole program as being a function $f$ on the lattice $M$. It takes a
  10403. mapping as input and computes a new mapping.
  10404. \[
  10405. f(m_i) = m_{i+1}
  10406. \]
  10407. Next let us think for a moment about what a final solution $m_s$
  10408. should look like. If we perform liveness analysis using the solution
  10409. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10410. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10411. \[
  10412. f(m_s) = m_s
  10413. \]
  10414. Furthermore, the solution should include only locations that are
  10415. forced to be there by performing liveness analysis on the program, so
  10416. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10417. The Kleene fixed-point theorem states that if a function $f$ is
  10418. monotone (better inputs produce better outputs), then the least fixed
  10419. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10420. chain} obtained by starting at $\bot$ and iterating $f$, as
  10421. follows:\index{subject}{Kleene fixed-point theorem}
  10422. \[
  10423. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10424. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10425. \]
  10426. When a lattice contains only finitely long ascending chains, then
  10427. every Kleene chain tops out at some fixed point after some number of
  10428. iterations of $f$.
  10429. \[
  10430. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10431. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10432. \]
  10433. The liveness analysis is indeed a monotone function and the lattice
  10434. $M$ has finitely long ascending chains because there are only a
  10435. finite number of variables and blocks in the program. Thus we are
  10436. guaranteed that iteratively applying liveness analysis to all blocks
  10437. in the program will eventually produce the least fixed point solution.
  10438. Next let us consider dataflow analysis in general and discuss the
  10439. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10440. %
  10441. The algorithm has four parameters: the control-flow graph \code{G}, a
  10442. function \code{transfer} that applies the analysis to one block, and the
  10443. \code{bottom} and \code{join} operators for the lattice of abstract
  10444. states. The \code{analyze\_dataflow} function is formulated as a
  10445. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10446. function come from the predecessor nodes in the control-flow
  10447. graph. However, liveness analysis is a \emph{backward} dataflow
  10448. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10449. function with the transpose of the control-flow graph.
  10450. The algorithm begins by creating the bottom mapping, represented by a
  10451. hash table. It then pushes all the nodes in the control-flow graph
  10452. onto the work list (a queue). The algorithm repeats the \code{while}
  10453. loop as long as there are items in the work list. In each iteration, a
  10454. node is popped from the work list and processed. The \code{input} for
  10455. the node is computed by taking the join of the abstract states of all
  10456. the predecessor nodes. The \code{transfer} function is then applied to
  10457. obtain the \code{output} abstract state. If the output differs from
  10458. the previous state for this block, the mapping for this block is
  10459. updated and its successor nodes are pushed onto the work list.
  10460. \begin{figure}[tb]
  10461. \begin{tcolorbox}[colback=white]
  10462. {\if\edition\racketEd
  10463. \begin{lstlisting}
  10464. (define (analyze_dataflow G transfer bottom join)
  10465. (define mapping (make-hash))
  10466. (for ([v (in-vertices G)])
  10467. (dict-set! mapping v bottom))
  10468. (define worklist (make-queue))
  10469. (for ([v (in-vertices G)])
  10470. (enqueue! worklist v))
  10471. (define trans-G (transpose G))
  10472. (while (not (queue-empty? worklist))
  10473. (define node (dequeue! worklist))
  10474. (define input (for/fold ([state bottom])
  10475. ([pred (in-neighbors trans-G node)])
  10476. (join state (dict-ref mapping pred))))
  10477. (define output (transfer node input))
  10478. (cond [(not (equal? output (dict-ref mapping node)))
  10479. (dict-set! mapping node output)
  10480. (for ([v (in-neighbors G node)])
  10481. (enqueue! worklist v))]))
  10482. mapping)
  10483. \end{lstlisting}
  10484. \fi}
  10485. {\if\edition\pythonEd
  10486. \begin{lstlisting}
  10487. def analyze_dataflow(G, transfer, bottom, join):
  10488. trans_G = transpose(G)
  10489. mapping = dict((v, bottom) for v in G.vertices())
  10490. worklist = deque(G.vertices)
  10491. while worklist:
  10492. node = worklist.pop()
  10493. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10494. input = reduce(join, inputs, bottom)
  10495. output = transfer(node, input)
  10496. if output != mapping[node]:
  10497. mapping[node] = output
  10498. worklist.extend(G.adjacent(node))
  10499. \end{lstlisting}
  10500. \fi}
  10501. \end{tcolorbox}
  10502. \caption{Generic work list algorithm for dataflow analysis}
  10503. \label{fig:generic-dataflow}
  10504. \end{figure}
  10505. {\if\edition\racketEd
  10506. \section{Mutable Variables and Remove Complex Operands}
  10507. There is a subtle interaction between the
  10508. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10509. and the left-to-right order of evaluation of Racket. Consider the
  10510. following example:
  10511. \begin{lstlisting}
  10512. (let ([x 2])
  10513. (+ x (begin (set! x 40) x)))
  10514. \end{lstlisting}
  10515. The result of this program is \code{42} because the first read from
  10516. \code{x} produces \code{2} and the second produces \code{40}. However,
  10517. if we naively apply the \code{remove\_complex\_operands} pass to this
  10518. example we obtain the following program whose result is \code{80}!
  10519. \begin{lstlisting}
  10520. (let ([x 2])
  10521. (let ([tmp (begin (set! x 40) x)])
  10522. (+ x tmp)))
  10523. \end{lstlisting}
  10524. The problem is that with mutable variables, the ordering between
  10525. reads and writes is important, and the
  10526. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10527. before the first read of \code{x}.
  10528. We recommend solving this problem by giving special treatment to reads
  10529. from mutable variables, that is, variables that occur on the left-hand
  10530. side of a \code{set!}. We mark each read from a mutable variable with
  10531. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10532. that the read operation is effectful in that it can produce different
  10533. results at different points in time. Let's apply this idea to the
  10534. following variation that also involves a variable that is not mutated:
  10535. % loop_test_24.rkt
  10536. \begin{lstlisting}
  10537. (let ([x 2])
  10538. (let ([y 0])
  10539. (+ y (+ x (begin (set! x 40) x)))))
  10540. \end{lstlisting}
  10541. We first analyze this program to discover that variable \code{x}
  10542. is mutable but \code{y} is not. We then transform the program as
  10543. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10544. \begin{lstlisting}
  10545. (let ([x 2])
  10546. (let ([y 0])
  10547. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10548. \end{lstlisting}
  10549. Now that we have a clear distinction between reads from mutable and
  10550. immutable variables, we can apply the \code{remove\_complex\_operands}
  10551. pass, where reads from immutable variables are still classified as
  10552. atomic expressions but reads from mutable variables are classified as
  10553. complex. Thus, \code{remove\_complex\_operands} yields the following
  10554. program:\\
  10555. \begin{minipage}{\textwidth}
  10556. \begin{lstlisting}
  10557. (let ([x 2])
  10558. (let ([y 0])
  10559. (+ y (let ([t1 (get! x)])
  10560. (let ([t2 (begin (set! x 40) (get! x))])
  10561. (+ t1 t2))))))
  10562. \end{lstlisting}
  10563. \end{minipage}
  10564. The temporary variable \code{t1} gets the value of \code{x} before the
  10565. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10566. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10567. do not generate a temporary variable for the occurrence of \code{y}
  10568. because it's an immutable variable. We want to avoid such unnecessary
  10569. extra temporaries because they would needless increase the number of
  10570. variables, making it more likely for some of them to be spilled. The
  10571. result of this program is \code{42}, the same as the result prior to
  10572. \code{remove\_complex\_operands}.
  10573. The approach that we've sketched requires only a small
  10574. modification to \code{remove\_complex\_operands} to handle
  10575. \code{get!}. However, it requires a new pass, called
  10576. \code{uncover-get!}, that we discuss in
  10577. section~\ref{sec:uncover-get-bang}.
  10578. As an aside, this problematic interaction between \code{set!} and the
  10579. pass \code{remove\_complex\_operands} is particular to Racket and not
  10580. its predecessor, the Scheme language. The key difference is that
  10581. Scheme does not specify an order of evaluation for the arguments of an
  10582. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10583. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10584. would be correct results for the example program. Interestingly,
  10585. Racket is implemented on top of the Chez Scheme
  10586. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10587. presented in this section (using extra \code{let} bindings to control
  10588. the order of evaluation) is used in the translation from Racket to
  10589. Scheme~\citep{Flatt:2019tb}.
  10590. \fi} % racket
  10591. Having discussed the complications that arise from adding support for
  10592. assignment and loops, we turn to discussing the individual compilation
  10593. passes.
  10594. {\if\edition\racketEd
  10595. \section{Uncover \texttt{get!}}
  10596. \label{sec:uncover-get-bang}
  10597. The goal of this pass is to mark uses of mutable variables so that
  10598. \code{remove\_complex\_operands} can treat them as complex expressions
  10599. and thereby preserve their ordering relative to the side effects in
  10600. other operands. So, the first step is to collect all the mutable
  10601. variables. We recommend creating an auxiliary function for this,
  10602. named \code{collect-set!}, that recursively traverses expressions,
  10603. returning the set of all variables that occur on the left-hand side of a
  10604. \code{set!}. Here's an excerpt of its implementation.
  10605. \begin{center}
  10606. \begin{minipage}{\textwidth}
  10607. \begin{lstlisting}
  10608. (define (collect-set! e)
  10609. (match e
  10610. [(Var x) (set)]
  10611. [(Int n) (set)]
  10612. [(Let x rhs body)
  10613. (set-union (collect-set! rhs) (collect-set! body))]
  10614. [(SetBang var rhs)
  10615. (set-union (set var) (collect-set! rhs))]
  10616. ...))
  10617. \end{lstlisting}
  10618. \end{minipage}
  10619. \end{center}
  10620. By placing this pass after \code{uniquify}, we need not worry about
  10621. variable shadowing, and our logic for \code{Let} can remain simple, as
  10622. in this excerpt.
  10623. The second step is to mark the occurrences of the mutable variables
  10624. with the new \code{GetBang} AST node (\code{get!} in concrete
  10625. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10626. function, which takes two parameters: the set of mutable variables
  10627. \code{set!-vars} and the expression \code{e} to be processed. The
  10628. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10629. mutable variable or leaves it alone if not.
  10630. \begin{center}
  10631. \begin{minipage}{\textwidth}
  10632. \begin{lstlisting}
  10633. (define ((uncover-get!-exp set!-vars) e)
  10634. (match e
  10635. [(Var x)
  10636. (if (set-member? set!-vars x)
  10637. (GetBang x)
  10638. (Var x))]
  10639. ...))
  10640. \end{lstlisting}
  10641. \end{minipage}
  10642. \end{center}
  10643. To wrap things up, define the \code{uncover-get!} function for
  10644. processing a whole program, using \code{collect-set!} to obtain the
  10645. set of mutable variables and then \code{uncover-get!-exp} to replace
  10646. their occurrences with \code{GetBang}.
  10647. \fi}
  10648. \section{Remove Complex Operands}
  10649. \label{sec:rco-loop}
  10650. {\if\edition\racketEd
  10651. %
  10652. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10653. \code{while} are all complex expressions. The subexpressions of
  10654. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10655. %
  10656. \fi}
  10657. {\if\edition\pythonEd
  10658. %
  10659. The change needed for this pass is to add a case for the \code{while}
  10660. statement. The condition of a \code{while} loop is allowed to be a
  10661. complex expression, just like the condition of the \code{if}
  10662. statement.
  10663. %
  10664. \fi}
  10665. %
  10666. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10667. \LangLoopANF{} of this pass.
  10668. \newcommand{\LwhileMonadASTRacket}{
  10669. \begin{array}{rcl}
  10670. \Atm &::=& \VOID{} \\
  10671. \Exp &::=& \GETBANG{\Var}
  10672. \MID \SETBANG{\Var}{\Exp}
  10673. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10674. &\MID& \WHILE{\Exp}{\Exp}
  10675. \end{array}
  10676. }
  10677. \newcommand{\LwhileMonadASTPython}{
  10678. \begin{array}{rcl}
  10679. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10680. \end{array}
  10681. }
  10682. \begin{figure}[tp]
  10683. \centering
  10684. \begin{tcolorbox}[colback=white]
  10685. \small
  10686. {\if\edition\racketEd
  10687. \[
  10688. \begin{array}{l}
  10689. \gray{\LvarMonadASTRacket} \\ \hline
  10690. \gray{\LifMonadASTRacket} \\ \hline
  10691. \LwhileMonadASTRacket \\
  10692. \begin{array}{rcl}
  10693. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10694. \end{array}
  10695. \end{array}
  10696. \]
  10697. \fi}
  10698. {\if\edition\pythonEd
  10699. \[
  10700. \begin{array}{l}
  10701. \gray{\LvarMonadASTPython} \\ \hline
  10702. \gray{\LifMonadASTPython} \\ \hline
  10703. \LwhileMonadASTPython \\
  10704. \begin{array}{rcl}
  10705. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10706. \end{array}
  10707. \end{array}
  10708. %% \begin{array}{rcl}
  10709. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10710. %% \Exp &::=& \Atm \MID \READ{} \\
  10711. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10712. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10713. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10714. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10715. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10716. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10717. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10718. %% \end{array}
  10719. \]
  10720. \fi}
  10721. \end{tcolorbox}
  10722. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10723. \label{fig:Lwhile-anf-syntax}
  10724. \end{figure}
  10725. {\if\edition\racketEd
  10726. %
  10727. As usual, when a complex expression appears in a grammar position that
  10728. needs to be atomic, such as the argument of a primitive operator, we
  10729. must introduce a temporary variable and bind it to the complex
  10730. expression. This approach applies, unchanged, to handle the new
  10731. language forms. For example, in the following code there are two
  10732. \code{begin} expressions appearing as arguments to the \code{+}
  10733. operator. The output of \code{rco\_exp} is then shown, in which the
  10734. \code{begin} expressions have been bound to temporary
  10735. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10736. allowed to have arbitrary expressions in their right-hand side
  10737. expression, so it is fine to place \code{begin} there.
  10738. %
  10739. \begin{center}
  10740. \begin{tabular}{lcl}
  10741. \begin{minipage}{0.4\textwidth}
  10742. \begin{lstlisting}
  10743. (let ([x2 10])
  10744. (let ([y3 0])
  10745. (+ (+ (begin
  10746. (set! y3 (read))
  10747. (get! x2))
  10748. (begin
  10749. (set! x2 (read))
  10750. (get! y3)))
  10751. (get! x2))))
  10752. \end{lstlisting}
  10753. \end{minipage}
  10754. &
  10755. $\Rightarrow$
  10756. &
  10757. \begin{minipage}{0.4\textwidth}
  10758. \begin{lstlisting}
  10759. (let ([x2 10])
  10760. (let ([y3 0])
  10761. (let ([tmp4 (begin
  10762. (set! y3 (read))
  10763. x2)])
  10764. (let ([tmp5 (begin
  10765. (set! x2 (read))
  10766. y3)])
  10767. (let ([tmp6 (+ tmp4 tmp5)])
  10768. (let ([tmp7 x2])
  10769. (+ tmp6 tmp7)))))))
  10770. \end{lstlisting}
  10771. \end{minipage}
  10772. \end{tabular}
  10773. \end{center}
  10774. \fi}
  10775. \section{Explicate Control \racket{and \LangCLoop{}}}
  10776. \label{sec:explicate-loop}
  10777. \newcommand{\CloopASTRacket}{
  10778. \begin{array}{lcl}
  10779. \Atm &::=& \VOID \\
  10780. \Stmt &::=& \READ{}
  10781. \end{array}
  10782. }
  10783. {\if\edition\racketEd
  10784. Recall that in the \code{explicate\_control} pass we define one helper
  10785. function for each kind of position in the program. For the \LangVar{}
  10786. language of integers and variables, we needed assignment and tail
  10787. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10788. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10789. another kind of position: effect position. Except for the last
  10790. subexpression, the subexpressions inside a \code{begin} are evaluated
  10791. only for their effect. Their result values are discarded. We can
  10792. generate better code by taking this fact into account.
  10793. The output language of \code{explicate\_control} is \LangCLoop{}
  10794. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10795. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10796. and that \code{read} may appear as a statement. The most significant
  10797. difference between the programs generated by \code{explicate\_control}
  10798. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10799. chapter is that the control-flow graphs of the latter may contain
  10800. cycles.
  10801. \begin{figure}[tp]
  10802. \begin{tcolorbox}[colback=white]
  10803. \small
  10804. \[
  10805. \begin{array}{l}
  10806. \gray{\CvarASTRacket} \\ \hline
  10807. \gray{\CifASTRacket} \\ \hline
  10808. \CloopASTRacket \\
  10809. \begin{array}{lcl}
  10810. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10811. \end{array}
  10812. \end{array}
  10813. \]
  10814. \end{tcolorbox}
  10815. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10816. \label{fig:c7-syntax}
  10817. \end{figure}
  10818. The new auxiliary function \code{explicate\_effect} takes an
  10819. expression (in an effect position) and the code for its
  10820. continuation. The function returns a $\Tail$ that includes the
  10821. generated code for the input expression followed by the
  10822. continuation. If the expression is obviously pure, that is, never
  10823. causes side effects, then the expression can be removed, so the result
  10824. is just the continuation.
  10825. %
  10826. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10827. interesting; the generated code is depicted in the following diagram:
  10828. \begin{center}
  10829. \begin{minipage}{0.3\textwidth}
  10830. \xymatrix{
  10831. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10832. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10833. & *+[F]{\txt{\itm{cont}}} \\
  10834. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10835. }
  10836. \end{minipage}
  10837. \end{center}
  10838. We start by creating a fresh label $\itm{loop}$ for the top of the
  10839. loop. Next, recursively process the \itm{body} (in effect position)
  10840. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10841. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10842. \itm{body'} as the \emph{then} branch and the continuation block as the
  10843. \emph{else} branch. The result should be added to the dictionary of
  10844. \code{basic-blocks} with the label \itm{loop}. The result for the
  10845. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10846. The auxiliary functions for tail, assignment, and predicate positions
  10847. need to be updated. The three new language forms, \code{while},
  10848. \code{set!}, and \code{begin}, can appear in assignment and tail
  10849. positions. Only \code{begin} may appear in predicate positions; the
  10850. other two have result type \code{Void}.
  10851. \fi}
  10852. %
  10853. {\if\edition\pythonEd
  10854. %
  10855. The output of this pass is the language \LangCIf{}. No new language
  10856. features are needed in the output because a \code{while} loop can be
  10857. expressed in terms of \code{goto} and \code{if} statements, which are
  10858. already in \LangCIf{}.
  10859. %
  10860. Add a case for the \code{while} statement to the
  10861. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10862. the condition expression.
  10863. %
  10864. \fi}
  10865. {\if\edition\racketEd
  10866. \section{Select Instructions}
  10867. \label{sec:select-instructions-loop}
  10868. Only two small additions are needed in the \code{select\_instructions}
  10869. pass to handle the changes to \LangCLoop{}. First, to handle the
  10870. addition of \VOID{} we simply translate it to \code{0}. Second,
  10871. \code{read} may appear as a stand-alone statement instead of
  10872. appearing only on the right-hand side of an assignment statement. The code
  10873. generation is nearly identical to the one for assignment; just leave
  10874. off the instruction for moving the result into the left-hand side.
  10875. \fi}
  10876. \section{Register Allocation}
  10877. \label{sec:register-allocation-loop}
  10878. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10879. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10880. which complicates the liveness analysis needed for register
  10881. allocation.
  10882. %
  10883. We recommend using the generic \code{analyze\_dataflow} function that
  10884. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10885. perform liveness analysis, replacing the code in
  10886. \code{uncover\_live} that processed the basic blocks in topological
  10887. order (section~\ref{sec:liveness-analysis-Lif}).
  10888. The \code{analyze\_dataflow} function has the following four parameters.
  10889. \begin{enumerate}
  10890. \item The first parameter \code{G} should be passed the transpose
  10891. of the control-flow graph.
  10892. \item The second parameter \code{transfer} should be passed a function
  10893. that applies liveness analysis to a basic block. It takes two
  10894. parameters: the label for the block to analyze and the live-after
  10895. set for that block. The transfer function should return the
  10896. live-before set for the block.
  10897. %
  10898. \racket{Also, as a side effect, it should update the block's
  10899. $\itm{info}$ with the liveness information for each instruction.}
  10900. %
  10901. \python{Also, as a side-effect, it should update the live-before and
  10902. live-after sets for each instruction.}
  10903. %
  10904. To implement the \code{transfer} function, you should be able to
  10905. reuse the code you already have for analyzing basic blocks.
  10906. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10907. \code{bottom} and \code{join} for the lattice of abstract states,
  10908. that is, sets of locations. For liveness analysis, the bottom of the
  10909. lattice is the empty set, and the join operator is set union.
  10910. \end{enumerate}
  10911. \begin{figure}[p]
  10912. \begin{tcolorbox}[colback=white]
  10913. {\if\edition\racketEd
  10914. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10915. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10916. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10917. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10918. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10919. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10920. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10921. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10922. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10923. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10924. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10925. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10926. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10927. \path[->,bend left=15] (Lfun) edge [above] node
  10928. {\ttfamily\footnotesize shrink} (Lfun-2);
  10929. \path[->,bend left=15] (Lfun-2) edge [above] node
  10930. {\ttfamily\footnotesize uniquify} (F1-4);
  10931. \path[->,bend left=15] (F1-4) edge [above] node
  10932. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10933. \path[->,bend left=15] (F1-5) edge [left] node
  10934. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10935. \path[->,bend left=10] (F1-6) edge [above] node
  10936. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10937. \path[->,bend left=15] (C3-2) edge [right] node
  10938. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10939. \path[->,bend right=15] (x86-2) edge [right] node
  10940. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10941. \path[->,bend right=15] (x86-2-1) edge [below] node
  10942. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10943. \path[->,bend right=15] (x86-2-2) edge [right] node
  10944. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10945. \path[->,bend left=15] (x86-3) edge [above] node
  10946. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10947. \path[->,bend left=15] (x86-4) edge [right] node
  10948. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10949. \end{tikzpicture}
  10950. \fi}
  10951. {\if\edition\pythonEd
  10952. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10953. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10954. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10955. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10956. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10957. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10958. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10959. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10960. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10961. \path[->,bend left=15] (Lfun) edge [above] node
  10962. {\ttfamily\footnotesize shrink} (Lfun-2);
  10963. \path[->,bend left=15] (Lfun-2) edge [above] node
  10964. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10965. \path[->,bend left=10] (F1-6) edge [right] node
  10966. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10967. \path[->,bend right=15] (C3-2) edge [right] node
  10968. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10969. \path[->,bend right=15] (x86-2) edge [below] node
  10970. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10971. \path[->,bend left=15] (x86-3) edge [above] node
  10972. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10973. \path[->,bend right=15] (x86-4) edge [below] node
  10974. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10975. \end{tikzpicture}
  10976. \fi}
  10977. \end{tcolorbox}
  10978. \caption{Diagram of the passes for \LangLoop{}.}
  10979. \label{fig:Lwhile-passes}
  10980. \end{figure}
  10981. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10982. for the compilation of \LangLoop{}.
  10983. % Further Reading: dataflow analysis
  10984. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10985. \chapter{Tuples and Garbage Collection}
  10986. \label{ch:Lvec}
  10987. \index{subject}{tuple}
  10988. \index{subject}{vector}
  10989. \index{subject}{allocate}
  10990. \index{subject}{heap allocate}
  10991. \setcounter{footnote}{0}
  10992. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10993. %% all the IR grammars are spelled out! \\ --Jeremy}
  10994. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10995. %% the root stack. \\ --Jeremy}
  10996. In this chapter we study the implementation of tuples\racket{, called
  10997. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10998. in which each element may have a different type.
  10999. %
  11000. This language feature is the first to use the computer's
  11001. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11002. indefinite; that is, a tuple lives forever from the programmer's
  11003. viewpoint. Of course, from an implementer's viewpoint, it is important
  11004. to reclaim the space associated with a tuple when it is no longer
  11005. needed, which is why we also study \emph{garbage collection}
  11006. \index{subject}{garbage collection} techniques in this chapter.
  11007. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11008. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11009. language (chapter~\ref{ch:Lwhile}) with tuples.
  11010. %
  11011. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11012. copying live tuples back and forth between two halves of the heap. The
  11013. garbage collector requires coordination with the compiler so that it
  11014. can find all the live tuples.
  11015. %
  11016. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11017. discuss the necessary changes and additions to the compiler passes,
  11018. including a new compiler pass named \code{expose\_allocation}.
  11019. \section{The \LangVec{} Language}
  11020. \label{sec:r3}
  11021. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11022. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11023. the definition of the abstract syntax.
  11024. %
  11025. \racket{The \LangVec{} language includes the forms: \code{vector} for
  11026. creating a tuple, \code{vector-ref} for reading an element of a
  11027. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11028. \code{vector-length} for obtaining the number of elements of a
  11029. tuple.}
  11030. %
  11031. \python{The \LangVec{} language adds 1) tuple creation via a
  11032. comma-separated list of expressions, 2) accessing an element of a
  11033. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11034. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11035. operator, and 4) obtaining the number of elements (the length) of a
  11036. tuple. In this chapter, we restrict access indices to constant
  11037. integers.}
  11038. %
  11039. The following program shows an example use of tuples. It creates a tuple
  11040. \code{t} containing the elements \code{40},
  11041. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11042. contains just \code{2}. The element at index $1$ of \code{t} is
  11043. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11044. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11045. to which we add \code{2}, the element at index $0$ of the tuple.
  11046. The result of the program is \code{42}.
  11047. %
  11048. {\if\edition\racketEd
  11049. \begin{lstlisting}
  11050. (let ([t (vector 40 #t (vector 2))])
  11051. (if (vector-ref t 1)
  11052. (+ (vector-ref t 0)
  11053. (vector-ref (vector-ref t 2) 0))
  11054. 44))
  11055. \end{lstlisting}
  11056. \fi}
  11057. {\if\edition\pythonEd
  11058. \begin{lstlisting}
  11059. t = 40, True, (2,)
  11060. print( t[0] + t[2][0] if t[1] else 44 )
  11061. \end{lstlisting}
  11062. \fi}
  11063. \newcommand{\LtupGrammarRacket}{
  11064. \begin{array}{lcl}
  11065. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11066. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11067. \MID \LP\key{vector-length}\;\Exp\RP \\
  11068. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11069. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11070. \end{array}
  11071. }
  11072. \newcommand{\LtupASTRacket}{
  11073. \begin{array}{lcl}
  11074. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11075. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11076. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11077. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11078. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11079. \end{array}
  11080. }
  11081. \newcommand{\LtupGrammarPython}{
  11082. \begin{array}{rcl}
  11083. \itm{cmp} &::= & \key{is} \\
  11084. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11085. \end{array}
  11086. }
  11087. \newcommand{\LtupASTPython}{
  11088. \begin{array}{lcl}
  11089. \itm{cmp} &::= & \code{Is()} \\
  11090. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11091. &\MID& \LEN{\Exp}
  11092. \end{array}
  11093. }
  11094. \begin{figure}[tbp]
  11095. \centering
  11096. \begin{tcolorbox}[colback=white]
  11097. \small
  11098. {\if\edition\racketEd
  11099. \[
  11100. \begin{array}{l}
  11101. \gray{\LintGrammarRacket{}} \\ \hline
  11102. \gray{\LvarGrammarRacket{}} \\ \hline
  11103. \gray{\LifGrammarRacket{}} \\ \hline
  11104. \gray{\LwhileGrammarRacket} \\ \hline
  11105. \LtupGrammarRacket \\
  11106. \begin{array}{lcl}
  11107. \LangVecM{} &::=& \Exp
  11108. \end{array}
  11109. \end{array}
  11110. \]
  11111. \fi}
  11112. {\if\edition\pythonEd
  11113. \[
  11114. \begin{array}{l}
  11115. \gray{\LintGrammarPython{}} \\ \hline
  11116. \gray{\LvarGrammarPython{}} \\ \hline
  11117. \gray{\LifGrammarPython{}} \\ \hline
  11118. \gray{\LwhileGrammarPython} \\ \hline
  11119. \LtupGrammarPython \\
  11120. \begin{array}{rcl}
  11121. \LangVecM{} &::=& \Stmt^{*}
  11122. \end{array}
  11123. \end{array}
  11124. \]
  11125. \fi}
  11126. \end{tcolorbox}
  11127. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11128. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11129. \label{fig:Lvec-concrete-syntax}
  11130. \end{figure}
  11131. \begin{figure}[tp]
  11132. \centering
  11133. \begin{tcolorbox}[colback=white]
  11134. \small
  11135. {\if\edition\racketEd
  11136. \[
  11137. \begin{array}{l}
  11138. \gray{\LintOpAST} \\ \hline
  11139. \gray{\LvarASTRacket{}} \\ \hline
  11140. \gray{\LifASTRacket{}} \\ \hline
  11141. \gray{\LwhileASTRacket{}} \\ \hline
  11142. \LtupASTRacket{} \\
  11143. \begin{array}{lcl}
  11144. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11145. \end{array}
  11146. \end{array}
  11147. \]
  11148. \fi}
  11149. {\if\edition\pythonEd
  11150. \[
  11151. \begin{array}{l}
  11152. \gray{\LintASTPython} \\ \hline
  11153. \gray{\LvarASTPython} \\ \hline
  11154. \gray{\LifASTPython} \\ \hline
  11155. \gray{\LwhileASTPython} \\ \hline
  11156. \LtupASTPython \\
  11157. \begin{array}{lcl}
  11158. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11159. \end{array}
  11160. \end{array}
  11161. \]
  11162. \fi}
  11163. \end{tcolorbox}
  11164. \caption{The abstract syntax of \LangVec{}.}
  11165. \label{fig:Lvec-syntax}
  11166. \end{figure}
  11167. Tuples raise several interesting new issues. First, variable binding
  11168. performs a shallow copy in dealing with tuples, which means that
  11169. different variables can refer to the same tuple; that is, two
  11170. variables can be \emph{aliases}\index{subject}{alias} for the same
  11171. entity. Consider the following example, in which \code{t1} and
  11172. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11173. different tuple value with equal elements. The result of the
  11174. program is \code{42}.
  11175. \begin{center}
  11176. \begin{minipage}{0.96\textwidth}
  11177. {\if\edition\racketEd
  11178. \begin{lstlisting}
  11179. (let ([t1 (vector 3 7)])
  11180. (let ([t2 t1])
  11181. (let ([t3 (vector 3 7)])
  11182. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11183. 42
  11184. 0))))
  11185. \end{lstlisting}
  11186. \fi}
  11187. {\if\edition\pythonEd
  11188. \begin{lstlisting}
  11189. t1 = 3, 7
  11190. t2 = t1
  11191. t3 = 3, 7
  11192. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11193. \end{lstlisting}
  11194. \fi}
  11195. \end{minipage}
  11196. \end{center}
  11197. {\if\edition\racketEd
  11198. Whether two variables are aliased or not affects what happens
  11199. when the underlying tuple is mutated\index{subject}{mutation}.
  11200. Consider the following example in which \code{t1} and \code{t2}
  11201. again refer to the same tuple value.
  11202. \begin{center}
  11203. \begin{minipage}{0.96\textwidth}
  11204. \begin{lstlisting}
  11205. (let ([t1 (vector 3 7)])
  11206. (let ([t2 t1])
  11207. (let ([_ (vector-set! t2 0 42)])
  11208. (vector-ref t1 0))))
  11209. \end{lstlisting}
  11210. \end{minipage}
  11211. \end{center}
  11212. The mutation through \code{t2} is visible in referencing the tuple
  11213. from \code{t1}, so the result of this program is \code{42}.
  11214. \fi}
  11215. The next issue concerns the lifetime of tuples. When does a tuple's
  11216. lifetime end? Notice that \LangVec{} does not include an operation
  11217. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11218. to any notion of static scoping.
  11219. %
  11220. {\if\edition\racketEd
  11221. %
  11222. For example, the following program returns \code{42} even though the
  11223. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11224. that reads from the vector to which it was bound.
  11225. \begin{center}
  11226. \begin{minipage}{0.96\textwidth}
  11227. \begin{lstlisting}
  11228. (let ([v (vector (vector 44))])
  11229. (let ([x (let ([w (vector 42)])
  11230. (let ([_ (vector-set! v 0 w)])
  11231. 0))])
  11232. (+ x (vector-ref (vector-ref v 0) 0))))
  11233. \end{lstlisting}
  11234. \end{minipage}
  11235. \end{center}
  11236. \fi}
  11237. %
  11238. {\if\edition\pythonEd
  11239. %
  11240. For example, the following program returns \code{42} even though the
  11241. variable \code{x} goes out of scope when the function returns, prior
  11242. to reading the tuple element at index zero. (We study the compilation
  11243. of functions in chapter~\ref{ch:Lfun}.)
  11244. %
  11245. \begin{center}
  11246. \begin{minipage}{0.96\textwidth}
  11247. \begin{lstlisting}
  11248. def f():
  11249. x = 42, 43
  11250. return x
  11251. t = f()
  11252. print( t[0] )
  11253. \end{lstlisting}
  11254. \end{minipage}
  11255. \end{center}
  11256. \fi}
  11257. %
  11258. From the perspective of programmer-observable behavior, tuples live
  11259. forever. However, if they really lived forever then many long-running
  11260. programs would run out of memory. To solve this problem, the
  11261. language's runtime system performs automatic garbage collection.
  11262. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11263. \LangVec{} language.
  11264. %
  11265. \racket{We define the \code{vector}, \code{vector-ref},
  11266. \code{vector-set!}, and \code{vector-length} operations for
  11267. \LangVec{} in terms of the corresponding operations in Racket. One
  11268. subtle point is that the \code{vector-set!} operation returns the
  11269. \code{\#<void>} value.}
  11270. %
  11271. \python{We represent tuples with Python lists in the interpreter
  11272. because we need to write to them
  11273. (section~\ref{sec:expose-allocation}). (Python tuples are
  11274. immutable.) We define element access, the \code{is} operator, and
  11275. the \code{len} operator for \LangVec{} in terms of the corresponding
  11276. operations in Python.}
  11277. \begin{figure}[tbp]
  11278. \begin{tcolorbox}[colback=white]
  11279. {\if\edition\racketEd
  11280. \begin{lstlisting}
  11281. (define interp-Lvec-class
  11282. (class interp-Lwhile-class
  11283. (super-new)
  11284. (define/override (interp-op op)
  11285. (match op
  11286. ['eq? (lambda (v1 v2)
  11287. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11288. (and (boolean? v1) (boolean? v2))
  11289. (and (vector? v1) (vector? v2))
  11290. (and (void? v1) (void? v2)))
  11291. (eq? v1 v2)]))]
  11292. ['vector vector]
  11293. ['vector-length vector-length]
  11294. ['vector-ref vector-ref]
  11295. ['vector-set! vector-set!]
  11296. [else (super interp-op op)]
  11297. ))
  11298. (define/override ((interp-exp env) e)
  11299. (match e
  11300. [(HasType e t) ((interp-exp env) e)]
  11301. [else ((super interp-exp env) e)]
  11302. ))
  11303. ))
  11304. (define (interp-Lvec p)
  11305. (send (new interp-Lvec-class) interp-program p))
  11306. \end{lstlisting}
  11307. \fi}
  11308. %
  11309. {\if\edition\pythonEd
  11310. \begin{lstlisting}
  11311. class InterpLtup(InterpLwhile):
  11312. def interp_cmp(self, cmp):
  11313. match cmp:
  11314. case Is():
  11315. return lambda x, y: x is y
  11316. case _:
  11317. return super().interp_cmp(cmp)
  11318. def interp_exp(self, e, env):
  11319. match e:
  11320. case Tuple(es, Load()):
  11321. return tuple([self.interp_exp(e, env) for e in es])
  11322. case Subscript(tup, index, Load()):
  11323. t = self.interp_exp(tup, env)
  11324. n = self.interp_exp(index, env)
  11325. return t[n]
  11326. case _:
  11327. return super().interp_exp(e, env)
  11328. \end{lstlisting}
  11329. \fi}
  11330. \end{tcolorbox}
  11331. \caption{Interpreter for the \LangVec{} language.}
  11332. \label{fig:interp-Lvec}
  11333. \end{figure}
  11334. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11335. \LangVec{}.
  11336. %
  11337. The type of a tuple is a
  11338. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11339. type for each of its elements.
  11340. %
  11341. \racket{To create the s-expression for the \code{Vector} type, we use the
  11342. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11343. operator} \code{,@} to insert the list \code{t*} without its usual
  11344. start and end parentheses. \index{subject}{unquote-splicing}}
  11345. %
  11346. The type of accessing the ith element of a tuple is the ith element
  11347. type of the tuple's type, if there is one. If not, an error is
  11348. signaled. Note that the index \code{i} is required to be a constant
  11349. integer (and not, for example, a call to
  11350. \racket{\code{read}}\python{input\_int}) so that the type checker
  11351. can determine the element's type given the tuple type.
  11352. %
  11353. \racket{
  11354. Regarding writing an element to a tuple, the element's type must
  11355. be equal to the ith element type of the tuple's type.
  11356. The result type is \code{Void}.}
  11357. %% When allocating a tuple,
  11358. %% we need to know which elements of the tuple are themselves tuples for
  11359. %% the purposes of garbage collection. We can obtain this information
  11360. %% during type checking. The type checker shown in
  11361. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11362. %% expression; it also
  11363. %% %
  11364. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11365. %% where $T$ is the tuple's type.
  11366. %
  11367. %records the type of each tuple expression in a new field named \code{has\_type}.
  11368. \begin{figure}[tp]
  11369. \begin{tcolorbox}[colback=white]
  11370. {\if\edition\racketEd
  11371. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11372. (define type-check-Lvec-class
  11373. (class type-check-Lif-class
  11374. (super-new)
  11375. (inherit check-type-equal?)
  11376. (define/override (type-check-exp env)
  11377. (lambda (e)
  11378. (define recur (type-check-exp env))
  11379. (match e
  11380. [(Prim 'vector es)
  11381. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11382. (define t `(Vector ,@t*))
  11383. (values (Prim 'vector e*) t)]
  11384. [(Prim 'vector-ref (list e1 (Int i)))
  11385. (define-values (e1^ t) (recur e1))
  11386. (match t
  11387. [`(Vector ,ts ...)
  11388. (unless (and (0 . <= . i) (i . < . (length ts)))
  11389. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11390. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11391. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11392. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11393. (define-values (e-vec t-vec) (recur e1))
  11394. (define-values (e-elt^ t-elt) (recur elt))
  11395. (match t-vec
  11396. [`(Vector ,ts ...)
  11397. (unless (and (0 . <= . i) (i . < . (length ts)))
  11398. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11399. (check-type-equal? (list-ref ts i) t-elt e)
  11400. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11401. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11402. [(Prim 'vector-length (list e))
  11403. (define-values (e^ t) (recur e))
  11404. (match t
  11405. [`(Vector ,ts ...)
  11406. (values (Prim 'vector-length (list e^)) 'Integer)]
  11407. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11408. [(Prim 'eq? (list arg1 arg2))
  11409. (define-values (e1 t1) (recur arg1))
  11410. (define-values (e2 t2) (recur arg2))
  11411. (match* (t1 t2)
  11412. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11413. [(other wise) (check-type-equal? t1 t2 e)])
  11414. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11415. [else ((super type-check-exp env) e)]
  11416. )))
  11417. ))
  11418. (define (type-check-Lvec p)
  11419. (send (new type-check-Lvec-class) type-check-program p))
  11420. \end{lstlisting}
  11421. \fi}
  11422. {\if\edition\pythonEd
  11423. \begin{lstlisting}
  11424. class TypeCheckLtup(TypeCheckLwhile):
  11425. def type_check_exp(self, e, env):
  11426. match e:
  11427. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11428. l = self.type_check_exp(left, env)
  11429. r = self.type_check_exp(right, env)
  11430. check_type_equal(l, r, e)
  11431. return bool
  11432. case Tuple(es, Load()):
  11433. ts = [self.type_check_exp(e, env) for e in es]
  11434. e.has_type = TupleType(ts)
  11435. return e.has_type
  11436. case Subscript(tup, Constant(i), Load()):
  11437. tup_ty = self.type_check_exp(tup, env)
  11438. i_ty = self.type_check_exp(Constant(i), env)
  11439. check_type_equal(i_ty, int, i)
  11440. match tup_ty:
  11441. case TupleType(ts):
  11442. return ts[i]
  11443. case _:
  11444. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11445. case _:
  11446. return super().type_check_exp(e, env)
  11447. \end{lstlisting}
  11448. \fi}
  11449. \end{tcolorbox}
  11450. \caption{Type checker for the \LangVec{} language.}
  11451. \label{fig:type-check-Lvec}
  11452. \end{figure}
  11453. \section{Garbage Collection}
  11454. \label{sec:GC}
  11455. Garbage collection is a runtime technique for reclaiming space on the
  11456. heap that will not be used in the future of the running program. We
  11457. use the term \emph{object}\index{subject}{object} to refer to any
  11458. value that is stored in the heap, which for now includes only
  11459. tuples.%
  11460. %
  11461. \footnote{The term \emph{object} as it is used in the context of
  11462. object-oriented programming has a more specific meaning than the
  11463. way in which we use the term here.}
  11464. %
  11465. Unfortunately, it is impossible to know precisely which objects will
  11466. be accessed in the future and which will not. Instead, garbage
  11467. collectors overapproximate the set of objects that will be accessed by
  11468. identifying which objects can possibly be accessed. The running
  11469. program can directly access objects that are in registers and on the
  11470. procedure call stack. It can also transitively access the elements of
  11471. tuples, starting with a tuple whose address is in a register or on the
  11472. procedure call stack. We define the \emph{root
  11473. set}\index{subject}{root set} to be all the tuple addresses that are
  11474. in registers or on the procedure call stack. We define the \emph{live
  11475. objects}\index{subject}{live objects} to be the objects that are
  11476. reachable from the root set. Garbage collectors reclaim the space that
  11477. is allocated to objects that are no longer live. That means that some
  11478. objects may not get reclaimed as soon as they could be, but at least
  11479. garbage collectors do not reclaim the space dedicated to objects that
  11480. will be accessed in the future! The programmer can influence which
  11481. objects get reclaimed by causing them to become unreachable.
  11482. So the goal of the garbage collector is twofold:
  11483. \begin{enumerate}
  11484. \item to preserve all the live objects, and
  11485. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11486. \end{enumerate}
  11487. \subsection{Two-Space Copying Collector}
  11488. Here we study a relatively simple algorithm for garbage collection
  11489. that is the basis of many state-of-the-art garbage
  11490. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11491. particular, we describe a two-space copying
  11492. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11493. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11494. collector} \index{subject}{two-space copying collector}
  11495. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11496. what happens in a two-space collector, showing two time steps, prior
  11497. to garbage collection (on the top) and after garbage collection (on
  11498. the bottom). In a two-space collector, the heap is divided into two
  11499. parts named the FromSpace\index{subject}{FromSpace} and the
  11500. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11501. FromSpace until there is not enough room for the next allocation
  11502. request. At that point, the garbage collector goes to work to make
  11503. room for the next allocation.
  11504. A copying collector makes more room by copying all the live objects
  11505. from the FromSpace into the ToSpace and then performs a sleight of
  11506. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11507. as the new ToSpace. In the example shown in
  11508. figure~\ref{fig:copying-collector}, the root set consists of three
  11509. pointers, one in a register and two on the stack. All the live
  11510. objects have been copied to the ToSpace (the right-hand side of
  11511. figure~\ref{fig:copying-collector}) in a way that preserves the
  11512. pointer relationships. For example, the pointer in the register still
  11513. points to a tuple that in turn points to two other tuples. There are
  11514. four tuples that are not reachable from the root set and therefore do
  11515. not get copied into the ToSpace.
  11516. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11517. created by a well-typed program in \LangVec{} because it contains a
  11518. cycle. However, creating cycles will be possible once we get to
  11519. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11520. to deal with cycles to begin with, so we will not need to revisit this
  11521. issue.
  11522. \begin{figure}[tbp]
  11523. \centering
  11524. \begin{tcolorbox}[colback=white]
  11525. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11526. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11527. \\[5ex]
  11528. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11529. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11530. \end{tcolorbox}
  11531. \caption{A copying collector in action.}
  11532. \label{fig:copying-collector}
  11533. \end{figure}
  11534. \subsection{Graph Copying via Cheney's Algorithm}
  11535. \label{sec:cheney}
  11536. \index{subject}{Cheney's algorithm}
  11537. Let us take a closer look at the copying of the live objects. The
  11538. allocated objects and pointers can be viewed as a graph, and we need to
  11539. copy the part of the graph that is reachable from the root set. To
  11540. make sure that we copy all the reachable vertices in the graph, we need
  11541. an exhaustive graph traversal algorithm, such as depth-first search or
  11542. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  11543. such algorithms take into account the possibility of cycles by marking
  11544. which vertices have already been visited, so to ensure termination
  11545. of the algorithm. These search algorithms also use a data structure
  11546. such as a stack or queue as a to-do list to keep track of the vertices
  11547. that need to be visited. We use breadth-first search and a trick
  11548. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  11549. and copying tuples into the ToSpace.
  11550. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11551. copy progresses. The queue is represented by a chunk of contiguous
  11552. memory at the beginning of the ToSpace, using two pointers to track
  11553. the front and the back of the queue, called the \emph{free pointer}
  11554. and the \emph{scan pointer}, respectively. The algorithm starts by
  11555. copying all tuples that are immediately reachable from the root set
  11556. into the ToSpace to form the initial queue. When we copy a tuple, we
  11557. mark the old tuple to indicate that it has been visited. We discuss
  11558. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11559. that any pointers inside the copied tuples in the queue still point
  11560. back to the FromSpace. Once the initial queue has been created, the
  11561. algorithm enters a loop in which it repeatedly processes the tuple at
  11562. the front of the queue and pops it off the queue. To process a tuple,
  11563. the algorithm copies all the objects that are directly reachable from it
  11564. to the ToSpace, placing them at the back of the queue. The algorithm
  11565. then updates the pointers in the popped tuple so that they point to the
  11566. newly copied objects.
  11567. \begin{figure}[tbp]
  11568. \centering
  11569. \begin{tcolorbox}[colback=white]
  11570. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11571. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11572. \end{tcolorbox}
  11573. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11574. \label{fig:cheney}
  11575. \end{figure}
  11576. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11577. tuple whose second element is $42$ to the back of the queue. The other
  11578. pointer goes to a tuple that has already been copied, so we do not
  11579. need to copy it again, but we do need to update the pointer to the new
  11580. location. This can be accomplished by storing a \emph{forwarding
  11581. pointer}\index{subject}{forwarding pointer} to the new location in the
  11582. old tuple, when we initially copied the tuple into the
  11583. ToSpace. This completes one step of the algorithm. The algorithm
  11584. continues in this way until the queue is empty; that is, when the scan
  11585. pointer catches up with the free pointer.
  11586. \subsection{Data Representation}
  11587. \label{sec:data-rep-gc}
  11588. The garbage collector places some requirements on the data
  11589. representations used by our compiler. First, the garbage collector
  11590. needs to distinguish between pointers and other kinds of data such as
  11591. integers. The following are several ways to accomplish this:
  11592. \begin{enumerate}
  11593. \item Attach a tag to each object that identifies what type of
  11594. object it is~\citep{McCarthy:1960dz}.
  11595. \item Store different types of objects in different
  11596. regions~\citep{Steele:1977ab}.
  11597. \item Use type information from the program to either (a) generate
  11598. type-specific code for collecting, or (b) generate tables that
  11599. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11600. \end{enumerate}
  11601. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11602. need to tag objects in any case, so option 1 is a natural choice for those
  11603. languages. However, \LangVec{} is a statically typed language, so it
  11604. would be unfortunate to require tags on every object, especially small
  11605. and pervasive objects like integers and Booleans. Option 3 is the
  11606. best-performing choice for statically typed languages, but it comes with
  11607. a relatively high implementation complexity. To keep this chapter
  11608. within a reasonable scope of complexity, we recommend a combination of options
  11609. 1 and 2, using separate strategies for the stack and the heap.
  11610. Regarding the stack, we recommend using a separate stack for pointers,
  11611. which we call the \emph{root stack}\index{subject}{root stack}
  11612. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11613. That is, when a local variable needs to be spilled and is of type
  11614. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11615. root stack instead of putting it on the procedure call
  11616. stack. Furthermore, we always spill tuple-typed variables if they are
  11617. live during a call to the collector, thereby ensuring that no pointers
  11618. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11619. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11620. contrasts it with the data layout using a root stack. The root stack
  11621. contains the two pointers from the regular stack and also the pointer
  11622. in the second register.
  11623. \begin{figure}[tbp]
  11624. \centering
  11625. \begin{tcolorbox}[colback=white]
  11626. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11627. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11628. \end{tcolorbox}
  11629. \caption{Maintaining a root stack to facilitate garbage collection.}
  11630. \label{fig:shadow-stack}
  11631. \end{figure}
  11632. The problem of distinguishing between pointers and other kinds of data
  11633. also arises inside each tuple on the heap. We solve this problem by
  11634. attaching a tag, an extra 64 bits, to each
  11635. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11636. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11637. Note that we have drawn the bits in a big-endian way, from right to left,
  11638. with bit location 0 (the least significant bit) on the far right,
  11639. which corresponds to the direction of the x86 shifting instructions
  11640. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11641. is dedicated to specifying which elements of the tuple are pointers,
  11642. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11643. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11644. data. The pointer mask starts at bit location 7. We limit tuples to a
  11645. maximum size of fifty elements, so we need 50 bits for the pointer
  11646. mask.%
  11647. %
  11648. \footnote{A production-quality compiler would handle
  11649. arbitrarily sized tuples and use a more complex approach.}
  11650. %
  11651. The tag also contains two other pieces of information. The length of
  11652. the tuple (number of elements) is stored in bits at locations 1 through
  11653. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11654. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11655. has not yet been copied. If the bit has value 0, then the entire tag
  11656. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11657. zero in any case, because our tuples are 8-byte aligned.)
  11658. \begin{figure}[tbp]
  11659. \centering
  11660. \begin{tcolorbox}[colback=white]
  11661. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11662. \end{tcolorbox}
  11663. \caption{Representation of tuples in the heap.}
  11664. \label{fig:tuple-rep}
  11665. \end{figure}
  11666. \subsection{Implementation of the Garbage Collector}
  11667. \label{sec:organize-gz}
  11668. \index{subject}{prelude}
  11669. An implementation of the copying collector is provided in the
  11670. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11671. interface to the garbage collector that is used by the compiler. The
  11672. \code{initialize} function creates the FromSpace, ToSpace, and root
  11673. stack and should be called in the prelude of the \code{main}
  11674. function. The arguments of \code{initialize} are the root stack size
  11675. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11676. good choice for both. The \code{initialize} function puts the address
  11677. of the beginning of the FromSpace into the global variable
  11678. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11679. the address that is one past the last element of the FromSpace. We use
  11680. half-open intervals to represent chunks of
  11681. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11682. points to the first element of the root stack.
  11683. As long as there is room left in the FromSpace, your generated code
  11684. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11685. %
  11686. The amount of room left in the FromSpace is the difference between the
  11687. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11688. function should be called when there is not enough room left in the
  11689. FromSpace for the next allocation. The \code{collect} function takes
  11690. a pointer to the current top of the root stack (one past the last item
  11691. that was pushed) and the number of bytes that need to be
  11692. allocated. The \code{collect} function performs the copying collection
  11693. and leaves the heap in a state such that there is enough room for the
  11694. next allocation.
  11695. \begin{figure}[tbp]
  11696. \begin{tcolorbox}[colback=white]
  11697. \begin{lstlisting}
  11698. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11699. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11700. int64_t* free_ptr;
  11701. int64_t* fromspace_begin;
  11702. int64_t* fromspace_end;
  11703. int64_t** rootstack_begin;
  11704. \end{lstlisting}
  11705. \end{tcolorbox}
  11706. \caption{The compiler's interface to the garbage collector.}
  11707. \label{fig:gc-header}
  11708. \end{figure}
  11709. %% \begin{exercise}
  11710. %% In the file \code{runtime.c} you will find the implementation of
  11711. %% \code{initialize} and a partial implementation of \code{collect}.
  11712. %% The \code{collect} function calls another function, \code{cheney},
  11713. %% to perform the actual copy, and that function is left to the reader
  11714. %% to implement. The following is the prototype for \code{cheney}.
  11715. %% \begin{lstlisting}
  11716. %% static void cheney(int64_t** rootstack_ptr);
  11717. %% \end{lstlisting}
  11718. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11719. %% rootstack (which is an array of pointers). The \code{cheney} function
  11720. %% also communicates with \code{collect} through the global
  11721. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11722. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11723. %% the ToSpace:
  11724. %% \begin{lstlisting}
  11725. %% static int64_t* tospace_begin;
  11726. %% static int64_t* tospace_end;
  11727. %% \end{lstlisting}
  11728. %% The job of the \code{cheney} function is to copy all the live
  11729. %% objects (reachable from the root stack) into the ToSpace, update
  11730. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11731. %% update the root stack so that it points to the objects in the
  11732. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11733. %% and ToSpace.
  11734. %% \end{exercise}
  11735. The introduction of garbage collection has a nontrivial impact on our
  11736. compiler passes. We introduce a new compiler pass named
  11737. \code{expose\_allocation} that elaborates the code for allocating
  11738. tuples. We also make significant changes to
  11739. \code{select\_instructions}, \code{build\_interference},
  11740. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11741. make minor changes in several more passes.
  11742. The following program serves as our running example. It creates
  11743. two tuples, one nested inside the other. Both tuples have length
  11744. one. The program accesses the element in the inner tuple.
  11745. % tests/vectors_test_17.rkt
  11746. {\if\edition\racketEd
  11747. \begin{lstlisting}
  11748. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11749. \end{lstlisting}
  11750. \fi}
  11751. {\if\edition\pythonEd
  11752. \begin{lstlisting}
  11753. print( ((42,),)[0][0] )
  11754. \end{lstlisting}
  11755. \fi}
  11756. %% {\if\edition\racketEd
  11757. %% \section{Shrink}
  11758. %% \label{sec:shrink-Lvec}
  11759. %% Recall that the \code{shrink} pass translates the primitives operators
  11760. %% into a smaller set of primitives.
  11761. %% %
  11762. %% This pass comes after type checking, and the type checker adds a
  11763. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11764. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11765. %% \fi}
  11766. \section{Expose Allocation}
  11767. \label{sec:expose-allocation}
  11768. The pass \code{expose\_allocation} lowers tuple creation into making a
  11769. conditional call to the collector followed by allocating the
  11770. appropriate amount of memory and initializing it. We choose to place
  11771. the \code{expose\_allocation} pass before
  11772. \code{remove\_complex\_operands} because it generates
  11773. code that contains complex operands.
  11774. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11775. that replaces tuple creation with new lower-level forms that we use in the
  11776. translation of tuple creation.
  11777. %
  11778. {\if\edition\racketEd
  11779. \[
  11780. \begin{array}{lcl}
  11781. \Exp &::=& \cdots
  11782. \MID (\key{collect} \,\itm{int})
  11783. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11784. \MID (\key{global-value} \,\itm{name})
  11785. \end{array}
  11786. \]
  11787. \fi}
  11788. {\if\edition\pythonEd
  11789. \[
  11790. \begin{array}{lcl}
  11791. \Exp &::=& \cdots\\
  11792. &\MID& \key{collect}(\itm{int})
  11793. \MID \key{allocate}(\itm{int},\itm{type})
  11794. \MID \key{global\_value}(\itm{name}) \\
  11795. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11796. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11797. \end{array}
  11798. \]
  11799. \fi}
  11800. %
  11801. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11802. make sure that there are $n$ bytes ready to be allocated. During
  11803. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11804. the \code{collect} function in \code{runtime.c}.
  11805. %
  11806. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11807. space at the front for the 64-bit tag), but the elements are not
  11808. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11809. of the tuple:
  11810. %
  11811. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11812. %
  11813. where $\Type_i$ is the type of the $i$th element.
  11814. %
  11815. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11816. variable, such as \code{free\_ptr}.
  11817. %
  11818. \python{The \code{begin} form is an expression that executes a
  11819. sequence of statements and then produces the value of the expression
  11820. at the end.}
  11821. \racket{
  11822. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11823. can be obtained by running the
  11824. \code{type-check-Lvec-has-type} type checker immediately before the
  11825. \code{expose\_allocation} pass. This version of the type checker
  11826. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11827. around each tuple creation. The concrete syntax
  11828. for \code{HasType} is \code{has-type}.}
  11829. The following shows the transformation of tuple creation into (1) a
  11830. sequence of temporary variable bindings for the initializing
  11831. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11832. \code{allocate}, and (4) the initialization of the tuple. The
  11833. \itm{len} placeholder refers to the length of the tuple, and
  11834. \itm{bytes} is the total number of bytes that need to be allocated for
  11835. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11836. %
  11837. \python{The \itm{type} needed for the second argument of the
  11838. \code{allocate} form can be obtained from the \code{has\_type} field
  11839. of the tuple AST node, which is stored there by running the type
  11840. checker for \LangVec{} immediately before this pass.}
  11841. %
  11842. \begin{center}
  11843. \begin{minipage}{\textwidth}
  11844. {\if\edition\racketEd
  11845. \begin{lstlisting}
  11846. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11847. |$\Longrightarrow$|
  11848. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11849. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11850. (global-value fromspace_end))
  11851. (void)
  11852. (collect |\itm{bytes}|))])
  11853. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11854. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11855. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11856. |$v$|) ... )))) ...)
  11857. \end{lstlisting}
  11858. \fi}
  11859. {\if\edition\pythonEd
  11860. \begin{lstlisting}
  11861. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11862. |$\Longrightarrow$|
  11863. begin:
  11864. |$x_0$| = |$e_0$|
  11865. |$\vdots$|
  11866. |$x_{n-1}$| = |$e_{n-1}$|
  11867. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11868. 0
  11869. else:
  11870. collect(|\itm{bytes}|)
  11871. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11872. |$v$|[0] = |$x_0$|
  11873. |$\vdots$|
  11874. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11875. |$v$|
  11876. \end{lstlisting}
  11877. \fi}
  11878. \end{minipage}
  11879. \end{center}
  11880. %
  11881. \noindent The sequencing of the initializing expressions
  11882. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11883. they may trigger garbage collection and we cannot have an allocated
  11884. but uninitialized tuple on the heap during a collection.
  11885. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11886. \code{expose\_allocation} pass on our running example.
  11887. \begin{figure}[tbp]
  11888. \begin{tcolorbox}[colback=white]
  11889. % tests/s2_17.rkt
  11890. {\if\edition\racketEd
  11891. \begin{lstlisting}
  11892. (vector-ref
  11893. (vector-ref
  11894. (let ([vecinit6
  11895. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11896. (global-value fromspace_end))
  11897. (void)
  11898. (collect 16))])
  11899. (let ([alloc2 (allocate 1 (Vector Integer))])
  11900. (let ([_3 (vector-set! alloc2 0 42)])
  11901. alloc2)))])
  11902. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11903. (global-value fromspace_end))
  11904. (void)
  11905. (collect 16))])
  11906. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11907. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11908. alloc5))))
  11909. 0)
  11910. 0)
  11911. \end{lstlisting}
  11912. \fi}
  11913. {\if\edition\pythonEd
  11914. \begin{lstlisting}
  11915. print( |$T_1$|[0][0] )
  11916. \end{lstlisting}
  11917. where $T_1$ is
  11918. \begin{lstlisting}
  11919. begin:
  11920. tmp.1 = |$T_2$|
  11921. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11922. 0
  11923. else:
  11924. collect(16)
  11925. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11926. tmp.2[0] = tmp.1
  11927. tmp.2
  11928. \end{lstlisting}
  11929. and $T_2$ is
  11930. \begin{lstlisting}
  11931. begin:
  11932. tmp.3 = 42
  11933. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11934. 0
  11935. else:
  11936. collect(16)
  11937. tmp.4 = allocate(1, TupleType([int]))
  11938. tmp.4[0] = tmp.3
  11939. tmp.4
  11940. \end{lstlisting}
  11941. \fi}
  11942. \end{tcolorbox}
  11943. \caption{Output of the \code{expose\_allocation} pass.}
  11944. \label{fig:expose-alloc-output}
  11945. \end{figure}
  11946. \section{Remove Complex Operands}
  11947. \label{sec:remove-complex-opera-Lvec}
  11948. {\if\edition\racketEd
  11949. %
  11950. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11951. should be treated as complex operands.
  11952. %
  11953. \fi}
  11954. %
  11955. {\if\edition\pythonEd
  11956. %
  11957. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11958. and tuple access should be treated as complex operands. The
  11959. sub-expressions of tuple access must be atomic.
  11960. %
  11961. \fi}
  11962. %% A new case for
  11963. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11964. %% handled carefully to prevent the \code{Prim} node from being separated
  11965. %% from its enclosing \code{HasType}.
  11966. Figure~\ref{fig:Lvec-anf-syntax}
  11967. shows the grammar for the output language \LangAllocANF{} of this
  11968. pass, which is \LangAlloc{} in monadic normal form.
  11969. \newcommand{\LtupMonadASTRacket}{
  11970. \begin{array}{rcl}
  11971. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11972. \MID \GLOBALVALUE{\Var}
  11973. \end{array}
  11974. }
  11975. \newcommand{\LtupMonadASTPython}{
  11976. \begin{array}{rcl}
  11977. \Exp &::=& \GET{\Atm}{\Atm} \\
  11978. &\MID& \LEN{\Atm}\\
  11979. &\MID& \ALLOCATE{\Int}{\Type}
  11980. \MID \GLOBALVALUE{\Var} \\
  11981. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11982. &\MID& \COLLECT{\Int}
  11983. \end{array}
  11984. }
  11985. \begin{figure}[tp]
  11986. \centering
  11987. \begin{tcolorbox}[colback=white]
  11988. \small
  11989. {\if\edition\racketEd
  11990. \[
  11991. \begin{array}{l}
  11992. \gray{\LvarMonadASTRacket} \\ \hline
  11993. \gray{\LifMonadASTRacket} \\ \hline
  11994. \gray{\LwhileMonadASTRacket} \\ \hline
  11995. \LtupMonadASTRacket \\
  11996. \begin{array}{rcl}
  11997. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11998. \end{array}
  11999. \end{array}
  12000. \]
  12001. \fi}
  12002. {\if\edition\pythonEd
  12003. \[
  12004. \begin{array}{l}
  12005. \gray{\LvarMonadASTPython} \\ \hline
  12006. \gray{\LifMonadASTPython} \\ \hline
  12007. \gray{\LwhileMonadASTPython} \\ \hline
  12008. \LtupMonadASTPython \\
  12009. \begin{array}{rcl}
  12010. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12011. \end{array}
  12012. \end{array}
  12013. \]
  12014. \fi}
  12015. \end{tcolorbox}
  12016. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12017. \label{fig:Lvec-anf-syntax}
  12018. \end{figure}
  12019. \section{Explicate Control and the \LangCVec{} language}
  12020. \label{sec:explicate-control-r3}
  12021. \newcommand{\CtupASTRacket}{
  12022. \begin{array}{lcl}
  12023. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12024. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12025. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12026. &\MID& \VECLEN{\Atm} \\
  12027. &\MID& \GLOBALVALUE{\Var} \\
  12028. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12029. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12030. \end{array}
  12031. }
  12032. \newcommand{\CtupASTPython}{
  12033. \begin{array}{lcl}
  12034. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12035. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12036. \Stmt &::=& \COLLECT{\Int} \\
  12037. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12038. \end{array}
  12039. }
  12040. \begin{figure}[tp]
  12041. \begin{tcolorbox}[colback=white]
  12042. \small
  12043. {\if\edition\racketEd
  12044. \[
  12045. \begin{array}{l}
  12046. \gray{\CvarASTRacket} \\ \hline
  12047. \gray{\CifASTRacket} \\ \hline
  12048. \gray{\CloopASTRacket} \\ \hline
  12049. \CtupASTRacket \\
  12050. \begin{array}{lcl}
  12051. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12052. \end{array}
  12053. \end{array}
  12054. \]
  12055. \fi}
  12056. {\if\edition\pythonEd
  12057. \[
  12058. \begin{array}{l}
  12059. \gray{\CifASTPython} \\ \hline
  12060. \CtupASTPython \\
  12061. \begin{array}{lcl}
  12062. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12063. \end{array}
  12064. \end{array}
  12065. \]
  12066. \fi}
  12067. \end{tcolorbox}
  12068. \caption{The abstract syntax of \LangCVec{}, extending
  12069. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12070. (figure~\ref{fig:c1-syntax})}.}
  12071. \label{fig:c2-syntax}
  12072. \end{figure}
  12073. The output of \code{explicate\_control} is a program in the
  12074. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12075. shows the definition of the abstract syntax.
  12076. %
  12077. %% \racket{(The concrete syntax is defined in
  12078. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12079. %
  12080. The new expressions of \LangCVec{} include \key{allocate},
  12081. %
  12082. \racket{\key{vector-ref}, and \key{vector-set!},}
  12083. %
  12084. \python{accessing tuple elements,}
  12085. %
  12086. and \key{global\_value}.
  12087. %
  12088. \python{\LangCVec{} also includes the \code{collect} statement and
  12089. assignment to a tuple element.}
  12090. %
  12091. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12092. %
  12093. The \code{explicate\_control} pass can treat these new forms much like
  12094. the other forms that we've already encountered. The output of the
  12095. \code{explicate\_control} pass on the running example is shown on the
  12096. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12097. section.
  12098. \section{Select Instructions and the \LangXGlobal{} Language}
  12099. \label{sec:select-instructions-gc}
  12100. \index{subject}{instruction selection}
  12101. %% void (rep as zero)
  12102. %% allocate
  12103. %% collect (callq collect)
  12104. %% vector-ref
  12105. %% vector-set!
  12106. %% vector-length
  12107. %% global (postpone)
  12108. In this pass we generate x86 code for most of the new operations that
  12109. were needed to compile tuples, including \code{Allocate},
  12110. \code{Collect}, and accessing tuple elements.
  12111. %
  12112. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12113. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12114. \ref{fig:x86-2}). \index{subject}{x86}
  12115. The tuple read and write forms translate into \code{movq}
  12116. instructions. (The $+1$ in the offset serves to move past the tag at the
  12117. beginning of the tuple representation.)
  12118. %
  12119. \begin{center}
  12120. \begin{minipage}{\textwidth}
  12121. {\if\edition\racketEd
  12122. \begin{lstlisting}
  12123. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12124. |$\Longrightarrow$|
  12125. movq |$\itm{tup}'$|, %r11
  12126. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12127. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12128. |$\Longrightarrow$|
  12129. movq |$\itm{tup}'$|, %r11
  12130. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12131. movq $0, |$\itm{lhs'}$|
  12132. \end{lstlisting}
  12133. \fi}
  12134. {\if\edition\pythonEd
  12135. \begin{lstlisting}
  12136. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12137. |$\Longrightarrow$|
  12138. movq |$\itm{tup}'$|, %r11
  12139. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12140. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12141. |$\Longrightarrow$|
  12142. movq |$\itm{tup}'$|, %r11
  12143. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12144. \end{lstlisting}
  12145. \fi}
  12146. \end{minipage}
  12147. \end{center}
  12148. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12149. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12150. are obtained by translating from \LangCVec{} to x86.
  12151. %
  12152. The move of $\itm{tup}'$ to
  12153. register \code{r11} ensures that offset expression
  12154. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12155. removing \code{r11} from consideration by the register allocating.
  12156. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12157. \code{rax}. Then the generated code for tuple assignment would be
  12158. \begin{lstlisting}
  12159. movq |$\itm{tup}'$|, %rax
  12160. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12161. \end{lstlisting}
  12162. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12163. \code{patch\_instructions} would insert a move through \code{rax}
  12164. as follows:
  12165. \begin{lstlisting}
  12166. movq |$\itm{tup}'$|, %rax
  12167. movq |$\itm{rhs}'$|, %rax
  12168. movq %rax, |$8(n+1)$|(%rax)
  12169. \end{lstlisting}
  12170. However, this sequence of instructions does not work, because we're
  12171. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12172. $\itm{rhs}'$) at the same time!
  12173. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12174. be translated into a sequence of instructions that read the tag of the
  12175. tuple and extract the 6 bits that represent the tuple length, which
  12176. are the bits starting at index 1 and going up to and including bit 6.
  12177. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12178. (shift right) can be used to accomplish this.
  12179. We compile the \code{allocate} form to operations on the
  12180. \code{free\_ptr}, as shown next. This approach is called
  12181. \emph{inline allocation} because it implements allocation without a
  12182. function call by simply incrementing the allocation pointer. It is much
  12183. more efficient than calling a function for each allocation. The
  12184. address in the \code{free\_ptr} is the next free address in the
  12185. FromSpace, so we copy it into \code{r11} and then move it forward by
  12186. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12187. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12188. the tag. We then initialize the \itm{tag} and finally copy the
  12189. address in \code{r11} to the left-hand side. Refer to
  12190. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12191. %
  12192. \racket{We recommend using the Racket operations
  12193. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12194. during compilation.}
  12195. %
  12196. \python{We recommend using the bitwise-or operator \code{|} and the
  12197. shift-left operator \code{<<} to compute the tag during
  12198. compilation.}
  12199. %
  12200. The type annotation in the \code{allocate} form is used to determine
  12201. the pointer mask region of the tag.
  12202. %
  12203. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12204. address of the \code{free\_ptr} global variable using a special
  12205. instruction-pointer-relative addressing mode of the x86-64 processor.
  12206. In particular, the assembler computes the distance $d$ between the
  12207. address of \code{free\_ptr} and where the \code{rip} would be at that
  12208. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12209. \code{$d$(\%rip)}, which at runtime will compute the address of
  12210. \code{free\_ptr}.
  12211. %
  12212. {\if\edition\racketEd
  12213. \begin{lstlisting}
  12214. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12215. |$\Longrightarrow$|
  12216. movq free_ptr(%rip), %r11
  12217. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12218. movq $|$\itm{tag}$|, 0(%r11)
  12219. movq %r11, |$\itm{lhs}'$|
  12220. \end{lstlisting}
  12221. \fi}
  12222. {\if\edition\pythonEd
  12223. \begin{lstlisting}
  12224. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12225. |$\Longrightarrow$|
  12226. movq free_ptr(%rip), %r11
  12227. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12228. movq $|$\itm{tag}$|, 0(%r11)
  12229. movq %r11, |$\itm{lhs}'$|
  12230. \end{lstlisting}
  12231. \fi}
  12232. %
  12233. The \code{collect} form is compiled to a call to the \code{collect}
  12234. function in the runtime. The arguments to \code{collect} are (1) the
  12235. top of the root stack, and (2) the number of bytes that need to be
  12236. allocated. We use another dedicated register, \code{r15}, to store
  12237. the pointer to the top of the root stack. Therefore \code{r15} is not
  12238. available for use by the register allocator.
  12239. %
  12240. {\if\edition\racketEd
  12241. \begin{lstlisting}
  12242. (collect |$\itm{bytes}$|)
  12243. |$\Longrightarrow$|
  12244. movq %r15, %rdi
  12245. movq $|\itm{bytes}|, %rsi
  12246. callq collect
  12247. \end{lstlisting}
  12248. \fi}
  12249. {\if\edition\pythonEd
  12250. \begin{lstlisting}
  12251. collect(|$\itm{bytes}$|)
  12252. |$\Longrightarrow$|
  12253. movq %r15, %rdi
  12254. movq $|\itm{bytes}|, %rsi
  12255. callq collect
  12256. \end{lstlisting}
  12257. \fi}
  12258. \newcommand{\GrammarXGlobal}{
  12259. \begin{array}{lcl}
  12260. \Arg &::=& \itm{label} \key{(\%rip)}
  12261. \end{array}
  12262. }
  12263. \newcommand{\ASTXGlobalRacket}{
  12264. \begin{array}{lcl}
  12265. \Arg &::=& \GLOBAL{\itm{label}}
  12266. \end{array}
  12267. }
  12268. \begin{figure}[tp]
  12269. \begin{tcolorbox}[colback=white]
  12270. \[
  12271. \begin{array}{l}
  12272. \gray{\GrammarXInt} \\ \hline
  12273. \gray{\GrammarXIf} \\ \hline
  12274. \GrammarXGlobal \\
  12275. \begin{array}{lcl}
  12276. \LangXGlobalM{} &::= & \key{.globl main} \\
  12277. & & \key{main:} \; \Instr^{*}
  12278. \end{array}
  12279. \end{array}
  12280. \]
  12281. \end{tcolorbox}
  12282. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12283. \label{fig:x86-2-concrete}
  12284. \end{figure}
  12285. \begin{figure}[tp]
  12286. \begin{tcolorbox}[colback=white]
  12287. \small
  12288. \[
  12289. \begin{array}{l}
  12290. \gray{\ASTXIntRacket} \\ \hline
  12291. \gray{\ASTXIfRacket} \\ \hline
  12292. \ASTXGlobalRacket \\
  12293. \begin{array}{lcl}
  12294. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12295. \end{array}
  12296. \end{array}
  12297. \]
  12298. \end{tcolorbox}
  12299. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12300. \label{fig:x86-2}
  12301. \end{figure}
  12302. The definitions of the concrete and abstract syntax of the
  12303. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12304. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12305. of global variables.
  12306. %
  12307. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12308. \code{select\_instructions} pass on the running example.
  12309. \begin{figure}[tbp]
  12310. \centering
  12311. \begin{tcolorbox}[colback=white]
  12312. % tests/s2_17.rkt
  12313. \begin{tabular}{lll}
  12314. \begin{minipage}{0.5\textwidth}
  12315. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12316. start:
  12317. tmp9 = (global-value free_ptr);
  12318. tmp0 = (+ tmp9 16);
  12319. tmp1 = (global-value fromspace_end);
  12320. if (< tmp0 tmp1)
  12321. goto block0;
  12322. else
  12323. goto block1;
  12324. block0:
  12325. _4 = (void);
  12326. goto block9;
  12327. block1:
  12328. (collect 16)
  12329. goto block9;
  12330. block9:
  12331. alloc2 = (allocate 1 (Vector Integer));
  12332. _3 = (vector-set! alloc2 0 42);
  12333. vecinit6 = alloc2;
  12334. tmp2 = (global-value free_ptr);
  12335. tmp3 = (+ tmp2 16);
  12336. tmp4 = (global-value fromspace_end);
  12337. if (< tmp3 tmp4)
  12338. goto block7;
  12339. else
  12340. goto block8;
  12341. block7:
  12342. _8 = (void);
  12343. goto block6;
  12344. block8:
  12345. (collect 16)
  12346. goto block6;
  12347. block6:
  12348. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12349. _7 = (vector-set! alloc5 0 vecinit6);
  12350. tmp5 = (vector-ref alloc5 0);
  12351. return (vector-ref tmp5 0);
  12352. \end{lstlisting}
  12353. \end{minipage}
  12354. &$\Rightarrow$&
  12355. \begin{minipage}{0.4\textwidth}
  12356. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12357. start:
  12358. movq free_ptr(%rip), tmp9
  12359. movq tmp9, tmp0
  12360. addq $16, tmp0
  12361. movq fromspace_end(%rip), tmp1
  12362. cmpq tmp1, tmp0
  12363. jl block0
  12364. jmp block1
  12365. block0:
  12366. movq $0, _4
  12367. jmp block9
  12368. block1:
  12369. movq %r15, %rdi
  12370. movq $16, %rsi
  12371. callq collect
  12372. jmp block9
  12373. block9:
  12374. movq free_ptr(%rip), %r11
  12375. addq $16, free_ptr(%rip)
  12376. movq $3, 0(%r11)
  12377. movq %r11, alloc2
  12378. movq alloc2, %r11
  12379. movq $42, 8(%r11)
  12380. movq $0, _3
  12381. movq alloc2, vecinit6
  12382. movq free_ptr(%rip), tmp2
  12383. movq tmp2, tmp3
  12384. addq $16, tmp3
  12385. movq fromspace_end(%rip), tmp4
  12386. cmpq tmp4, tmp3
  12387. jl block7
  12388. jmp block8
  12389. block7:
  12390. movq $0, _8
  12391. jmp block6
  12392. block8:
  12393. movq %r15, %rdi
  12394. movq $16, %rsi
  12395. callq collect
  12396. jmp block6
  12397. block6:
  12398. movq free_ptr(%rip), %r11
  12399. addq $16, free_ptr(%rip)
  12400. movq $131, 0(%r11)
  12401. movq %r11, alloc5
  12402. movq alloc5, %r11
  12403. movq vecinit6, 8(%r11)
  12404. movq $0, _7
  12405. movq alloc5, %r11
  12406. movq 8(%r11), tmp5
  12407. movq tmp5, %r11
  12408. movq 8(%r11), %rax
  12409. jmp conclusion
  12410. \end{lstlisting}
  12411. \end{minipage}
  12412. \end{tabular}
  12413. \end{tcolorbox}
  12414. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12415. \code{select\_instructions} (\emph{right}) passes on the running
  12416. example.}
  12417. \label{fig:select-instr-output-gc}
  12418. \end{figure}
  12419. \clearpage
  12420. \section{Register Allocation}
  12421. \label{sec:reg-alloc-gc}
  12422. \index{subject}{register allocation}
  12423. As discussed previously in this chapter, the garbage collector needs to
  12424. access all the pointers in the root set, that is, all variables that
  12425. are tuples. It will be the responsibility of the register allocator
  12426. to make sure that
  12427. \begin{enumerate}
  12428. \item the root stack is used for spilling tuple-typed variables, and
  12429. \item if a tuple-typed variable is live during a call to the
  12430. collector, it must be spilled to ensure that it is visible to the
  12431. collector.
  12432. \end{enumerate}
  12433. The latter responsibility can be handled during construction of the
  12434. interference graph, by adding interference edges between the call-live
  12435. tuple-typed variables and all the callee-saved registers. (They
  12436. already interfere with the caller-saved registers.)
  12437. %
  12438. \racket{The type information for variables is in the \code{Program}
  12439. form, so we recommend adding another parameter to the
  12440. \code{build\_interference} function to communicate this alist.}
  12441. %
  12442. \python{The type information for variables is generated by the type
  12443. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12444. the \code{CProgram} AST mode. You'll need to propagate that
  12445. information so that it is available in this pass.}
  12446. The spilling of tuple-typed variables to the root stack can be handled
  12447. after graph coloring, in choosing how to assign the colors
  12448. (integers) to registers and stack locations. The
  12449. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12450. changes to also record the number of spills to the root stack.
  12451. % build-interference
  12452. %
  12453. % callq
  12454. % extra parameter for var->type assoc. list
  12455. % update 'program' and 'if'
  12456. % allocate-registers
  12457. % allocate spilled vectors to the rootstack
  12458. % don't change color-graph
  12459. % TODO:
  12460. %\section{Patch Instructions}
  12461. %[mention that global variables are memory references]
  12462. \section{Prelude and Conclusion}
  12463. \label{sec:print-x86-gc}
  12464. \label{sec:prelude-conclusion-x86-gc}
  12465. \index{subject}{prelude}\index{subject}{conclusion}
  12466. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12467. \code{prelude\_and\_conclusion} pass on the running example. In the
  12468. prelude of the \code{main} function, we allocate space
  12469. on the root stack to make room for the spills of tuple-typed
  12470. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12471. taking care that the root stack grows up instead of down. For the
  12472. running example, there was just one spill, so we increment \code{r15}
  12473. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12474. One issue that deserves special care is that there may be a call to
  12475. \code{collect} prior to the initializing assignments for all the
  12476. variables in the root stack. We do not want the garbage collector to
  12477. mistakenly determine that some uninitialized variable is a pointer that
  12478. needs to be followed. Thus, we zero out all locations on the root
  12479. stack in the prelude of \code{main}. In
  12480. figure~\ref{fig:print-x86-output-gc}, the instruction
  12481. %
  12482. \lstinline{movq $0, 0(%r15)}
  12483. %
  12484. is sufficient to accomplish this task because there is only one spill.
  12485. In general, we have to clear as many words as there are spills of
  12486. tuple-typed variables. The garbage collector tests each root to see
  12487. if it is null prior to dereferencing it.
  12488. \begin{figure}[htbp]
  12489. % TODO: Python Version -Jeremy
  12490. \begin{tcolorbox}[colback=white]
  12491. \begin{minipage}[t]{0.5\textwidth}
  12492. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12493. .globl main
  12494. main:
  12495. pushq %rbp
  12496. movq %rsp, %rbp
  12497. subq $0, %rsp
  12498. movq $65536, %rdi
  12499. movq $65536, %rsi
  12500. callq initialize
  12501. movq rootstack_begin(%rip), %r15
  12502. movq $0, 0(%r15)
  12503. addq $8, %r15
  12504. jmp start
  12505. conclusion:
  12506. subq $8, %r15
  12507. addq $0, %rsp
  12508. popq %rbp
  12509. retq
  12510. \end{lstlisting}
  12511. \end{minipage}
  12512. \end{tcolorbox}
  12513. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12514. \label{fig:print-x86-output-gc}
  12515. \end{figure}
  12516. \begin{figure}[tbp]
  12517. \begin{tcolorbox}[colback=white]
  12518. {\if\edition\racketEd
  12519. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12520. \node (Lvec) at (0,2) {\large \LangVec{}};
  12521. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12522. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12523. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12524. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12525. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12526. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12527. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12528. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12529. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12530. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12531. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12532. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12533. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12534. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12535. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12536. \path[->,bend left=15] (Lvec-4) edge [right] node
  12537. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12538. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12539. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12540. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12541. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12542. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12543. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12544. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12545. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12546. \end{tikzpicture}
  12547. \fi}
  12548. {\if\edition\pythonEd
  12549. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12550. \node (Lvec) at (0,2) {\large \LangVec{}};
  12551. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12552. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12553. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12554. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12555. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12556. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12557. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12558. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12559. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12560. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12561. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12562. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12563. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12564. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12565. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12566. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12567. \end{tikzpicture}
  12568. \fi}
  12569. \end{tcolorbox}
  12570. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12571. \label{fig:Lvec-passes}
  12572. \end{figure}
  12573. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12574. for the compilation of \LangVec{}.
  12575. \clearpage
  12576. {\if\edition\racketEd
  12577. \section{Challenge: Simple Structures}
  12578. \label{sec:simple-structures}
  12579. \index{subject}{struct}
  12580. \index{subject}{structure}
  12581. The language \LangStruct{} extends \LangVec{} with support for simple
  12582. structures. The definition of its concrete syntax is shown in
  12583. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12584. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12585. in Typed Racket is a user-defined data type that contains named fields
  12586. and that is heap allocated, similarly to a vector. The following is an
  12587. example of a structure definition, in this case the definition of a
  12588. \code{point} type:
  12589. \begin{lstlisting}
  12590. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12591. \end{lstlisting}
  12592. \newcommand{\LstructGrammarRacket}{
  12593. \begin{array}{lcl}
  12594. \Type &::=& \Var \\
  12595. \Exp &::=& (\Var\;\Exp \ldots)\\
  12596. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12597. \end{array}
  12598. }
  12599. \newcommand{\LstructASTRacket}{
  12600. \begin{array}{lcl}
  12601. \Type &::=& \VAR{\Var} \\
  12602. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12603. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12604. \end{array}
  12605. }
  12606. \begin{figure}[tbp]
  12607. \centering
  12608. \begin{tcolorbox}[colback=white]
  12609. \[
  12610. \begin{array}{l}
  12611. \gray{\LintGrammarRacket{}} \\ \hline
  12612. \gray{\LvarGrammarRacket{}} \\ \hline
  12613. \gray{\LifGrammarRacket{}} \\ \hline
  12614. \gray{\LwhileGrammarRacket} \\ \hline
  12615. \gray{\LtupGrammarRacket} \\ \hline
  12616. \LstructGrammarRacket \\
  12617. \begin{array}{lcl}
  12618. \LangStruct{} &::=& \Def \ldots \; \Exp
  12619. \end{array}
  12620. \end{array}
  12621. \]
  12622. \end{tcolorbox}
  12623. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12624. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12625. \label{fig:Lstruct-concrete-syntax}
  12626. \end{figure}
  12627. \begin{figure}[tbp]
  12628. \centering
  12629. \begin{tcolorbox}[colback=white]
  12630. \small
  12631. \[
  12632. \begin{array}{l}
  12633. \gray{\LintASTRacket{}} \\ \hline
  12634. \gray{\LvarASTRacket{}} \\ \hline
  12635. \gray{\LifASTRacket{}} \\ \hline
  12636. \gray{\LwhileASTRacket} \\ \hline
  12637. \gray{\LtupASTRacket} \\ \hline
  12638. \LstructASTRacket \\
  12639. \begin{array}{lcl}
  12640. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12641. \end{array}
  12642. \end{array}
  12643. \]
  12644. \end{tcolorbox}
  12645. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12646. (figure~\ref{fig:Lvec-syntax}).}
  12647. \label{fig:Lstruct-syntax}
  12648. \end{figure}
  12649. An instance of a structure is created using function-call syntax, with
  12650. the name of the structure in the function position, as follows:
  12651. \begin{lstlisting}
  12652. (point 7 12)
  12653. \end{lstlisting}
  12654. Function-call syntax is also used to read a field of a structure. The
  12655. function name is formed by the structure name, a dash, and the field
  12656. name. The following example uses \code{point-x} and \code{point-y} to
  12657. access the \code{x} and \code{y} fields of two point instances:
  12658. \begin{center}
  12659. \begin{lstlisting}
  12660. (let ([pt1 (point 7 12)])
  12661. (let ([pt2 (point 4 3)])
  12662. (+ (- (point-x pt1) (point-x pt2))
  12663. (- (point-y pt1) (point-y pt2)))))
  12664. \end{lstlisting}
  12665. \end{center}
  12666. Similarly, to write to a field of a structure, use its set function,
  12667. whose name starts with \code{set-}, followed by the structure name,
  12668. then a dash, then the field name, and finally with an exclamation
  12669. mark. The following example uses \code{set-point-x!} to change the
  12670. \code{x} field from \code{7} to \code{42}:
  12671. \begin{center}
  12672. \begin{lstlisting}
  12673. (let ([pt (point 7 12)])
  12674. (let ([_ (set-point-x! pt 42)])
  12675. (point-x pt)))
  12676. \end{lstlisting}
  12677. \end{center}
  12678. \begin{exercise}\normalfont\normalsize
  12679. Create a type checker for \LangStruct{} by extending the type
  12680. checker for \LangVec{}. Extend your compiler with support for simple
  12681. structures, compiling \LangStruct{} to x86 assembly code. Create
  12682. five new test cases that use structures and, test your compiler.
  12683. \end{exercise}
  12684. % TODO: create an interpreter for L_struct
  12685. \clearpage
  12686. \fi}
  12687. \section{Challenge: Arrays}
  12688. \label{sec:arrays}
  12689. % TODO mention trapped-error
  12690. In this chapter we have studied tuples, that is, heterogeneous
  12691. sequences of elements whose length is determined at compile time. This
  12692. challenge is also about sequences, but this time the length is
  12693. determined at runtime and all the elements have the same type (they
  12694. are homogeneous). We use the term \emph{array} for this latter kind of
  12695. sequence.
  12696. %
  12697. \racket{
  12698. The Racket language does not distinguish between tuples and arrays;
  12699. they are both represented by vectors. However, Typed Racket
  12700. distinguishes between tuples and arrays: the \code{Vector} type is for
  12701. tuples, and the \code{Vectorof} type is for arrays.}
  12702. \python{
  12703. Arrays correspond to the \code{list} type in Python language.
  12704. }
  12705. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12706. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12707. presents the definition of the abstract syntax, extending \LangVec{}
  12708. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12709. %
  12710. \racket{\code{make-vector} primitive operator for creating an array,
  12711. whose arguments are the length of the array and an initial value for
  12712. all the elements in the array.}
  12713. \python{bracket notation for creating an array literal.}
  12714. \racket{
  12715. The \code{vector-length},
  12716. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12717. for tuples become overloaded for use with arrays.}
  12718. \python{
  12719. The subscript operator becomes overloaded for use with arrays and tuples
  12720. and now may appear on the left-hand side of an assignment.
  12721. Note that the index of the subscript, when applied to an array, may be an
  12722. arbitrary expression and not just a constant integer.
  12723. The \code{len} function is also applicable to arrays.
  12724. }
  12725. %
  12726. We include integer multiplication in \LangArray{}, because it is
  12727. useful in many examples involving arrays such as computing the
  12728. inner product of two arrays (figure~\ref{fig:inner_product}).
  12729. \newcommand{\LarrayGrammarRacket}{
  12730. \begin{array}{lcl}
  12731. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12732. \Exp &::=& \CMUL{\Exp}{\Exp}
  12733. \MID \CMAKEVEC{\Exp}{\Exp}
  12734. \end{array}
  12735. }
  12736. \newcommand{\LarrayASTRacket}{
  12737. \begin{array}{lcl}
  12738. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12739. \Exp &::=& \MUL{\Exp}{\Exp}
  12740. \MID \MAKEVEC{\Exp}{\Exp}
  12741. \end{array}
  12742. }
  12743. \newcommand{\LarrayGrammarPython}{
  12744. \begin{array}{lcl}
  12745. \Type &::=& \key{list}\LS\Type\RS \\
  12746. \Exp &::=& \CMUL{\Exp}{\Exp}
  12747. \MID \CGET{\Exp}{\Exp}
  12748. \MID \LS \Exp \code{,} \ldots \RS \\
  12749. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12750. \end{array}
  12751. }
  12752. \newcommand{\LarrayASTPython}{
  12753. \begin{array}{lcl}
  12754. \Type &::=& \key{ListType}\LP\Type\RP \\
  12755. \Exp &::=& \MUL{\Exp}{\Exp}
  12756. \MID \GET{\Exp}{\Exp} \\
  12757. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12758. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12759. \end{array}
  12760. }
  12761. \begin{figure}[tp]
  12762. \centering
  12763. \begin{tcolorbox}[colback=white]
  12764. \small
  12765. {\if\edition\racketEd
  12766. \[
  12767. \begin{array}{l}
  12768. \gray{\LintGrammarRacket{}} \\ \hline
  12769. \gray{\LvarGrammarRacket{}} \\ \hline
  12770. \gray{\LifGrammarRacket{}} \\ \hline
  12771. \gray{\LwhileGrammarRacket} \\ \hline
  12772. \gray{\LtupGrammarRacket} \\ \hline
  12773. \LarrayGrammarRacket \\
  12774. \begin{array}{lcl}
  12775. \LangArray{} &::=& \Exp
  12776. \end{array}
  12777. \end{array}
  12778. \]
  12779. \fi}
  12780. {\if\edition\pythonEd
  12781. \[
  12782. \begin{array}{l}
  12783. \gray{\LintGrammarPython{}} \\ \hline
  12784. \gray{\LvarGrammarPython{}} \\ \hline
  12785. \gray{\LifGrammarPython{}} \\ \hline
  12786. \gray{\LwhileGrammarPython} \\ \hline
  12787. \gray{\LtupGrammarPython} \\ \hline
  12788. \LarrayGrammarPython \\
  12789. \begin{array}{rcl}
  12790. \LangArrayM{} &::=& \Stmt^{*}
  12791. \end{array}
  12792. \end{array}
  12793. \]
  12794. \fi}
  12795. \end{tcolorbox}
  12796. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12797. \label{fig:Lvecof-concrete-syntax}
  12798. \end{figure}
  12799. \begin{figure}[tp]
  12800. \centering
  12801. \begin{tcolorbox}[colback=white]
  12802. \small
  12803. {\if\edition\racketEd
  12804. \[
  12805. \begin{array}{l}
  12806. \gray{\LintASTRacket{}} \\ \hline
  12807. \gray{\LvarASTRacket{}} \\ \hline
  12808. \gray{\LifASTRacket{}} \\ \hline
  12809. \gray{\LwhileASTRacket} \\ \hline
  12810. \gray{\LtupASTRacket} \\ \hline
  12811. \LarrayASTRacket \\
  12812. \begin{array}{lcl}
  12813. \LangArray{} &::=& \Exp
  12814. \end{array}
  12815. \end{array}
  12816. \]
  12817. \fi}
  12818. {\if\edition\pythonEd
  12819. \[
  12820. \begin{array}{l}
  12821. \gray{\LintASTPython{}} \\ \hline
  12822. \gray{\LvarASTPython{}} \\ \hline
  12823. \gray{\LifASTPython{}} \\ \hline
  12824. \gray{\LwhileASTPython} \\ \hline
  12825. \gray{\LtupASTPython} \\ \hline
  12826. \LarrayASTPython \\
  12827. \begin{array}{rcl}
  12828. \LangArrayM{} &::=& \Stmt^{*}
  12829. \end{array}
  12830. \end{array}
  12831. \]
  12832. \fi}
  12833. \end{tcolorbox}
  12834. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12835. \label{fig:Lvecof-syntax}
  12836. \end{figure}
  12837. \begin{figure}[tp]
  12838. \begin{tcolorbox}[colback=white]
  12839. {\if\edition\racketEd
  12840. % TODO: remove the function from the following example, like the python version -Jeremy
  12841. \begin{lstlisting}
  12842. (let ([A (make-vector 2 2)])
  12843. (let ([B (make-vector 2 3)])
  12844. (let ([i 0])
  12845. (let ([prod 0])
  12846. (begin
  12847. (while (< i n)
  12848. (begin
  12849. (set! prod (+ prod (* (vector-ref A i)
  12850. (vector-ref B i))))
  12851. (set! i (+ i 1))))
  12852. prod)))))
  12853. \end{lstlisting}
  12854. \fi}
  12855. {\if\edition\pythonEd
  12856. \begin{lstlisting}
  12857. A = [2, 2]
  12858. B = [3, 3]
  12859. i = 0
  12860. prod = 0
  12861. while i != len(A):
  12862. prod = prod + A[i] * B[i]
  12863. i = i + 1
  12864. print( prod )
  12865. \end{lstlisting}
  12866. \fi}
  12867. \end{tcolorbox}
  12868. \caption{Example program that computes the inner product.}
  12869. \label{fig:inner_product}
  12870. \end{figure}
  12871. {\if\edition\racketEd
  12872. %
  12873. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12874. checker for \LangArray{}. The result type of
  12875. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12876. of the initializing expression. The length expression is required to
  12877. have type \code{Integer}. The type checking of the operators
  12878. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12879. updated to handle the situation in which the vector has type
  12880. \code{Vectorof}. In these cases we translate the operators to their
  12881. \code{vectorof} form so that later passes can easily distinguish
  12882. between operations on tuples versus arrays. We override the
  12883. \code{operator-types} method to provide the type signature for
  12884. multiplication: it takes two integers and returns an integer. \fi}
  12885. {\if\edition\pythonEd
  12886. %
  12887. The type checker for \LangArray{} is defined in
  12888. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12889. is \code{list[T]} where \code{T} is the type of the initializing
  12890. expressions. The type checking of the \code{len} function and the
  12891. subscript operator is updated to handle lists. The type checker now
  12892. also handles a subscript on the left-hand side of an assignment.
  12893. Regarding multiplication, it takes two integers and returns an
  12894. integer.
  12895. %
  12896. \fi}
  12897. \begin{figure}[tbp]
  12898. \begin{tcolorbox}[colback=white]
  12899. {\if\edition\racketEd
  12900. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12901. (define type-check-Lvecof-class
  12902. (class type-check-Lvec-class
  12903. (super-new)
  12904. (inherit check-type-equal?)
  12905. (define/override (operator-types)
  12906. (append '((* . ((Integer Integer) . Integer)))
  12907. (super operator-types)))
  12908. (define/override (type-check-exp env)
  12909. (lambda (e)
  12910. (define recur (type-check-exp env))
  12911. (match e
  12912. [(Prim 'make-vector (list e1 e2))
  12913. (define-values (e1^ t1) (recur e1))
  12914. (define-values (e2^ elt-type) (recur e2))
  12915. (define vec-type `(Vectorof ,elt-type))
  12916. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12917. [(Prim 'vector-ref (list e1 e2))
  12918. (define-values (e1^ t1) (recur e1))
  12919. (define-values (e2^ t2) (recur e2))
  12920. (match* (t1 t2)
  12921. [(`(Vectorof ,elt-type) 'Integer)
  12922. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12923. [(other wise) ((super type-check-exp env) e)])]
  12924. [(Prim 'vector-set! (list e1 e2 e3) )
  12925. (define-values (e-vec t-vec) (recur e1))
  12926. (define-values (e2^ t2) (recur e2))
  12927. (define-values (e-arg^ t-arg) (recur e3))
  12928. (match t-vec
  12929. [`(Vectorof ,elt-type)
  12930. (check-type-equal? elt-type t-arg e)
  12931. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12932. [else ((super type-check-exp env) e)])]
  12933. [(Prim 'vector-length (list e1))
  12934. (define-values (e1^ t1) (recur e1))
  12935. (match t1
  12936. [`(Vectorof ,t)
  12937. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12938. [else ((super type-check-exp env) e)])]
  12939. [else ((super type-check-exp env) e)])))
  12940. ))
  12941. (define (type-check-Lvecof p)
  12942. (send (new type-check-Lvecof-class) type-check-program p))
  12943. \end{lstlisting}
  12944. \fi}
  12945. {\if\edition\pythonEd
  12946. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12947. class TypeCheckLarray(TypeCheckLtup):
  12948. def type_check_exp(self, e, env):
  12949. match e:
  12950. case ast.List(es, Load()):
  12951. ts = [self.type_check_exp(e, env) for e in es]
  12952. elt_ty = ts[0]
  12953. for (ty, elt) in zip(ts, es):
  12954. self.check_type_equal(elt_ty, ty, elt)
  12955. e.has_type = ListType(elt_ty)
  12956. return e.has_type
  12957. case Call(Name('len'), [tup]):
  12958. tup_t = self.type_check_exp(tup, env)
  12959. tup.has_type = tup_t
  12960. match tup_t:
  12961. case TupleType(ts):
  12962. return IntType()
  12963. case ListType(ty):
  12964. return IntType()
  12965. case _:
  12966. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12967. case Subscript(tup, index, Load()):
  12968. tup_ty = self.type_check_exp(tup, env)
  12969. index_ty = self.type_check_exp(index, env)
  12970. self.check_type_equal(index_ty, IntType(), index)
  12971. match tup_ty:
  12972. case TupleType(ts):
  12973. match index:
  12974. case Constant(i):
  12975. return ts[i]
  12976. case _:
  12977. raise Exception('subscript required constant integer index')
  12978. case ListType(ty):
  12979. return ty
  12980. case _:
  12981. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12982. case BinOp(left, Mult(), right):
  12983. l = self.type_check_exp(left, env)
  12984. self.check_type_equal(l, IntType(), left)
  12985. r = self.type_check_exp(right, env)
  12986. self.check_type_equal(r, IntType(), right)
  12987. return IntType()
  12988. case _:
  12989. return super().type_check_exp(e, env)
  12990. def type_check_stmts(self, ss, env):
  12991. if len(ss) == 0:
  12992. return VoidType()
  12993. match ss[0]:
  12994. case Assign([Subscript(tup, index, Store())], value):
  12995. tup_t = self.type_check_exp(tup, env)
  12996. value_t = self.type_check_exp(value, env)
  12997. index_ty = self.type_check_exp(index, env)
  12998. self.check_type_equal(index_ty, IntType(), index)
  12999. match tup_t:
  13000. case ListType(ty):
  13001. self.check_type_equal(ty, value_t, ss[0])
  13002. case TupleType(ts):
  13003. return self.type_check_stmts(ss, env)
  13004. case _:
  13005. raise Exception('type_check_stmts: '
  13006. 'expected tuple or list, not ' + repr(tup_t))
  13007. return self.type_check_stmts(ss[1:], env)
  13008. case _:
  13009. return super().type_check_stmts(ss, env)
  13010. \end{lstlisting}
  13011. \fi}
  13012. \end{tcolorbox}
  13013. \caption{Type checker for the \LangArray{} language.}
  13014. \label{fig:type-check-Lvecof}
  13015. \end{figure}
  13016. The definition of the interpreter for \LangArray{} is shown in
  13017. figure~\ref{fig:interp-Lvecof}.
  13018. \racket{The \code{make-vector} operator is
  13019. interpreted using Racket's \code{make-vector} function,
  13020. and multiplication is interpreted using \code{fx*},
  13021. which is multiplication for \code{fixnum} integers.
  13022. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  13023. we translate array access operations
  13024. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13025. which we interpret using \code{vector} operations with additional
  13026. bounds checks that signal a \code{trapped-error}.
  13027. }
  13028. %
  13029. \python{We implement list creation with a Python list comprehension
  13030. and multiplication is implemented with Python multiplication. We
  13031. add a case to handle a subscript on the left-hand side of
  13032. assignment. Other uses of subscript can be handled by the existing
  13033. code for tuples.}
  13034. \begin{figure}[tbp]
  13035. \begin{tcolorbox}[colback=white]
  13036. {\if\edition\racketEd
  13037. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13038. (define interp-Lvecof-class
  13039. (class interp-Lvec-class
  13040. (super-new)
  13041. (define/override (interp-op op)
  13042. (match op
  13043. ['make-vector make-vector]
  13044. ['vectorof-length vector-length]
  13045. ['vectorof-ref
  13046. (lambda (v i)
  13047. (if (< i (vector-length v))
  13048. (vector-ref v i)
  13049. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13050. ['vectorof-set!
  13051. (lambda (v i e)
  13052. (if (< i (vector-length v))
  13053. (vector-set! v i e)
  13054. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13055. [else (super interp-op op)]))
  13056. ))
  13057. (define (interp-Lvecof p)
  13058. (send (new interp-Lvecof-class) interp-program p))
  13059. \end{lstlisting}
  13060. \fi}
  13061. {\if\edition\pythonEd
  13062. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13063. class InterpLarray(InterpLtup):
  13064. def interp_exp(self, e, env):
  13065. match e:
  13066. case ast.List(es, Load()):
  13067. return [self.interp_exp(e, env) for e in es]
  13068. case BinOp(left, Mult(), right):
  13069. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13070. return l * r
  13071. case _:
  13072. return super().interp_exp(e, env)
  13073. def interp_stmts(self, ss, env):
  13074. if len(ss) == 0:
  13075. return
  13076. match ss[0]:
  13077. case Assign([Subscript(lst, index)], value):
  13078. lst = self.interp_exp(lst, env)
  13079. index = self.interp_exp(index, env)
  13080. lst[index] = self.interp_exp(value, env)
  13081. return self.interp_stmts(ss[1:], env)
  13082. case _:
  13083. return super().interp_stmts(ss, env)
  13084. \end{lstlisting}
  13085. \fi}
  13086. \end{tcolorbox}
  13087. \caption{Interpreter for \LangArray{}.}
  13088. \label{fig:interp-Lvecof}
  13089. \end{figure}
  13090. \subsection{Data Representation}
  13091. \label{sec:array-rep}
  13092. Just as with tuples, we store arrays on the heap, which means that the
  13093. garbage collector will need to inspect arrays. An immediate thought is
  13094. to use the same representation for arrays that we use for tuples.
  13095. However, we limit tuples to a length of fifty so that their length and
  13096. pointer mask can fit into the 64-bit tag at the beginning of each
  13097. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13098. millions of elements, so we need more bits to store the length.
  13099. However, because arrays are homogeneous, we need only 1 bit for the
  13100. pointer mask instead of 1 bit per array element. Finally, the
  13101. garbage collector must be able to distinguish between tuples
  13102. and arrays, so we need to reserve one bit for that purpose. We
  13103. arrive at the following layout for the 64-bit tag at the beginning of
  13104. an array:
  13105. \begin{itemize}
  13106. \item The right-most bit is the forwarding bit, just as in a tuple.
  13107. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13108. that it is not.
  13109. \item The next bit to the left is the pointer mask. A $0$ indicates
  13110. that none of the elements are pointers to the heap, and a $1$
  13111. indicates that all the elements are pointers.
  13112. \item The next $60$ bits store the length of the array.
  13113. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13114. and an array ($1$).
  13115. \item The left-most bit is reserved as explained in
  13116. chapter~\ref{ch:Lgrad}.
  13117. \end{itemize}
  13118. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13119. %% differentiate the kinds of values that have been injected into the
  13120. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13121. %% to indicate that the value is an array.
  13122. In the following subsections we provide hints regarding how to update
  13123. the passes to handle arrays.
  13124. \subsection{Overload Resolution}
  13125. \label{sec:array-resolution}
  13126. As noted previously, with the addition of arrays, several operators
  13127. have become \emph{overloaded}; that is, they can be applied to values
  13128. of more than one type. In this case, the element access and length
  13129. operators can be applied to both tuples and arrays. This kind of
  13130. overloading is quite common in programming languages, so many
  13131. compilers perform \emph{overload resolution}\index{subject}{overload
  13132. resolution} to handle it. The idea is to translate each overloaded
  13133. operator into different operators for the different types.
  13134. Implement a new pass named \code{resolve}.
  13135. Translate the reading of an array element
  13136. into a call to
  13137. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13138. and the writing of an array element to
  13139. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13140. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13141. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13142. When these operators are applied to tuples, leave them as is.
  13143. %
  13144. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13145. field which can be inspected to determine whether the operator
  13146. is applied to a tuple or an array.}
  13147. \subsection{Bounds Checking}
  13148. Recall that the interpreter for \LangArray{} signals a
  13149. \code{trapped-error} when there is an array access that is out of
  13150. bounds. Therefore your compiler is obliged to also catch these errors
  13151. during execution and halt, signaling an error. We recommend inserting
  13152. a new pass named \code{check\_bounds} that inserts code around each
  13153. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13154. \python{subscript} operation to ensure that the index is greater than
  13155. or equal to zero and less than the array's length. If not, the program
  13156. should halt, for which we recommend using a new primitive operation
  13157. named \code{exit}.
  13158. %% \subsection{Reveal Casts}
  13159. %% The array-access operators \code{vectorof-ref} and
  13160. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13161. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13162. %% that the type checker cannot tell whether the index will be in bounds,
  13163. %% so the bounds check must be performed at run time. Recall that the
  13164. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13165. %% an \code{If} around a vector reference for update to check whether
  13166. %% the index is less than the length. You should do the same for
  13167. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13168. %% In addition, the handling of the \code{any-vector} operators in
  13169. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13170. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13171. %% generated code should test whether the tag is for tuples (\code{010})
  13172. %% or arrays (\code{110}) and then dispatch to either
  13173. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13174. %% we add a case in \code{select\_instructions} to generate the
  13175. %% appropriate instructions for accessing the array length from the
  13176. %% header of an array.
  13177. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13178. %% the generated code needs to check that the index is less than the
  13179. %% vector length, so like the code for \code{any-vector-length}, check
  13180. %% the tag to determine whether to use \code{any-vector-length} or
  13181. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13182. %% is complete, the generated code can use \code{any-vector-ref} and
  13183. %% \code{any-vector-set!} for both tuples and arrays because the
  13184. %% instructions used for those operators do not look at the tag at the
  13185. %% front of the tuple or array.
  13186. \subsection{Expose Allocation}
  13187. This pass should translate array creation into lower-level
  13188. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13189. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13190. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13191. array. The \code{AllocateArray} AST node allocates an array of the
  13192. length specified by the $\Exp$ (of type \INTTY), but does not
  13193. initialize the elements of the array. Generate code in this pass to
  13194. initialize the elements analogous to the case for tuples.
  13195. {\if\edition\racketEd
  13196. \section{Uncover \texttt{get!}}
  13197. \label{sec:uncover-get-bang-vecof}
  13198. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13199. \code{uncover-get!-exp}.
  13200. \fi}
  13201. \subsection{Remove Complex Operands}
  13202. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13203. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13204. complex, and its subexpression must be atomic.
  13205. \subsection{Explicate Control}
  13206. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13207. \code{explicate\_assign}.
  13208. \subsection{Select Instructions}
  13209. Generate instructions for \code{AllocateArray} similar to those for
  13210. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13211. except that the tag at the front of the array should instead use the
  13212. representation discussed in section~\ref{sec:array-rep}.
  13213. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13214. extract the length from the tag.
  13215. The instructions generated for accessing an element of an array differ
  13216. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13217. that the index is not a constant so you need to generate instructions
  13218. that compute the offset at runtime.
  13219. Compile the \code{exit} primitive into a call to the \code{exit}
  13220. function of the C standard library, with an argument of $255$.
  13221. %% Also, note that assignment to an array element may appear in
  13222. %% as a stand-alone statement, so make sure to handle that situation in
  13223. %% this pass.
  13224. %% Finally, the instructions for \code{any-vectorof-length} should be
  13225. %% similar to those for \code{vectorof-length}, except that one must
  13226. %% first project the array by writing zeroes into the $3$-bit tag
  13227. \begin{exercise}\normalfont\normalsize
  13228. Implement a compiler for the \LangArray{} language by extending your
  13229. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13230. programs, including the one shown in figure~\ref{fig:inner_product}
  13231. and also a program that multiplies two matrices. Note that although
  13232. matrices are two-dimensional arrays, they can be encoded into
  13233. one-dimensional arrays by laying out each row in the array, one after
  13234. the next.
  13235. \end{exercise}
  13236. {\if\edition\racketEd
  13237. \section{Challenge: Generational Collection}
  13238. The copying collector described in section~\ref{sec:GC} can incur
  13239. significant runtime overhead because the call to \code{collect} takes
  13240. time proportional to all the live data. One way to reduce this
  13241. overhead is to reduce how much data is inspected in each call to
  13242. \code{collect}. In particular, researchers have observed that recently
  13243. allocated data is more likely to become garbage then data that has
  13244. survived one or more previous calls to \code{collect}. This insight
  13245. motivated the creation of \emph{generational garbage collectors}
  13246. \index{subject}{generational garbage collector} that
  13247. (1) segregate data according to its age into two or more generations;
  13248. (2) allocate less space for younger generations, so collecting them is
  13249. faster, and more space for the older generations; and (3) perform
  13250. collection on the younger generations more frequently than on older
  13251. generations~\citep{Wilson:1992fk}.
  13252. For this challenge assignment, the goal is to adapt the copying
  13253. collector implemented in \code{runtime.c} to use two generations, one
  13254. for young data and one for old data. Each generation consists of a
  13255. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13256. \code{collect} function to use the two generations:
  13257. \begin{enumerate}
  13258. \item Copy the young generation's FromSpace to its ToSpace and then
  13259. switch the role of the ToSpace and FromSpace
  13260. \item If there is enough space for the requested number of bytes in
  13261. the young FromSpace, then return from \code{collect}.
  13262. \item If there is not enough space in the young FromSpace for the
  13263. requested bytes, then move the data from the young generation to the
  13264. old one with the following steps:
  13265. \begin{enumerate}
  13266. \item[a.] If there is enough room in the old FromSpace, copy the young
  13267. FromSpace to the old FromSpace and then return.
  13268. \item[b.] If there is not enough room in the old FromSpace, then collect
  13269. the old generation by copying the old FromSpace to the old ToSpace
  13270. and swap the roles of the old FromSpace and ToSpace.
  13271. \item[c.] If there is enough room now, copy the young FromSpace to the
  13272. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13273. and ToSpace for the old generation. Copy the young FromSpace and
  13274. the old FromSpace into the larger FromSpace for the old
  13275. generation and then return.
  13276. \end{enumerate}
  13277. \end{enumerate}
  13278. We recommend that you generalize the \code{cheney} function so that it
  13279. can be used for all the copies mentioned: between the young FromSpace
  13280. and ToSpace, between the old FromSpace and ToSpace, and between the
  13281. young FromSpace and old FromSpace. This can be accomplished by adding
  13282. parameters to \code{cheney} that replace its use of the global
  13283. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13284. \code{tospace\_begin}, and \code{tospace\_end}.
  13285. Note that the collection of the young generation does not traverse the
  13286. old generation. This introduces a potential problem: there may be
  13287. young data that is reachable only through pointers in the old
  13288. generation. If these pointers are not taken into account, the
  13289. collector could throw away young data that is live! One solution,
  13290. called \emph{pointer recording}, is to maintain a set of all the
  13291. pointers from the old generation into the new generation and consider
  13292. this set as part of the root set. To maintain this set, the compiler
  13293. must insert extra instructions around every \code{vector-set!}. If the
  13294. vector being modified is in the old generation, and if the value being
  13295. written is a pointer into the new generation, then that pointer must
  13296. be added to the set. Also, if the value being overwritten was a
  13297. pointer into the new generation, then that pointer should be removed
  13298. from the set.
  13299. \begin{exercise}\normalfont\normalsize
  13300. Adapt the \code{collect} function in \code{runtime.c} to implement
  13301. generational garbage collection, as outlined in this section.
  13302. Update the code generation for \code{vector-set!} to implement
  13303. pointer recording. Make sure that your new compiler and runtime
  13304. execute without error on your test suite.
  13305. \end{exercise}
  13306. \fi}
  13307. \section{Further Reading}
  13308. \citet{Appel90} describes many data representation approaches,
  13309. including the ones used in the compilation of Standard ML.
  13310. There are many alternatives to copying collectors (and their bigger
  13311. siblings, the generational collectors) with regard to garbage
  13312. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13313. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13314. collectors are that allocation is fast (just a comparison and pointer
  13315. increment), there is no fragmentation, cyclic garbage is collected,
  13316. and the time complexity of collection depends only on the amount of
  13317. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13318. main disadvantages of a two-space copying collector is that it uses a
  13319. lot of extra space and takes a long time to perform the copy, though
  13320. these problems are ameliorated in generational collectors.
  13321. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13322. small objects and generate a lot of garbage, so copying and
  13323. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13324. Garbage collection is an active research topic, especially concurrent
  13325. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13326. developing new techniques and revisiting old
  13327. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13328. meet every year at the International Symposium on Memory Management to
  13329. present these findings.
  13330. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13331. \chapter{Functions}
  13332. \label{ch:Lfun}
  13333. \index{subject}{function}
  13334. \setcounter{footnote}{0}
  13335. This chapter studies the compilation of a subset of \racket{Typed
  13336. Racket}\python{Python} in which only top-level function definitions
  13337. are allowed. This kind of function appears in the C programming
  13338. language, and it serves as an important stepping-stone to implementing
  13339. lexically scoped functions in the form of \key{lambda} abstractions,
  13340. which is the topic of chapter~\ref{ch:Llambda}.
  13341. \section{The \LangFun{} Language}
  13342. The concrete syntax and abstract syntax for function definitions and
  13343. function application are shown in
  13344. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13345. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13346. with zero or more function definitions. The function names from these
  13347. definitions are in scope for the entire program, including all the
  13348. function definitions, and therefore the ordering of function
  13349. definitions does not matter.
  13350. %
  13351. \python{The abstract syntax for function parameters in
  13352. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13353. consists of a parameter name and its type. This design differs from
  13354. Python's \code{ast} module, which has a more complex structure for
  13355. function parameters to handle keyword parameters,
  13356. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13357. complex Python abstract syntax into the simpler syntax of
  13358. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13359. \code{FunctionDef} constructor are for decorators and a type
  13360. comment, neither of which are used by our compiler. We recommend
  13361. replacing them with \code{None} in the \code{shrink} pass.
  13362. }
  13363. %
  13364. The concrete syntax for function application
  13365. \index{subject}{function application}
  13366. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13367. where the first expression
  13368. must evaluate to a function and the remaining expressions are the arguments. The
  13369. abstract syntax for function application is
  13370. $\APPLY{\Exp}{\Exp^*}$.
  13371. %% The syntax for function application does not include an explicit
  13372. %% keyword, which is error prone when using \code{match}. To alleviate
  13373. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13374. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13375. Functions are first-class in the sense that a function pointer
  13376. \index{subject}{function pointer} is data and can be stored in memory or passed
  13377. as a parameter to another function. Thus, there is a function
  13378. type, written
  13379. {\if\edition\racketEd
  13380. \begin{lstlisting}
  13381. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13382. \end{lstlisting}
  13383. \fi}
  13384. {\if\edition\pythonEd
  13385. \begin{lstlisting}
  13386. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13387. \end{lstlisting}
  13388. \fi}
  13389. %
  13390. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13391. through $\Type_n$ and whose return type is $\Type_R$. The main
  13392. limitation of these functions (with respect to
  13393. \racket{Racket}\python{Python} functions) is that they are not
  13394. lexically scoped. That is, the only external entities that can be
  13395. referenced from inside a function body are other globally defined
  13396. functions. The syntax of \LangFun{} prevents function definitions from
  13397. being nested inside each other.
  13398. \newcommand{\LfunGrammarRacket}{
  13399. \begin{array}{lcl}
  13400. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13401. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13402. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13403. \end{array}
  13404. }
  13405. \newcommand{\LfunASTRacket}{
  13406. \begin{array}{lcl}
  13407. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13408. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13409. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13410. \end{array}
  13411. }
  13412. \newcommand{\LfunGrammarPython}{
  13413. \begin{array}{lcl}
  13414. \Type &::=& \key{int}
  13415. \MID \key{bool} \MID \key{void}
  13416. \MID \key{tuple}\LS \Type^+ \RS
  13417. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13418. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13419. \Stmt &::=& \CRETURN{\Exp} \\
  13420. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13421. \end{array}
  13422. }
  13423. \newcommand{\LfunASTPython}{
  13424. \begin{array}{lcl}
  13425. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13426. \MID \key{TupleType}\LS\Type^+\RS\\
  13427. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13428. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13429. \Stmt &::=& \RETURN{\Exp} \\
  13430. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13431. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13432. \end{array}
  13433. }
  13434. \begin{figure}[tp]
  13435. \centering
  13436. \begin{tcolorbox}[colback=white]
  13437. \small
  13438. {\if\edition\racketEd
  13439. \[
  13440. \begin{array}{l}
  13441. \gray{\LintGrammarRacket{}} \\ \hline
  13442. \gray{\LvarGrammarRacket{}} \\ \hline
  13443. \gray{\LifGrammarRacket{}} \\ \hline
  13444. \gray{\LwhileGrammarRacket} \\ \hline
  13445. \gray{\LtupGrammarRacket} \\ \hline
  13446. \LfunGrammarRacket \\
  13447. \begin{array}{lcl}
  13448. \LangFunM{} &::=& \Def \ldots \; \Exp
  13449. \end{array}
  13450. \end{array}
  13451. \]
  13452. \fi}
  13453. {\if\edition\pythonEd
  13454. \[
  13455. \begin{array}{l}
  13456. \gray{\LintGrammarPython{}} \\ \hline
  13457. \gray{\LvarGrammarPython{}} \\ \hline
  13458. \gray{\LifGrammarPython{}} \\ \hline
  13459. \gray{\LwhileGrammarPython} \\ \hline
  13460. \gray{\LtupGrammarPython} \\ \hline
  13461. \LfunGrammarPython \\
  13462. \begin{array}{rcl}
  13463. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13464. \end{array}
  13465. \end{array}
  13466. \]
  13467. \fi}
  13468. \end{tcolorbox}
  13469. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13470. \label{fig:Lfun-concrete-syntax}
  13471. \end{figure}
  13472. \begin{figure}[tp]
  13473. \centering
  13474. \begin{tcolorbox}[colback=white]
  13475. \small
  13476. {\if\edition\racketEd
  13477. \[
  13478. \begin{array}{l}
  13479. \gray{\LintOpAST} \\ \hline
  13480. \gray{\LvarASTRacket{}} \\ \hline
  13481. \gray{\LifASTRacket{}} \\ \hline
  13482. \gray{\LwhileASTRacket{}} \\ \hline
  13483. \gray{\LtupASTRacket{}} \\ \hline
  13484. \LfunASTRacket \\
  13485. \begin{array}{lcl}
  13486. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13487. \end{array}
  13488. \end{array}
  13489. \]
  13490. \fi}
  13491. {\if\edition\pythonEd
  13492. \[
  13493. \begin{array}{l}
  13494. \gray{\LintASTPython{}} \\ \hline
  13495. \gray{\LvarASTPython{}} \\ \hline
  13496. \gray{\LifASTPython{}} \\ \hline
  13497. \gray{\LwhileASTPython} \\ \hline
  13498. \gray{\LtupASTPython} \\ \hline
  13499. \LfunASTPython \\
  13500. \begin{array}{rcl}
  13501. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13502. \end{array}
  13503. \end{array}
  13504. \]
  13505. \fi}
  13506. \end{tcolorbox}
  13507. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13508. \label{fig:Lfun-syntax}
  13509. \end{figure}
  13510. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13511. representative example of defining and using functions in \LangFun{}.
  13512. We define a function \code{map} that applies some other function
  13513. \code{f} to both elements of a tuple and returns a new tuple
  13514. containing the results. We also define a function \code{inc}. The
  13515. program applies \code{map} to \code{inc} and
  13516. %
  13517. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13518. %
  13519. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13520. %
  13521. from which we return \code{42}.
  13522. \begin{figure}[tbp]
  13523. \begin{tcolorbox}[colback=white]
  13524. {\if\edition\racketEd
  13525. \begin{lstlisting}
  13526. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13527. : (Vector Integer Integer)
  13528. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13529. (define (inc [x : Integer]) : Integer
  13530. (+ x 1))
  13531. (vector-ref (map inc (vector 0 41)) 1)
  13532. \end{lstlisting}
  13533. \fi}
  13534. {\if\edition\pythonEd
  13535. \begin{lstlisting}
  13536. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13537. return f(v[0]), f(v[1])
  13538. def inc(x : int) -> int:
  13539. return x + 1
  13540. print( map(inc, (0, 41))[1] )
  13541. \end{lstlisting}
  13542. \fi}
  13543. \end{tcolorbox}
  13544. \caption{Example of using functions in \LangFun{}.}
  13545. \label{fig:Lfun-function-example}
  13546. \end{figure}
  13547. The definitional interpreter for \LangFun{} is shown in
  13548. figure~\ref{fig:interp-Lfun}. The case for the
  13549. %
  13550. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13551. %
  13552. AST is responsible for setting up the mutual recursion between the
  13553. top-level function definitions.
  13554. %
  13555. \racket{We use the classic back-patching
  13556. \index{subject}{back-patching} approach that uses mutable variables
  13557. and makes two passes over the function
  13558. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13559. top-level environment using a mutable cons cell for each function
  13560. definition. Note that the \code{lambda} value for each function is
  13561. incomplete; it does not yet include the environment. Once the
  13562. top-level environment has been constructed, we iterate over it and
  13563. update the \code{lambda} values to use the top-level environment.}
  13564. %
  13565. \python{We create a dictionary named \code{env} and fill it in
  13566. by mapping each function name to a new \code{Function} value,
  13567. each of which stores a reference to the \code{env}.
  13568. (We define the class \code{Function} for this purpose.)}
  13569. %
  13570. To interpret a function \racket{application}\python{call}, we match
  13571. the result of the function expression to obtain a function value. We
  13572. then extend the function's environment with the mapping of parameters to
  13573. argument values. Finally, we interpret the body of the function in
  13574. this extended environment.
  13575. \begin{figure}[tp]
  13576. \begin{tcolorbox}[colback=white]
  13577. {\if\edition\racketEd
  13578. \begin{lstlisting}
  13579. (define interp-Lfun-class
  13580. (class interp-Lvec-class
  13581. (super-new)
  13582. (define/override ((interp-exp env) e)
  13583. (define recur (interp-exp env))
  13584. (match e
  13585. [(Apply fun args)
  13586. (define fun-val (recur fun))
  13587. (define arg-vals (for/list ([e args]) (recur e)))
  13588. (match fun-val
  13589. [`(function (,xs ...) ,body ,fun-env)
  13590. (define params-args (for/list ([x xs] [arg arg-vals])
  13591. (cons x (box arg))))
  13592. (define new-env (append params-args fun-env))
  13593. ((interp-exp new-env) body)]
  13594. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  13595. [else ((super interp-exp env) e)]
  13596. ))
  13597. (define/public (interp-def d)
  13598. (match d
  13599. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13600. (cons f (box `(function ,xs ,body ())))]))
  13601. (define/override (interp-program p)
  13602. (match p
  13603. [(ProgramDefsExp info ds body)
  13604. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13605. (for/list ([f (in-dict-values top-level)])
  13606. (set-box! f (match (unbox f)
  13607. [`(function ,xs ,body ())
  13608. `(function ,xs ,body ,top-level)])))
  13609. ((interp-exp top-level) body))]))
  13610. ))
  13611. (define (interp-Lfun p)
  13612. (send (new interp-Lfun-class) interp-program p))
  13613. \end{lstlisting}
  13614. \fi}
  13615. {\if\edition\pythonEd
  13616. \begin{lstlisting}
  13617. class InterpLfun(InterpLtup):
  13618. def apply_fun(self, fun, args, e):
  13619. match fun:
  13620. case Function(name, xs, body, env):
  13621. new_env = env.copy().update(zip(xs, args))
  13622. return self.interp_stmts(body, new_env)
  13623. case _:
  13624. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13625. def interp_exp(self, e, env):
  13626. match e:
  13627. case Call(Name('input_int'), []):
  13628. return super().interp_exp(e, env)
  13629. case Call(func, args):
  13630. f = self.interp_exp(func, env)
  13631. vs = [self.interp_exp(arg, env) for arg in args]
  13632. return self.apply_fun(f, vs, e)
  13633. case _:
  13634. return super().interp_exp(e, env)
  13635. def interp_stmts(self, ss, env):
  13636. if len(ss) == 0:
  13637. return
  13638. match ss[0]:
  13639. case Return(value):
  13640. return self.interp_exp(value, env)
  13641. case FunctionDef(name, params, bod, dl, returns, comment):
  13642. ps = [x for (x,t) in params]
  13643. env[name] = Function(name, ps, bod, env)
  13644. return self.interp_stmts(ss[1:], env)
  13645. case _:
  13646. return super().interp_stmts(ss, env)
  13647. def interp(self, p):
  13648. match p:
  13649. case Module(ss):
  13650. env = {}
  13651. self.interp_stmts(ss, env)
  13652. if 'main' in env.keys():
  13653. self.apply_fun(env['main'], [], None)
  13654. case _:
  13655. raise Exception('interp: unexpected ' + repr(p))
  13656. \end{lstlisting}
  13657. \fi}
  13658. \end{tcolorbox}
  13659. \caption{Interpreter for the \LangFun{} language.}
  13660. \label{fig:interp-Lfun}
  13661. \end{figure}
  13662. %\margincomment{TODO: explain type checker}
  13663. The type checker for \LangFun{} is shown in
  13664. figure~\ref{fig:type-check-Lfun}.
  13665. %
  13666. \python{(We omit the code that parses function parameters into the
  13667. simpler abstract syntax.)}
  13668. %
  13669. Similarly to the interpreter, the case for the
  13670. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13671. %
  13672. AST is responsible for setting up the mutual recursion between the
  13673. top-level function definitions. We begin by create a mapping
  13674. \code{env} from every function name to its type. We then type check
  13675. the program using this mapping.
  13676. %
  13677. In the case for function \racket{application}\python{call}, we match
  13678. the type of the function expression to a function type and check that
  13679. the types of the argument expressions are equal to the function's
  13680. parameter types. The type of the \racket{application}\python{call} as
  13681. a whole is the return type from the function type.
  13682. \begin{figure}[tp]
  13683. \begin{tcolorbox}[colback=white]
  13684. {\if\edition\racketEd
  13685. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13686. (define type-check-Lfun-class
  13687. (class type-check-Lvec-class
  13688. (super-new)
  13689. (inherit check-type-equal?)
  13690. (define/public (type-check-apply env e es)
  13691. (define-values (e^ ty) ((type-check-exp env) e))
  13692. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13693. ((type-check-exp env) e)))
  13694. (match ty
  13695. [`(,ty^* ... -> ,rt)
  13696. (for ([arg-ty ty*] [param-ty ty^*])
  13697. (check-type-equal? arg-ty param-ty (Apply e es)))
  13698. (values e^ e* rt)]))
  13699. (define/override (type-check-exp env)
  13700. (lambda (e)
  13701. (match e
  13702. [(FunRef f n)
  13703. (values (FunRef f n) (dict-ref env f))]
  13704. [(Apply e es)
  13705. (define-values (e^ es^ rt) (type-check-apply env e es))
  13706. (values (Apply e^ es^) rt)]
  13707. [(Call e es)
  13708. (define-values (e^ es^ rt) (type-check-apply env e es))
  13709. (values (Call e^ es^) rt)]
  13710. [else ((super type-check-exp env) e)])))
  13711. (define/public (type-check-def env)
  13712. (lambda (e)
  13713. (match e
  13714. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13715. (define new-env (append (map cons xs ps) env))
  13716. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13717. (check-type-equal? ty^ rt body)
  13718. (Def f p:t* rt info body^)])))
  13719. (define/public (fun-def-type d)
  13720. (match d
  13721. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13722. (define/override (type-check-program e)
  13723. (match e
  13724. [(ProgramDefsExp info ds body)
  13725. (define env (for/list ([d ds])
  13726. (cons (Def-name d) (fun-def-type d))))
  13727. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13728. (define-values (body^ ty) ((type-check-exp env) body))
  13729. (check-type-equal? ty 'Integer body)
  13730. (ProgramDefsExp info ds^ body^)]))))
  13731. (define (type-check-Lfun p)
  13732. (send (new type-check-Lfun-class) type-check-program p))
  13733. \end{lstlisting}
  13734. \fi}
  13735. {\if\edition\pythonEd
  13736. \begin{lstlisting}
  13737. class TypeCheckLfun(TypeCheckLtup):
  13738. def type_check_exp(self, e, env):
  13739. match e:
  13740. case Call(Name('input_int'), []):
  13741. return super().type_check_exp(e, env)
  13742. case Call(func, args):
  13743. func_t = self.type_check_exp(func, env)
  13744. args_t = [self.type_check_exp(arg, env) for arg in args]
  13745. match func_t:
  13746. case FunctionType(params_t, return_t):
  13747. for (arg_t, param_t) in zip(args_t, params_t):
  13748. check_type_equal(param_t, arg_t, e)
  13749. return return_t
  13750. case _:
  13751. raise Exception('type_check_exp: in call, unexpected ' +
  13752. repr(func_t))
  13753. case _:
  13754. return super().type_check_exp(e, env)
  13755. def type_check_stmts(self, ss, env):
  13756. if len(ss) == 0:
  13757. return
  13758. match ss[0]:
  13759. case FunctionDef(name, params, body, dl, returns, comment):
  13760. new_env = env.copy().update(params)
  13761. rt = self.type_check_stmts(body, new_env)
  13762. check_type_equal(returns, rt, ss[0])
  13763. return self.type_check_stmts(ss[1:], env)
  13764. case Return(value):
  13765. return self.type_check_exp(value, env)
  13766. case _:
  13767. return super().type_check_stmts(ss, env)
  13768. def type_check(self, p):
  13769. match p:
  13770. case Module(body):
  13771. env = {}
  13772. for s in body:
  13773. match s:
  13774. case FunctionDef(name, params, bod, dl, returns, comment):
  13775. if name in env:
  13776. raise Exception('type_check: function ' +
  13777. repr(name) + ' defined twice')
  13778. params_t = [t for (x,t) in params]
  13779. env[name] = FunctionType(params_t, returns)
  13780. self.type_check_stmts(body, env)
  13781. case _:
  13782. raise Exception('type_check: unexpected ' + repr(p))
  13783. \end{lstlisting}
  13784. \fi}
  13785. \end{tcolorbox}
  13786. \caption{Type checker for the \LangFun{} language.}
  13787. \label{fig:type-check-Lfun}
  13788. \end{figure}
  13789. \clearpage
  13790. \section{Functions in x86}
  13791. \label{sec:fun-x86}
  13792. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13793. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13794. %% \margincomment{\tiny Talk about the return address on the
  13795. %% stack and what callq and retq does.\\ --Jeremy }
  13796. The x86 architecture provides a few features to support the
  13797. implementation of functions. We have already seen that there are
  13798. labels in x86 so that one can refer to the location of an instruction,
  13799. as is needed for jump instructions. Labels can also be used to mark
  13800. the beginning of the instructions for a function. Going further, we
  13801. can obtain the address of a label by using the \key{leaq}
  13802. instruction. For example, the following puts the address of the
  13803. \code{inc} label into the \code{rbx} register:
  13804. \begin{lstlisting}
  13805. leaq inc(%rip), %rbx
  13806. \end{lstlisting}
  13807. Recall from section~\ref{sec:select-instructions-gc} that
  13808. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13809. addressing.
  13810. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13811. to functions whose locations were given by a label, such as
  13812. \code{read\_int}. To support function calls in this chapter we instead
  13813. jump to functions whose location are given by an address in
  13814. a register; that is, we use \emph{indirect function calls}. The
  13815. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13816. before the register name.\index{subject}{indirect function call}
  13817. \begin{lstlisting}
  13818. callq *%rbx
  13819. \end{lstlisting}
  13820. \subsection{Calling Conventions}
  13821. \label{sec:calling-conventions-fun}
  13822. \index{subject}{calling conventions}
  13823. The \code{callq} instruction provides partial support for implementing
  13824. functions: it pushes the return address on the stack and it jumps to
  13825. the target. However, \code{callq} does not handle
  13826. \begin{enumerate}
  13827. \item parameter passing,
  13828. \item pushing frames on the procedure call stack and popping them off,
  13829. or
  13830. \item determining how registers are shared by different functions.
  13831. \end{enumerate}
  13832. Regarding parameter passing, recall that the x86-64 calling
  13833. convention for Unix-based system uses the following six registers to
  13834. pass arguments to a function, in the given order.
  13835. \begin{lstlisting}
  13836. rdi rsi rdx rcx r8 r9
  13837. \end{lstlisting}
  13838. If there are more than six arguments, then the calling convention
  13839. mandates using space on the frame of the caller for the rest of the
  13840. arguments. However, to ease the implementation of efficient tail calls
  13841. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13842. arguments.
  13843. %
  13844. The return value of the function is stored in register \code{rax}.
  13845. \index{subject}{prelude}\index{subject}{conclusion}
  13846. Regarding frames \index{subject}{frame} and the procedure call stack,
  13847. \index{subject}{procedure call stack} recall from
  13848. section~\ref{sec:x86} that the stack grows down and each function call
  13849. uses a chunk of space on the stack called a frame. The caller sets the
  13850. stack pointer, register \code{rsp}, to the last data item in its
  13851. frame. The callee must not change anything in the caller's frame, that
  13852. is, anything that is at or above the stack pointer. The callee is free
  13853. to use locations that are below the stack pointer.
  13854. Recall that we store variables of tuple type on the root stack. So,
  13855. the prelude of a function needs to move the root stack pointer
  13856. \code{r15} up according to the number of variables of tuple type and
  13857. the conclusion needs to move the root stack pointer back down. Also,
  13858. the prelude must initialize to \code{0} this frame's slots in the root
  13859. stack to signal to the garbage collector that those slots do not yet
  13860. contain a valid pointer. Otherwise the garbage collector will
  13861. interpret the garbage bits in those slots as memory addresses and try
  13862. to traverse them, causing serious mayhem!
  13863. Regarding the sharing of registers between different functions, recall
  13864. from section~\ref{sec:calling-conventions} that the registers are
  13865. divided into two groups, the caller-saved registers and the
  13866. callee-saved registers. The caller should assume that all the
  13867. caller-saved registers are overwritten with arbitrary values by the
  13868. callee. For that reason we recommend in
  13869. section~\ref{sec:calling-conventions} that variables that are live
  13870. during a function call should not be assigned to caller-saved
  13871. registers.
  13872. On the flip side, if the callee wants to use a callee-saved register,
  13873. the callee must save the contents of those registers on their stack
  13874. frame and then put them back prior to returning to the caller. For
  13875. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13876. the register allocator assigns a variable to a callee-saved register,
  13877. then the prelude of the \code{main} function must save that register
  13878. to the stack and the conclusion of \code{main} must restore it. This
  13879. recommendation now generalizes to all functions.
  13880. Recall that the base pointer, register \code{rbp}, is used as a
  13881. point of reference within a frame, so that each local variable can be
  13882. accessed at a fixed offset from the base pointer
  13883. (section~\ref{sec:x86}).
  13884. %
  13885. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13886. and callee frames.
  13887. \begin{figure}[tbp]
  13888. \centering
  13889. \begin{tcolorbox}[colback=white]
  13890. \begin{tabular}{r|r|l|l} \hline
  13891. Caller View & Callee View & Contents & Frame \\ \hline
  13892. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13893. 0(\key{\%rbp}) & & old \key{rbp} \\
  13894. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13895. \ldots & & \ldots \\
  13896. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13897. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13898. \ldots & & \ldots \\
  13899. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13900. %% & & \\
  13901. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13902. %% & \ldots & \ldots \\
  13903. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13904. \hline
  13905. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13906. & 0(\key{\%rbp}) & old \key{rbp} \\
  13907. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13908. & \ldots & \ldots \\
  13909. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13910. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13911. & \ldots & \ldots \\
  13912. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13913. \end{tabular}
  13914. \end{tcolorbox}
  13915. \caption{Memory layout of caller and callee frames.}
  13916. \label{fig:call-frames}
  13917. \end{figure}
  13918. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13919. %% local variables and for storing the values of callee-saved registers
  13920. %% (we shall refer to all of these collectively as ``locals''), and that
  13921. %% at the beginning of a function we move the stack pointer \code{rsp}
  13922. %% down to make room for them.
  13923. %% We recommend storing the local variables
  13924. %% first and then the callee-saved registers, so that the local variables
  13925. %% can be accessed using \code{rbp} the same as before the addition of
  13926. %% functions.
  13927. %% To make additional room for passing arguments, we shall
  13928. %% move the stack pointer even further down. We count how many stack
  13929. %% arguments are needed for each function call that occurs inside the
  13930. %% body of the function and find their maximum. Adding this number to the
  13931. %% number of locals gives us how much the \code{rsp} should be moved at
  13932. %% the beginning of the function. In preparation for a function call, we
  13933. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13934. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13935. %% so on.
  13936. %% Upon calling the function, the stack arguments are retrieved by the
  13937. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13938. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13939. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13940. %% the layout of the caller and callee frames. Notice how important it is
  13941. %% that we correctly compute the maximum number of arguments needed for
  13942. %% function calls; if that number is too small then the arguments and
  13943. %% local variables will smash into each other!
  13944. \subsection{Efficient Tail Calls}
  13945. \label{sec:tail-call}
  13946. In general, the amount of stack space used by a program is determined
  13947. by the longest chain of nested function calls. That is, if function
  13948. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13949. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13950. large if functions are recursive. However, in some cases we can
  13951. arrange to use only a constant amount of space for a long chain of
  13952. nested function calls.
  13953. A \emph{tail call}\index{subject}{tail call} is a function call that
  13954. happens as the last action in a function body. For example, in the
  13955. following program, the recursive call to \code{tail\_sum} is a tail
  13956. call:
  13957. \begin{center}
  13958. {\if\edition\racketEd
  13959. \begin{lstlisting}
  13960. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13961. (if (eq? n 0)
  13962. r
  13963. (tail_sum (- n 1) (+ n r))))
  13964. (+ (tail_sum 3 0) 36)
  13965. \end{lstlisting}
  13966. \fi}
  13967. {\if\edition\pythonEd
  13968. \begin{lstlisting}
  13969. def tail_sum(n : int, r : int) -> int:
  13970. if n == 0:
  13971. return r
  13972. else:
  13973. return tail_sum(n - 1, n + r)
  13974. print( tail_sum(3, 0) + 36)
  13975. \end{lstlisting}
  13976. \fi}
  13977. \end{center}
  13978. At a tail call, the frame of the caller is no longer needed, so we can
  13979. pop the caller's frame before making the tail call. With this
  13980. approach, a recursive function that makes only tail calls ends up
  13981. using a constant amount of stack space. Functional languages like
  13982. Racket rely heavily on recursive functions, so the definition of
  13983. Racket \emph{requires} that all tail calls be optimized in this way.
  13984. \index{subject}{frame}
  13985. Some care is needed with regard to argument passing in tail calls. As
  13986. mentioned, for arguments beyond the sixth, the convention is to use
  13987. space in the caller's frame for passing arguments. However, for a
  13988. tail call we pop the caller's frame and can no longer use it. An
  13989. alternative is to use space in the callee's frame for passing
  13990. arguments. However, this option is also problematic because the caller
  13991. and callee's frames overlap in memory. As we begin to copy the
  13992. arguments from their sources in the caller's frame, the target
  13993. locations in the callee's frame might collide with the sources for
  13994. later arguments! We solve this problem by using the heap instead of
  13995. the stack for passing more than six arguments
  13996. (section~\ref{sec:limit-functions-r4}).
  13997. As mentioned, for a tail call we pop the caller's frame prior to
  13998. making the tail call. The instructions for popping a frame are the
  13999. instructions that we usually place in the conclusion of a
  14000. function. Thus, we also need to place such code immediately before
  14001. each tail call. These instructions include restoring the callee-saved
  14002. registers, so it is fortunate that the argument passing registers are
  14003. all caller-saved registers.
  14004. One note remains regarding which instruction to use to make the tail
  14005. call. When the callee is finished, it should not return to the current
  14006. function but instead return to the function that called the current
  14007. one. Thus, the return address that is already on the stack is the
  14008. right one, and we should not use \key{callq} to make the tail call
  14009. because that would overwrite the return address. Instead we simply use
  14010. the \key{jmp} instruction. As with the indirect function call, we write
  14011. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14012. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14013. jump target because the conclusion can overwrite just about everything
  14014. else.
  14015. \begin{lstlisting}
  14016. jmp *%rax
  14017. \end{lstlisting}
  14018. \section{Shrink \LangFun{}}
  14019. \label{sec:shrink-r4}
  14020. The \code{shrink} pass performs a minor modification to ease the
  14021. later passes. This pass introduces an explicit \code{main} function
  14022. that gobbles up all the top-level statements of the module.
  14023. %
  14024. \racket{It also changes the top \code{ProgramDefsExp} form to
  14025. \code{ProgramDefs}.}
  14026. {\if\edition\racketEd
  14027. \begin{lstlisting}
  14028. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14029. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14030. \end{lstlisting}
  14031. where $\itm{mainDef}$ is
  14032. \begin{lstlisting}
  14033. (Def 'main '() 'Integer '() |$\Exp'$|)
  14034. \end{lstlisting}
  14035. \fi}
  14036. {\if\edition\pythonEd
  14037. \begin{lstlisting}
  14038. Module(|$\Def\ldots\Stmt\ldots$|)
  14039. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14040. \end{lstlisting}
  14041. where $\itm{mainDef}$ is
  14042. \begin{lstlisting}
  14043. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14044. \end{lstlisting}
  14045. \fi}
  14046. \section{Reveal Functions and the \LangFunRef{} language}
  14047. \label{sec:reveal-functions-r4}
  14048. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14049. in that it conflates the use of function names and local
  14050. variables. This is a problem because we need to compile the use of a
  14051. function name differently from the use of a local variable. In
  14052. particular, we use \code{leaq} to convert the function name (a label
  14053. in x86) to an address in a register. Thus, we create a new pass that
  14054. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14055. $n$ is the arity of the function.\python{\footnote{The arity is not
  14056. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14057. This pass is named \code{reveal\_functions} and the output language
  14058. is \LangFunRef{}.
  14059. %is defined in figure~\ref{fig:f1-syntax}.
  14060. %% The concrete syntax for a
  14061. %% function reference is $\CFUNREF{f}$.
  14062. %% \begin{figure}[tp]
  14063. %% \centering
  14064. %% \fbox{
  14065. %% \begin{minipage}{0.96\textwidth}
  14066. %% {\if\edition\racketEd
  14067. %% \[
  14068. %% \begin{array}{lcl}
  14069. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14070. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14071. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14072. %% \end{array}
  14073. %% \]
  14074. %% \fi}
  14075. %% {\if\edition\pythonEd
  14076. %% \[
  14077. %% \begin{array}{lcl}
  14078. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14079. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14080. %% \end{array}
  14081. %% \]
  14082. %% \fi}
  14083. %% \end{minipage}
  14084. %% }
  14085. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14086. %% (figure~\ref{fig:Lfun-syntax}).}
  14087. %% \label{fig:f1-syntax}
  14088. %% \end{figure}
  14089. %% Distinguishing between calls in tail position and non-tail position
  14090. %% requires the pass to have some notion of context. We recommend using
  14091. %% two mutually recursive functions, one for processing expressions in
  14092. %% tail position and another for the rest.
  14093. \racket{Placing this pass after \code{uniquify} will make sure that
  14094. there are no local variables and functions that share the same
  14095. name.}
  14096. %
  14097. The \code{reveal\_functions} pass should come before the
  14098. \code{remove\_complex\_operands} pass because function references
  14099. should be categorized as complex expressions.
  14100. \section{Limit Functions}
  14101. \label{sec:limit-functions-r4}
  14102. Recall that we wish to limit the number of function parameters to six
  14103. so that we do not need to use the stack for argument passing, which
  14104. makes it easier to implement efficient tail calls. However, because
  14105. the input language \LangFun{} supports arbitrary numbers of function
  14106. arguments, we have some work to do! The \code{limit\_functions} pass
  14107. transforms functions and function calls that involve more than six
  14108. arguments to pass the first five arguments as usual, but it packs the
  14109. rest of the arguments into a tuple and passes it as the sixth
  14110. argument.\footnote{The implementation this pass can be postponed to
  14111. last because you can test the rest of the passes on functions with
  14112. six or fewer parameters.}
  14113. Each function definition with seven or more parameters is transformed as
  14114. follows.
  14115. {\if\edition\racketEd
  14116. \begin{lstlisting}
  14117. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14118. |$\Rightarrow$|
  14119. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14120. \end{lstlisting}
  14121. \fi}
  14122. {\if\edition\pythonEd
  14123. \begin{lstlisting}
  14124. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14125. |$\Rightarrow$|
  14126. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14127. |$T_r$|, None, |$\itm{body}'$|, None)
  14128. \end{lstlisting}
  14129. \fi}
  14130. %
  14131. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14132. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14133. the $k$th element of the tuple, where $k = i - 6$.
  14134. %
  14135. {\if\edition\racketEd
  14136. \begin{lstlisting}
  14137. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14138. \end{lstlisting}
  14139. \fi}
  14140. {\if\edition\pythonEd
  14141. \begin{lstlisting}
  14142. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14143. \end{lstlisting}
  14144. \fi}
  14145. For function calls with too many arguments, the \code{limit\_functions}
  14146. pass transforms them in the following way:
  14147. \begin{tabular}{lll}
  14148. \begin{minipage}{0.3\textwidth}
  14149. {\if\edition\racketEd
  14150. \begin{lstlisting}
  14151. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14152. \end{lstlisting}
  14153. \fi}
  14154. {\if\edition\pythonEd
  14155. \begin{lstlisting}
  14156. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14157. \end{lstlisting}
  14158. \fi}
  14159. \end{minipage}
  14160. &
  14161. $\Rightarrow$
  14162. &
  14163. \begin{minipage}{0.5\textwidth}
  14164. {\if\edition\racketEd
  14165. \begin{lstlisting}
  14166. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14167. \end{lstlisting}
  14168. \fi}
  14169. {\if\edition\pythonEd
  14170. \begin{lstlisting}
  14171. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14172. \end{lstlisting}
  14173. \fi}
  14174. \end{minipage}
  14175. \end{tabular}
  14176. \section{Remove Complex Operands}
  14177. \label{sec:rco-r4}
  14178. The primary decisions to make for this pass are whether to classify
  14179. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14180. atomic or complex expressions. Recall that an atomic expression will
  14181. end up as an immediate argument of an x86 instruction. Function
  14182. application will be translated to a sequence of instructions, so
  14183. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14184. complex expression. On the other hand, the arguments of
  14185. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14186. expressions.
  14187. %
  14188. Regarding \code{FunRef}, as discussed previously, the function label
  14189. needs to be converted to an address using the \code{leaq}
  14190. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14191. needs to be classified as a complex expression so that we generate an
  14192. assignment statement with a left-hand side that can serve as the
  14193. target of the \code{leaq}.
  14194. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14195. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14196. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14197. and augments programs to include a list of function definitions.
  14198. %
  14199. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14200. \newcommand{\LfunMonadASTRacket}{
  14201. \begin{array}{lcl}
  14202. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14203. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14204. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14205. \end{array}
  14206. }
  14207. \newcommand{\LfunMonadASTPython}{
  14208. \begin{array}{lcl}
  14209. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14210. \MID \key{TupleType}\LS\Type^+\RS\\
  14211. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14212. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14213. \Stmt &::=& \RETURN{\Exp} \\
  14214. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14215. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14216. \end{array}
  14217. }
  14218. \begin{figure}[tp]
  14219. \centering
  14220. \begin{tcolorbox}[colback=white]
  14221. \small
  14222. {\if\edition\racketEd
  14223. \[
  14224. \begin{array}{l}
  14225. \gray{\LvarMonadASTRacket} \\ \hline
  14226. \gray{\LifMonadASTRacket} \\ \hline
  14227. \gray{\LwhileMonadASTRacket} \\ \hline
  14228. \gray{\LtupMonadASTRacket} \\ \hline
  14229. \LfunMonadASTRacket \\
  14230. \begin{array}{rcl}
  14231. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14232. \end{array}
  14233. \end{array}
  14234. \]
  14235. \fi}
  14236. {\if\edition\pythonEd
  14237. \[
  14238. \begin{array}{l}
  14239. \gray{\LvarMonadASTPython} \\ \hline
  14240. \gray{\LifMonadASTPython} \\ \hline
  14241. \gray{\LwhileMonadASTPython} \\ \hline
  14242. \gray{\LtupMonadASTPython} \\ \hline
  14243. \LfunMonadASTPython \\
  14244. \begin{array}{rcl}
  14245. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14246. \end{array}
  14247. \end{array}
  14248. \]
  14249. \fi}
  14250. \end{tcolorbox}
  14251. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14252. \label{fig:Lfun-anf-syntax}
  14253. \end{figure}
  14254. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14255. %% \LangFunANF{} of this pass.
  14256. %% \begin{figure}[tp]
  14257. %% \centering
  14258. %% \fbox{
  14259. %% \begin{minipage}{0.96\textwidth}
  14260. %% \small
  14261. %% \[
  14262. %% \begin{array}{rcl}
  14263. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14264. %% \MID \VOID{} } \\
  14265. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14266. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14267. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14268. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14269. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14270. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14271. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14272. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14273. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14274. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14275. %% \end{array}
  14276. %% \]
  14277. %% \end{minipage}
  14278. %% }
  14279. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14280. %% \label{fig:Lfun-anf-syntax}
  14281. %% \end{figure}
  14282. \section{Explicate Control and the \LangCFun{} language}
  14283. \label{sec:explicate-control-r4}
  14284. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14285. output of \code{explicate\_control}.
  14286. %
  14287. %% \racket{(The concrete syntax is given in
  14288. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14289. %
  14290. The auxiliary functions for assignment\racket{ and tail contexts} should
  14291. be updated with cases for
  14292. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14293. function for predicate context should be updated for
  14294. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14295. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14296. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14297. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14298. auxiliary function for processing function definitions. This code is
  14299. similar to the case for \code{Program} in \LangVec{}. The top-level
  14300. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14301. form of \LangFun{} can then apply this new function to all the
  14302. function definitions.
  14303. {\if\edition\pythonEd
  14304. The translation of \code{Return} statements requires a new auxiliary
  14305. function to handle expressions in tail context, called
  14306. \code{explicate\_tail}. The function should take an expression and the
  14307. dictionary of basic blocks and produce a list of statements in the
  14308. \LangCFun{} language. The \code{explicate\_tail} function should
  14309. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14310. and a default case for other kinds of expressions. The default case
  14311. should produce a \code{Return} statement. The case for \code{Call}
  14312. should change it into \code{TailCall}. The other cases should
  14313. recursively process their subexpressions and statements, choosing the
  14314. appropriate explicate functions for the various contexts.
  14315. \fi}
  14316. \newcommand{\CfunASTRacket}{
  14317. \begin{array}{lcl}
  14318. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14319. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14320. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14321. \end{array}
  14322. }
  14323. \newcommand{\CfunASTPython}{
  14324. \begin{array}{lcl}
  14325. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14326. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14327. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14328. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14329. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14330. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14331. \end{array}
  14332. }
  14333. \begin{figure}[tp]
  14334. \begin{tcolorbox}[colback=white]
  14335. \small
  14336. {\if\edition\racketEd
  14337. \[
  14338. \begin{array}{l}
  14339. \gray{\CvarASTRacket} \\ \hline
  14340. \gray{\CifASTRacket} \\ \hline
  14341. \gray{\CloopASTRacket} \\ \hline
  14342. \gray{\CtupASTRacket} \\ \hline
  14343. \CfunASTRacket \\
  14344. \begin{array}{lcl}
  14345. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14346. \end{array}
  14347. \end{array}
  14348. \]
  14349. \fi}
  14350. {\if\edition\pythonEd
  14351. \[
  14352. \begin{array}{l}
  14353. \gray{\CifASTPython} \\ \hline
  14354. \gray{\CtupASTPython} \\ \hline
  14355. \CfunASTPython \\
  14356. \begin{array}{lcl}
  14357. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14358. \end{array}
  14359. \end{array}
  14360. \]
  14361. \fi}
  14362. \end{tcolorbox}
  14363. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14364. \label{fig:c3-syntax}
  14365. \end{figure}
  14366. \clearpage
  14367. \section{Select Instructions and the \LangXIndCall{} Language}
  14368. \label{sec:select-r4}
  14369. \index{subject}{instruction selection}
  14370. The output of select instructions is a program in the \LangXIndCall{}
  14371. language; the definition of its concrete syntax is shown in
  14372. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14373. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14374. directive on the labels of function definitions to make sure the
  14375. bottom three bits are zero, which we put to use in
  14376. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14377. this section. \index{subject}{x86}
  14378. \newcommand{\GrammarXIndCall}{
  14379. \begin{array}{lcl}
  14380. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14381. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14382. \Block &::= & \Instr^{+} \\
  14383. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14384. \end{array}
  14385. }
  14386. \newcommand{\ASTXIndCallRacket}{
  14387. \begin{array}{lcl}
  14388. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14389. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14390. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14391. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14392. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14393. \end{array}
  14394. }
  14395. \begin{figure}[tp]
  14396. \begin{tcolorbox}[colback=white]
  14397. \small
  14398. \[
  14399. \begin{array}{l}
  14400. \gray{\GrammarXInt} \\ \hline
  14401. \gray{\GrammarXIf} \\ \hline
  14402. \gray{\GrammarXGlobal} \\ \hline
  14403. \GrammarXIndCall \\
  14404. \begin{array}{lcl}
  14405. \LangXIndCallM{} &::= & \Def^{*}
  14406. \end{array}
  14407. \end{array}
  14408. \]
  14409. \end{tcolorbox}
  14410. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14411. \label{fig:x86-3-concrete}
  14412. \end{figure}
  14413. \begin{figure}[tp]
  14414. \begin{tcolorbox}[colback=white]
  14415. \small
  14416. {\if\edition\racketEd
  14417. \[\arraycolsep=3pt
  14418. \begin{array}{l}
  14419. \gray{\ASTXIntRacket} \\ \hline
  14420. \gray{\ASTXIfRacket} \\ \hline
  14421. \gray{\ASTXGlobalRacket} \\ \hline
  14422. \ASTXIndCallRacket \\
  14423. \begin{array}{lcl}
  14424. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14425. \end{array}
  14426. \end{array}
  14427. \]
  14428. \fi}
  14429. {\if\edition\pythonEd
  14430. \[
  14431. \begin{array}{lcl}
  14432. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14433. \MID \BYTEREG{\Reg} } \\
  14434. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14435. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14436. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14437. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14438. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14439. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14440. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14441. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14442. \end{array}
  14443. \]
  14444. \fi}
  14445. \end{tcolorbox}
  14446. \caption{The abstract syntax of \LangXIndCall{} (extends
  14447. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14448. \label{fig:x86-3}
  14449. \end{figure}
  14450. An assignment of a function reference to a variable becomes a
  14451. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14452. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14453. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14454. node, whose concrete syntax is instruction-pointer-relative
  14455. addressing.
  14456. \begin{center}
  14457. \begin{tabular}{lcl}
  14458. \begin{minipage}{0.35\textwidth}
  14459. {\if\edition\racketEd
  14460. \begin{lstlisting}
  14461. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14462. \end{lstlisting}
  14463. \fi}
  14464. {\if\edition\pythonEd
  14465. \begin{lstlisting}
  14466. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14467. \end{lstlisting}
  14468. \fi}
  14469. \end{minipage}
  14470. &
  14471. $\Rightarrow$\qquad\qquad
  14472. &
  14473. \begin{minipage}{0.3\textwidth}
  14474. \begin{lstlisting}
  14475. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14476. \end{lstlisting}
  14477. \end{minipage}
  14478. \end{tabular}
  14479. \end{center}
  14480. Regarding function definitions, we need to remove the parameters and
  14481. instead perform parameter passing using the conventions discussed in
  14482. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14483. registers. We recommend turning the parameters into local variables
  14484. and generating instructions at the beginning of the function to move
  14485. from the argument-passing registers
  14486. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14487. {\if\edition\racketEd
  14488. \begin{lstlisting}
  14489. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14490. |$\Rightarrow$|
  14491. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14492. \end{lstlisting}
  14493. \fi}
  14494. {\if\edition\pythonEd
  14495. \begin{lstlisting}
  14496. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14497. |$\Rightarrow$|
  14498. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14499. \end{lstlisting}
  14500. \fi}
  14501. The basic blocks $B'$ are the same as $B$ except that the
  14502. \code{start} block is modified to add the instructions for moving from
  14503. the argument registers to the parameter variables. So the \code{start}
  14504. block of $B$ shown on the left of the following is changed to the code
  14505. on the right:
  14506. \begin{center}
  14507. \begin{minipage}{0.3\textwidth}
  14508. \begin{lstlisting}
  14509. start:
  14510. |$\itm{instr}_1$|
  14511. |$\cdots$|
  14512. |$\itm{instr}_n$|
  14513. \end{lstlisting}
  14514. \end{minipage}
  14515. $\Rightarrow$
  14516. \begin{minipage}{0.3\textwidth}
  14517. \begin{lstlisting}
  14518. |$f$|start:
  14519. movq %rdi, |$x_1$|
  14520. movq %rsi, |$x_2$|
  14521. |$\cdots$|
  14522. |$\itm{instr}_1$|
  14523. |$\cdots$|
  14524. |$\itm{instr}_n$|
  14525. \end{lstlisting}
  14526. \end{minipage}
  14527. \end{center}
  14528. Recall that we use the label \code{start} for the initial block of a
  14529. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14530. the conclusion of the program with \code{conclusion}, so that
  14531. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14532. by a jump to \code{conclusion}. With the addition of function
  14533. definitions, there is a start block and conclusion for each function,
  14534. but their labels need to be unique. We recommend prepending the
  14535. function's name to \code{start} and \code{conclusion}, respectively,
  14536. to obtain unique labels.
  14537. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14538. number of parameters the function expects, but the parameters are no
  14539. longer in the syntax of function definitions. Instead, add an entry
  14540. to $\itm{info}$ that maps \code{num-params} to the number of
  14541. parameters to construct $\itm{info}'$.}
  14542. By changing the parameters to local variables, we are giving the
  14543. register allocator control over which registers or stack locations to
  14544. use for them. If you implement the move-biasing challenge
  14545. (section~\ref{sec:move-biasing}), the register allocator will try to
  14546. assign the parameter variables to the corresponding argument register,
  14547. in which case the \code{patch\_instructions} pass will remove the
  14548. \code{movq} instruction. This happens in the example translation given
  14549. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14550. the \code{add} function.
  14551. %
  14552. Also, note that the register allocator will perform liveness analysis
  14553. on this sequence of move instructions and build the interference
  14554. graph. So, for example, $x_1$ will be marked as interfering with
  14555. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14556. which is good because otherwise the first \code{movq} would overwrite
  14557. the argument in \code{rsi} that is needed for $x_2$.
  14558. Next, consider the compilation of function calls. In the mirror image
  14559. of the handling of parameters in function definitions, the arguments
  14560. are moved to the argument-passing registers. Note that the function
  14561. is not given as a label, but its address is produced by the argument
  14562. $\itm{arg}_0$. So, we translate the call into an indirect function
  14563. call. The return value from the function is stored in \code{rax}, so
  14564. it needs to be moved into the \itm{lhs}.
  14565. \begin{lstlisting}
  14566. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14567. |$\Rightarrow$|
  14568. movq |$\itm{arg}_1$|, %rdi
  14569. movq |$\itm{arg}_2$|, %rsi
  14570. |$\vdots$|
  14571. callq *|$\itm{arg}_0$|
  14572. movq %rax, |$\itm{lhs}$|
  14573. \end{lstlisting}
  14574. The \code{IndirectCallq} AST node includes an integer for the arity of
  14575. the function, that is, the number of parameters. That information is
  14576. useful in the \code{uncover\_live} pass for determining which
  14577. argument-passing registers are potentially read during the call.
  14578. For tail calls, the parameter passing is the same as non-tail calls:
  14579. generate instructions to move the arguments into the argument-passing
  14580. registers. After that we need to pop the frame from the procedure
  14581. call stack. However, we do not yet know how big the frame is; that
  14582. gets determined during register allocation. So, instead of generating
  14583. those instructions here, we invent a new instruction that means ``pop
  14584. the frame and then do an indirect jump,'' which we name
  14585. \code{TailJmp}. The abstract syntax for this instruction includes an
  14586. argument that specifies where to jump and an integer that represents
  14587. the arity of the function being called.
  14588. \section{Register Allocation}
  14589. \label{sec:register-allocation-r4}
  14590. The addition of functions requires some changes to all three aspects
  14591. of register allocation, which we discuss in the following subsections.
  14592. \subsection{Liveness Analysis}
  14593. \label{sec:liveness-analysis-r4}
  14594. \index{subject}{liveness analysis}
  14595. %% The rest of the passes need only minor modifications to handle the new
  14596. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14597. %% \code{leaq}.
  14598. The \code{IndirectCallq} instruction should be treated like
  14599. \code{Callq} regarding its written locations $W$, in that they should
  14600. include all the caller-saved registers. Recall that the reason for
  14601. that is to force variables that are live across a function call to be assigned to callee-saved
  14602. registers or to be spilled to the stack.
  14603. Regarding the set of read locations $R$, the arity field of
  14604. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14605. argument-passing registers should be considered as read by those
  14606. instructions. Also, the target field of \code{TailJmp} and
  14607. \code{IndirectCallq} should be included in the set of read locations
  14608. $R$.
  14609. \subsection{Build Interference Graph}
  14610. \label{sec:build-interference-r4}
  14611. With the addition of function definitions, we compute a separate interference
  14612. graph for each function (not just one for the whole program).
  14613. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14614. spill tuple-typed variables that are live during a call to
  14615. \code{collect}, the garbage collector. With the addition of functions
  14616. to our language, we need to revisit this issue. Functions that perform
  14617. allocation contain calls to the collector. Thus, we should not only
  14618. spill a tuple-typed variable when it is live during a call to
  14619. \code{collect}, but we should spill the variable if it is live during
  14620. call to any user-defined function. Thus, in the
  14621. \code{build\_interference} pass, we recommend adding interference
  14622. edges between call-live tuple-typed variables and the callee-saved
  14623. registers (in addition to the usual addition of edges between
  14624. call-live variables and the caller-saved registers).
  14625. \subsection{Allocate Registers}
  14626. The primary change to the \code{allocate\_registers} pass is adding an
  14627. auxiliary function for handling definitions (the \Def{} nonterminal
  14628. shown in figure~\ref{fig:x86-3}) with one case for function
  14629. definitions. The logic is the same as described in
  14630. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14631. allocation is performed many times, once for each function definition,
  14632. instead of just once for the whole program.
  14633. \section{Patch Instructions}
  14634. In \code{patch\_instructions}, you should deal with the x86
  14635. idiosyncrasy that the destination argument of \code{leaq} must be a
  14636. register. Additionally, you should ensure that the argument of
  14637. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14638. trample many other registers before the tail call, as explained in the
  14639. next section.
  14640. \section{Prelude and Conclusion}
  14641. Now that register allocation is complete, we can translate the
  14642. \code{TailJmp} into a sequence of instructions. A naive translation of
  14643. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14644. before the jump we need to pop the current frame to achieve efficient
  14645. tail calls. This sequence of instructions is the same as the code for
  14646. the conclusion of a function, except that the \code{retq} is replaced with
  14647. \code{jmp *$\itm{arg}$}.
  14648. Regarding function definitions, we generate a prelude and conclusion
  14649. for each one. This code is similar to the prelude and conclusion
  14650. generated for the \code{main} function presented in
  14651. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14652. carry out the following steps:
  14653. % TODO: .align the functions!
  14654. \begin{enumerate}
  14655. %% \item Start with \code{.global} and \code{.align} directives followed
  14656. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14657. %% example.)
  14658. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14659. pointer.
  14660. \item Push to the stack all the callee-saved registers that were
  14661. used for register allocation.
  14662. \item Move the stack pointer \code{rsp} down to make room for the
  14663. regular spills (aligned to 16 bytes).
  14664. \item Move the root stack pointer \code{r15} up by the size of the
  14665. root-stack frame for this function, which depends on the number of
  14666. spilled tuple-typed variables. \label{root-stack-init}
  14667. \item Initialize to zero all new entries in the root-stack frame.
  14668. \item Jump to the start block.
  14669. \end{enumerate}
  14670. The prelude of the \code{main} function has an additional task: call
  14671. the \code{initialize} function to set up the garbage collector, and
  14672. then move the value of the global \code{rootstack\_begin} in
  14673. \code{r15}. This initialization should happen before step
  14674. \ref{root-stack-init}, which depends on \code{r15}.
  14675. The conclusion of every function should do the following:
  14676. \begin{enumerate}
  14677. \item Move the stack pointer back up past the regular spills.
  14678. \item Restore the callee-saved registers by popping them from the
  14679. stack.
  14680. \item Move the root stack pointer back down by the size of the
  14681. root-stack frame for this function.
  14682. \item Restore \code{rbp} by popping it from the stack.
  14683. \item Return to the caller with the \code{retq} instruction.
  14684. \end{enumerate}
  14685. The output of this pass is \LangXIndCallFlat{}, which differs from
  14686. \LangXIndCall{} in that there is no longer an AST node for function
  14687. definitions. Instead, a program is just an association list of basic
  14688. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14689. \[
  14690. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14691. \]
  14692. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14693. compiling \LangFun{} to x86.
  14694. \begin{exercise}\normalfont\normalsize
  14695. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14696. Create eight new programs that use functions, including examples that
  14697. pass functions and return functions from other functions, recursive
  14698. functions, functions that create vectors, and functions that make tail
  14699. calls. Test your compiler on these new programs and all your
  14700. previously created test programs.
  14701. \end{exercise}
  14702. \begin{figure}[tbp]
  14703. \begin{tcolorbox}[colback=white]
  14704. {\if\edition\racketEd
  14705. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14706. \node (Lfun) at (0,2) {\large \LangFun{}};
  14707. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14708. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14709. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14710. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14711. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14712. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14713. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14714. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14715. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14716. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14717. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14718. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14719. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14720. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14721. \path[->,bend left=15] (Lfun) edge [above] node
  14722. {\ttfamily\footnotesize shrink} (Lfun-1);
  14723. \path[->,bend left=15] (Lfun-1) edge [above] node
  14724. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14725. \path[->,bend left=15] (Lfun-2) edge [above] node
  14726. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14727. \path[->,bend left=15] (F1-1) edge [left] node
  14728. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14729. \path[->,bend left=15] (F1-2) edge [below] node
  14730. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14731. \path[->,bend left=15] (F1-3) edge [below] node
  14732. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14733. \path[->,bend right=15] (F1-4) edge [above] node
  14734. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14735. \path[->,bend right=15] (F1-5) edge [right] node
  14736. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14737. \path[->,bend right=15] (C3-2) edge [right] node
  14738. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14739. \path[->,bend left=15] (x86-2) edge [right] node
  14740. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14741. \path[->,bend right=15] (x86-2-1) edge [below] node
  14742. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14743. \path[->,bend right=15] (x86-2-2) edge [right] node
  14744. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14745. \path[->,bend left=15] (x86-3) edge [above] node
  14746. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14747. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14748. \end{tikzpicture}
  14749. \fi}
  14750. {\if\edition\pythonEd
  14751. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14752. \node (Lfun) at (0,2) {\large \LangFun{}};
  14753. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14754. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14755. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14756. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14757. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14758. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14759. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14760. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14761. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14762. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14763. \path[->,bend left=15] (Lfun) edge [above] node
  14764. {\ttfamily\footnotesize shrink} (Lfun-2);
  14765. \path[->,bend left=15] (Lfun-2) edge [above] node
  14766. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14767. \path[->,bend left=15] (F1-1) edge [above] node
  14768. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14769. \path[->,bend left=15] (F1-2) edge [right] node
  14770. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14771. \path[->,bend right=15] (F1-4) edge [above] node
  14772. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14773. \path[->,bend right=15] (F1-5) edge [right] node
  14774. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14775. \path[->,bend left=15] (C3-2) edge [right] node
  14776. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14777. \path[->,bend right=15] (x86-2) edge [below] node
  14778. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14779. \path[->,bend left=15] (x86-3) edge [above] node
  14780. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14781. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14782. \end{tikzpicture}
  14783. \fi}
  14784. \end{tcolorbox}
  14785. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14786. \label{fig:Lfun-passes}
  14787. \end{figure}
  14788. \section{An Example Translation}
  14789. \label{sec:functions-example}
  14790. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14791. function in \LangFun{} to x86. The figure also includes the results of the
  14792. \code{explicate\_control} and \code{select\_instructions} passes.
  14793. \begin{figure}[htbp]
  14794. \begin{tcolorbox}[colback=white]
  14795. \begin{tabular}{ll}
  14796. \begin{minipage}{0.4\textwidth}
  14797. % s3_2.rkt
  14798. {\if\edition\racketEd
  14799. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14800. (define (add [x : Integer]
  14801. [y : Integer])
  14802. : Integer
  14803. (+ x y))
  14804. (add 40 2)
  14805. \end{lstlisting}
  14806. \fi}
  14807. {\if\edition\pythonEd
  14808. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14809. def add(x:int, y:int) -> int:
  14810. return x + y
  14811. print(add(40, 2))
  14812. \end{lstlisting}
  14813. \fi}
  14814. $\Downarrow$
  14815. {\if\edition\racketEd
  14816. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14817. (define (add86 [x87 : Integer]
  14818. [y88 : Integer])
  14819. : Integer
  14820. add86start:
  14821. return (+ x87 y88);
  14822. )
  14823. (define (main) : Integer ()
  14824. mainstart:
  14825. tmp89 = (fun-ref add86 2);
  14826. (tail-call tmp89 40 2)
  14827. )
  14828. \end{lstlisting}
  14829. \fi}
  14830. {\if\edition\pythonEd
  14831. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14832. def add(x:int, y:int) -> int:
  14833. addstart:
  14834. return x + y
  14835. def main() -> int:
  14836. mainstart:
  14837. fun.0 = add
  14838. tmp.1 = fun.0(40, 2)
  14839. print(tmp.1)
  14840. return 0
  14841. \end{lstlisting}
  14842. \fi}
  14843. \end{minipage}
  14844. &
  14845. $\Rightarrow$
  14846. \begin{minipage}{0.5\textwidth}
  14847. {\if\edition\racketEd
  14848. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14849. (define (add86) : Integer
  14850. add86start:
  14851. movq %rdi, x87
  14852. movq %rsi, y88
  14853. movq x87, %rax
  14854. addq y88, %rax
  14855. jmp inc1389conclusion
  14856. )
  14857. (define (main) : Integer
  14858. mainstart:
  14859. leaq (fun-ref add86 2), tmp89
  14860. movq $40, %rdi
  14861. movq $2, %rsi
  14862. tail-jmp tmp89
  14863. )
  14864. \end{lstlisting}
  14865. \fi}
  14866. {\if\edition\pythonEd
  14867. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14868. def add() -> int:
  14869. addstart:
  14870. movq %rdi, x
  14871. movq %rsi, y
  14872. movq x, %rax
  14873. addq y, %rax
  14874. jmp addconclusion
  14875. def main() -> int:
  14876. mainstart:
  14877. leaq add, fun.0
  14878. movq $40, %rdi
  14879. movq $2, %rsi
  14880. callq *fun.0
  14881. movq %rax, tmp.1
  14882. movq tmp.1, %rdi
  14883. callq print_int
  14884. movq $0, %rax
  14885. jmp mainconclusion
  14886. \end{lstlisting}
  14887. \fi}
  14888. $\Downarrow$
  14889. \end{minipage}
  14890. \end{tabular}
  14891. \begin{tabular}{ll}
  14892. \begin{minipage}{0.3\textwidth}
  14893. {\if\edition\racketEd
  14894. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14895. .globl add86
  14896. .align 8
  14897. add86:
  14898. pushq %rbp
  14899. movq %rsp, %rbp
  14900. jmp add86start
  14901. add86start:
  14902. movq %rdi, %rax
  14903. addq %rsi, %rax
  14904. jmp add86conclusion
  14905. add86conclusion:
  14906. popq %rbp
  14907. retq
  14908. \end{lstlisting}
  14909. \fi}
  14910. {\if\edition\pythonEd
  14911. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14912. .align 8
  14913. add:
  14914. pushq %rbp
  14915. movq %rsp, %rbp
  14916. subq $0, %rsp
  14917. jmp addstart
  14918. addstart:
  14919. movq %rdi, %rdx
  14920. movq %rsi, %rcx
  14921. movq %rdx, %rax
  14922. addq %rcx, %rax
  14923. jmp addconclusion
  14924. addconclusion:
  14925. subq $0, %r15
  14926. addq $0, %rsp
  14927. popq %rbp
  14928. retq
  14929. \end{lstlisting}
  14930. \fi}
  14931. \end{minipage}
  14932. &
  14933. \begin{minipage}{0.5\textwidth}
  14934. {\if\edition\racketEd
  14935. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14936. .globl main
  14937. .align 8
  14938. main:
  14939. pushq %rbp
  14940. movq %rsp, %rbp
  14941. movq $16384, %rdi
  14942. movq $16384, %rsi
  14943. callq initialize
  14944. movq rootstack_begin(%rip), %r15
  14945. jmp mainstart
  14946. mainstart:
  14947. leaq add86(%rip), %rcx
  14948. movq $40, %rdi
  14949. movq $2, %rsi
  14950. movq %rcx, %rax
  14951. popq %rbp
  14952. jmp *%rax
  14953. mainconclusion:
  14954. popq %rbp
  14955. retq
  14956. \end{lstlisting}
  14957. \fi}
  14958. {\if\edition\pythonEd
  14959. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14960. .globl main
  14961. .align 8
  14962. main:
  14963. pushq %rbp
  14964. movq %rsp, %rbp
  14965. subq $0, %rsp
  14966. movq $65536, %rdi
  14967. movq $65536, %rsi
  14968. callq initialize
  14969. movq rootstack_begin(%rip), %r15
  14970. jmp mainstart
  14971. mainstart:
  14972. leaq add(%rip), %rcx
  14973. movq $40, %rdi
  14974. movq $2, %rsi
  14975. callq *%rcx
  14976. movq %rax, %rcx
  14977. movq %rcx, %rdi
  14978. callq print_int
  14979. movq $0, %rax
  14980. jmp mainconclusion
  14981. mainconclusion:
  14982. subq $0, %r15
  14983. addq $0, %rsp
  14984. popq %rbp
  14985. retq
  14986. \end{lstlisting}
  14987. \fi}
  14988. \end{minipage}
  14989. \end{tabular}
  14990. \end{tcolorbox}
  14991. \caption{Example compilation of a simple function to x86.}
  14992. \label{fig:add-fun}
  14993. \end{figure}
  14994. % Challenge idea: inlining! (simple version)
  14995. % Further Reading
  14996. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14997. \chapter{Lexically Scoped Functions}
  14998. \label{ch:Llambda}
  14999. \index{subject}{lambda}
  15000. \index{subject}{lexical scoping}
  15001. \setcounter{footnote}{0}
  15002. This chapter studies lexically scoped functions. Lexical scoping means
  15003. that a function's body may refer to variables whose binding site is
  15004. outside of the function, in an enclosing scope.
  15005. %
  15006. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15007. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  15008. creating lexically scoped functions. The body of the \key{lambda}
  15009. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  15010. binding sites for \code{x} and \code{y} are outside of the
  15011. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  15012. \key{let}}\python{a local variable of function \code{f}}, and
  15013. \code{x} is a parameter of function \code{f}. Note that function
  15014. \code{f} returns the \key{lambda} as its result value. The main
  15015. expression of the program includes two calls to \code{f} with
  15016. different arguments for \code{x}: first \code{5} and then \code{3}. The
  15017. functions returned from \code{f} are bound to variables \code{g} and
  15018. \code{h}. Even though these two functions were created by the same
  15019. \code{lambda}, they are really different functions because they use
  15020. different values for \code{x}. Applying \code{g} to \code{11} produces
  15021. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  15022. so the result of the program is \code{42}.
  15023. \begin{figure}[btp]
  15024. \begin{tcolorbox}[colback=white]
  15025. {\if\edition\racketEd
  15026. % lambda_test_21.rkt
  15027. \begin{lstlisting}
  15028. (define (f [x : Integer]) : (Integer -> Integer)
  15029. (let ([y 4])
  15030. (lambda: ([z : Integer]) : Integer
  15031. (+ x (+ y z)))))
  15032. (let ([g (f 5)])
  15033. (let ([h (f 3)])
  15034. (+ (g 11) (h 15))))
  15035. \end{lstlisting}
  15036. \fi}
  15037. {\if\edition\pythonEd
  15038. \begin{lstlisting}
  15039. def f(x : int) -> Callable[[int], int]:
  15040. y = 4
  15041. return lambda z: x + y + z
  15042. g = f(5)
  15043. h = f(3)
  15044. print( g(11) + h(15) )
  15045. \end{lstlisting}
  15046. \fi}
  15047. \end{tcolorbox}
  15048. \caption{Example of a lexically scoped function.}
  15049. \label{fig:lexical-scoping}
  15050. \end{figure}
  15051. The approach that we take for implementing lexically scoped functions
  15052. is to compile them into top-level function definitions, translating
  15053. from \LangLam{} into \LangFun{}. However, the compiler must give
  15054. special treatment to variable occurrences such as \code{x} and
  15055. \code{y} in the body of the \code{lambda} shown in
  15056. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15057. may not refer to variables defined outside of it. To identify such
  15058. variable occurrences, we review the standard notion of free variable.
  15059. \begin{definition}\normalfont
  15060. A variable is \emph{free in expression} $e$ if the variable occurs
  15061. inside $e$ but does not have an enclosing definition that is also in
  15062. $e$.\index{subject}{free variable}
  15063. \end{definition}
  15064. For example, in the expression
  15065. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15066. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15067. only \code{x} and \code{y} are free in the following expression,
  15068. because \code{z} is defined by the \code{lambda}
  15069. {\if\edition\racketEd
  15070. \begin{lstlisting}
  15071. (lambda: ([z : Integer]) : Integer
  15072. (+ x (+ y z)))
  15073. \end{lstlisting}
  15074. \fi}
  15075. {\if\edition\pythonEd
  15076. \begin{lstlisting}
  15077. lambda z: x + y + z
  15078. \end{lstlisting}
  15079. \fi}
  15080. %
  15081. \noindent Thus the free variables of a \code{lambda} are the ones that
  15082. need special treatment. We need to transport at runtime the values
  15083. of those variables from the point where the \code{lambda} was created
  15084. to the point where the \code{lambda} is applied. An efficient solution
  15085. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15086. values of the free variables together with a function pointer into a
  15087. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15088. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15089. closure}
  15090. %
  15091. By design, we have all the ingredients to make closures:
  15092. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15093. function pointers. The function pointer resides at index $0$, and the
  15094. values for the free variables fill in the rest of the tuple.
  15095. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15096. to see how closures work. It is a three-step dance. The program calls
  15097. function \code{f}, which creates a closure for the \code{lambda}. The
  15098. closure is a tuple whose first element is a pointer to the top-level
  15099. function that we will generate for the \code{lambda}; the second
  15100. element is the value of \code{x}, which is \code{5}; and the third
  15101. element is \code{4}, the value of \code{y}. The closure does not
  15102. contain an element for \code{z} because \code{z} is not a free
  15103. variable of the \code{lambda}. Creating the closure is step 1 of the
  15104. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15105. shown in figure~\ref{fig:closures}.
  15106. %
  15107. The second call to \code{f} creates another closure, this time with
  15108. \code{3} in the second slot (for \code{x}). This closure is also
  15109. returned from \code{f} but bound to \code{h}, which is also shown in
  15110. figure~\ref{fig:closures}.
  15111. \begin{figure}[tbp]
  15112. \centering
  15113. \begin{minipage}{0.65\textwidth}
  15114. \begin{tcolorbox}[colback=white]
  15115. \includegraphics[width=\textwidth]{figs/closures}
  15116. \end{tcolorbox}
  15117. \end{minipage}
  15118. \caption{Flat closure representations for the two functions
  15119. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15120. \label{fig:closures}
  15121. \end{figure}
  15122. Continuing with the example, consider the application of \code{g} to
  15123. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15124. closure, we obtain the function pointer from the first element of the
  15125. closure and call it, passing in the closure itself and then the
  15126. regular arguments, in this case \code{11}. This technique for applying
  15127. a closure is step 2 of the dance.
  15128. %
  15129. But doesn't this \code{lambda} take only one argument, for parameter
  15130. \code{z}? The third and final step of the dance is generating a
  15131. top-level function for a \code{lambda}. We add an additional
  15132. parameter for the closure and insert an initialization at the beginning
  15133. of the function for each free variable, to bind those variables to the
  15134. appropriate elements from the closure parameter.
  15135. %
  15136. This three-step dance is known as \emph{closure conversion}. We
  15137. discuss the details of closure conversion in
  15138. section~\ref{sec:closure-conversion} and show the code generated from
  15139. the example in section~\ref{sec:example-lambda}. First, we define
  15140. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  15141. \section{The \LangLam{} Language}
  15142. \label{sec:r5}
  15143. The definitions of the concrete syntax and abstract syntax for
  15144. \LangLam{}, a language with anonymous functions and lexical scoping,
  15145. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15146. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15147. for \LangFun{}, which already has syntax for function application.
  15148. %
  15149. \python{The syntax also includes an assignment statement that includes
  15150. a type annotation for the variable on the left-hand side, which
  15151. facilitates the type checking of \code{lambda} expressions that we
  15152. discuss later in this section.}
  15153. %
  15154. \racket{The \code{procedure-arity} operation returns the number of parameters
  15155. of a given function, an operation that we need for the translation
  15156. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15157. %
  15158. \python{The \code{arity} operation returns the number of parameters of
  15159. a given function, an operation that we need for the translation
  15160. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15161. The \code{arity} operation is not in Python, but the same functionality
  15162. is available in a more complex form. We include \code{arity} in the
  15163. \LangLam{} source language to enable testing.}
  15164. \newcommand{\LlambdaGrammarRacket}{
  15165. \begin{array}{lcl}
  15166. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15167. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15168. \end{array}
  15169. }
  15170. \newcommand{\LlambdaASTRacket}{
  15171. \begin{array}{lcl}
  15172. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15173. \itm{op} &::=& \code{procedure-arity}
  15174. \end{array}
  15175. }
  15176. \newcommand{\LlambdaGrammarPython}{
  15177. \begin{array}{lcl}
  15178. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15179. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15180. \end{array}
  15181. }
  15182. \newcommand{\LlambdaASTPython}{
  15183. \begin{array}{lcl}
  15184. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15185. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15186. \end{array}
  15187. }
  15188. % include AnnAssign in ASTPython
  15189. \begin{figure}[tp]
  15190. \centering
  15191. \begin{tcolorbox}[colback=white]
  15192. \small
  15193. {\if\edition\racketEd
  15194. \[
  15195. \begin{array}{l}
  15196. \gray{\LintGrammarRacket{}} \\ \hline
  15197. \gray{\LvarGrammarRacket{}} \\ \hline
  15198. \gray{\LifGrammarRacket{}} \\ \hline
  15199. \gray{\LwhileGrammarRacket} \\ \hline
  15200. \gray{\LtupGrammarRacket} \\ \hline
  15201. \gray{\LfunGrammarRacket} \\ \hline
  15202. \LlambdaGrammarRacket \\
  15203. \begin{array}{lcl}
  15204. \LangLamM{} &::=& \Def\ldots \; \Exp
  15205. \end{array}
  15206. \end{array}
  15207. \]
  15208. \fi}
  15209. {\if\edition\pythonEd
  15210. \[
  15211. \begin{array}{l}
  15212. \gray{\LintGrammarPython{}} \\ \hline
  15213. \gray{\LvarGrammarPython{}} \\ \hline
  15214. \gray{\LifGrammarPython{}} \\ \hline
  15215. \gray{\LwhileGrammarPython} \\ \hline
  15216. \gray{\LtupGrammarPython} \\ \hline
  15217. \gray{\LfunGrammarPython} \\ \hline
  15218. \LlambdaGrammarPython \\
  15219. \begin{array}{lcl}
  15220. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15221. \end{array}
  15222. \end{array}
  15223. \]
  15224. \fi}
  15225. \end{tcolorbox}
  15226. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15227. with \key{lambda}.}
  15228. \label{fig:Llam-concrete-syntax}
  15229. \end{figure}
  15230. \begin{figure}[tp]
  15231. \centering
  15232. \begin{tcolorbox}[colback=white]
  15233. \small
  15234. {\if\edition\racketEd
  15235. \[\arraycolsep=3pt
  15236. \begin{array}{l}
  15237. \gray{\LintOpAST} \\ \hline
  15238. \gray{\LvarASTRacket{}} \\ \hline
  15239. \gray{\LifASTRacket{}} \\ \hline
  15240. \gray{\LwhileASTRacket{}} \\ \hline
  15241. \gray{\LtupASTRacket{}} \\ \hline
  15242. \gray{\LfunASTRacket} \\ \hline
  15243. \LlambdaASTRacket \\
  15244. \begin{array}{lcl}
  15245. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15246. \end{array}
  15247. \end{array}
  15248. \]
  15249. \fi}
  15250. {\if\edition\pythonEd
  15251. \[
  15252. \begin{array}{l}
  15253. \gray{\LintASTPython} \\ \hline
  15254. \gray{\LvarASTPython{}} \\ \hline
  15255. \gray{\LifASTPython{}} \\ \hline
  15256. \gray{\LwhileASTPython{}} \\ \hline
  15257. \gray{\LtupASTPython{}} \\ \hline
  15258. \gray{\LfunASTPython} \\ \hline
  15259. \LlambdaASTPython \\
  15260. \begin{array}{lcl}
  15261. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15262. \end{array}
  15263. \end{array}
  15264. \]
  15265. \fi}
  15266. \end{tcolorbox}
  15267. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15268. \label{fig:Llam-syntax}
  15269. \end{figure}
  15270. \index{subject}{interpreter}
  15271. \label{sec:interp-Llambda}
  15272. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  15273. \LangLam{}. The case for \key{Lambda} saves the current environment
  15274. inside the returned function value. Recall that during function
  15275. application, the environment stored in the function value, extended
  15276. with the mapping of parameters to argument values, is used to
  15277. interpret the body of the function.
  15278. \begin{figure}[tbp]
  15279. \begin{tcolorbox}[colback=white]
  15280. {\if\edition\racketEd
  15281. \begin{lstlisting}
  15282. (define interp-Llambda-class
  15283. (class interp-Lfun-class
  15284. (super-new)
  15285. (define/override (interp-op op)
  15286. (match op
  15287. ['procedure-arity
  15288. (lambda (v)
  15289. (match v
  15290. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15291. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15292. [else (super interp-op op)]))
  15293. (define/override ((interp-exp env) e)
  15294. (define recur (interp-exp env))
  15295. (match e
  15296. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15297. `(function ,xs ,body ,env)]
  15298. [else ((super interp-exp env) e)]))
  15299. ))
  15300. (define (interp-Llambda p)
  15301. (send (new interp-Llambda-class) interp-program p))
  15302. \end{lstlisting}
  15303. \fi}
  15304. {\if\edition\pythonEd
  15305. \begin{lstlisting}
  15306. class InterpLlambda(InterpLfun):
  15307. def arity(self, v):
  15308. match v:
  15309. case Function(name, params, body, env):
  15310. return len(params)
  15311. case _:
  15312. raise Exception('Llambda arity unexpected ' + repr(v))
  15313. def interp_exp(self, e, env):
  15314. match e:
  15315. case Call(Name('arity'), [fun]):
  15316. f = self.interp_exp(fun, env)
  15317. return self.arity(f)
  15318. case Lambda(params, body):
  15319. return Function('lambda', params, [Return(body)], env)
  15320. case _:
  15321. return super().interp_exp(e, env)
  15322. def interp_stmts(self, ss, env):
  15323. if len(ss) == 0:
  15324. return
  15325. match ss[0]:
  15326. case AnnAssign(lhs, typ, value, simple):
  15327. env[lhs.id] = self.interp_exp(value, env)
  15328. return self.interp_stmts(ss[1:], env)
  15329. case _:
  15330. return super().interp_stmts(ss, env)
  15331. \end{lstlisting}
  15332. \fi}
  15333. \end{tcolorbox}
  15334. \caption{Interpreter for \LangLam{}.}
  15335. \label{fig:interp-Llambda}
  15336. \end{figure}
  15337. \label{sec:type-check-r5}
  15338. \index{subject}{type checking}
  15339. {\if\edition\racketEd
  15340. %
  15341. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15342. \key{lambda} form. The body of the \key{lambda} is checked in an
  15343. environment that includes the current environment (because it is
  15344. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15345. require the body's type to match the declared return type.
  15346. %
  15347. \fi}
  15348. {\if\edition\pythonEd
  15349. %
  15350. Figures~\ref{fig:type-check-Llambda} and
  15351. \ref{fig:type-check-Llambda-part2} define the type checker for
  15352. \LangLam{}, which is more complex than one might expect. The reason
  15353. for the added complexity is that the syntax of \key{lambda} does not
  15354. include type annotations for the parameters or return type. Instead
  15355. they must be inferred. There are many approaches of type inference to
  15356. choose from of varying degrees of complexity. We choose one of the
  15357. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15358. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15359. this book is compilation, not type inference.
  15360. The main idea of bidirectional type inference is to add an auxiliary
  15361. function, here named \code{check\_exp}, that takes an expected type
  15362. and checks whether the given expression is of that type. Thus, in
  15363. \code{check\_exp}, type information flows in a top-down manner with
  15364. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15365. function, where type information flows in a primarily bottom-up
  15366. manner.
  15367. %
  15368. The idea then is to use \code{check\_exp} in all the places where we
  15369. already know what the type of an expression should be, such as in the
  15370. \code{return} statement of a top-level function definition, or on the
  15371. right-hand side of an annotated assignment statement.
  15372. Getting back to \code{lambda}, it is straightforward to check a
  15373. \code{lambda} inside \code{check\_exp} because the expected type
  15374. provides the parameter types and the return type. On the other hand,
  15375. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15376. that we do not allow \code{lambda} in contexts where we don't already
  15377. know its type. This restriction does not incur a loss of
  15378. expressiveness for \LangLam{} because it is straightforward to modify
  15379. a program to sidestep the restriction, for example, by using an
  15380. annotated assignment statement to assign the \code{lambda} to a
  15381. temporary variable.
  15382. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15383. checker records their type in a \code{has\_type} field. This type
  15384. information is used later in this chapter.
  15385. %
  15386. \fi}
  15387. \begin{figure}[tbp]
  15388. \begin{tcolorbox}[colback=white]
  15389. {\if\edition\racketEd
  15390. \begin{lstlisting}
  15391. (define (type-check-Llambda env)
  15392. (lambda (e)
  15393. (match e
  15394. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15395. (define-values (new-body bodyT)
  15396. ((type-check-exp (append (map cons xs Ts) env)) body))
  15397. (define ty `(,@Ts -> ,rT))
  15398. (cond
  15399. [(equal? rT bodyT)
  15400. (values (HasType (Lambda params rT new-body) ty) ty)]
  15401. [else
  15402. (error "mismatch in return type" bodyT rT)])]
  15403. ...
  15404. )))
  15405. \end{lstlisting}
  15406. \fi}
  15407. {\if\edition\pythonEd
  15408. \begin{lstlisting}
  15409. class TypeCheckLlambda(TypeCheckLfun):
  15410. def type_check_exp(self, e, env):
  15411. match e:
  15412. case Name(id):
  15413. e.has_type = env[id]
  15414. return env[id]
  15415. case Lambda(params, body):
  15416. raise Exception('cannot synthesize a type for a lambda')
  15417. case Call(Name('arity'), [func]):
  15418. func_t = self.type_check_exp(func, env)
  15419. match func_t:
  15420. case FunctionType(params_t, return_t):
  15421. return IntType()
  15422. case _:
  15423. raise Exception('in arity, unexpected ' + repr(func_t))
  15424. case _:
  15425. return super().type_check_exp(e, env)
  15426. def check_exp(self, e, ty, env):
  15427. match e:
  15428. case Lambda(params, body):
  15429. e.has_type = ty
  15430. match ty:
  15431. case FunctionType(params_t, return_t):
  15432. new_env = env.copy().update(zip(params, params_t))
  15433. self.check_exp(body, return_t, new_env)
  15434. case _:
  15435. raise Exception('lambda does not have type ' + str(ty))
  15436. case Call(func, args):
  15437. func_t = self.type_check_exp(func, env)
  15438. match func_t:
  15439. case FunctionType(params_t, return_t):
  15440. for (arg, param_t) in zip(args, params_t):
  15441. self.check_exp(arg, param_t, env)
  15442. self.check_type_equal(return_t, ty, e)
  15443. case _:
  15444. raise Exception('type_check_exp: in call, unexpected ' + \
  15445. repr(func_t))
  15446. case _:
  15447. t = self.type_check_exp(e, env)
  15448. self.check_type_equal(t, ty, e)
  15449. \end{lstlisting}
  15450. \fi}
  15451. \end{tcolorbox}
  15452. \caption{Type checking \LangLam{}\python{, part 1}.}
  15453. \label{fig:type-check-Llambda}
  15454. \end{figure}
  15455. {\if\edition\pythonEd
  15456. \begin{figure}[tbp]
  15457. \begin{tcolorbox}[colback=white]
  15458. \begin{lstlisting}
  15459. def check_stmts(self, ss, return_ty, env):
  15460. if len(ss) == 0:
  15461. return
  15462. match ss[0]:
  15463. case FunctionDef(name, params, body, dl, returns, comment):
  15464. new_env = env.copy().update(params)
  15465. rt = self.check_stmts(body, returns, new_env)
  15466. self.check_stmts(ss[1:], return_ty, env)
  15467. case Return(value):
  15468. self.check_exp(value, return_ty, env)
  15469. case Assign([Name(id)], value):
  15470. if id in env:
  15471. self.check_exp(value, env[id], env)
  15472. else:
  15473. env[id] = self.type_check_exp(value, env)
  15474. self.check_stmts(ss[1:], return_ty, env)
  15475. case Assign([Subscript(tup, Constant(index), Store())], value):
  15476. tup_t = self.type_check_exp(tup, env)
  15477. match tup_t:
  15478. case TupleType(ts):
  15479. self.check_exp(value, ts[index], env)
  15480. case _:
  15481. raise Exception('expected a tuple, not ' + repr(tup_t))
  15482. self.check_stmts(ss[1:], return_ty, env)
  15483. case AnnAssign(Name(id), ty_annot, value, simple):
  15484. ss[0].annotation = ty_annot
  15485. if id in env:
  15486. self.check_type_equal(env[id], ty_annot)
  15487. else:
  15488. env[id] = ty_annot
  15489. self.check_exp(value, ty_annot, env)
  15490. self.check_stmts(ss[1:], return_ty, env)
  15491. case _:
  15492. self.type_check_stmts(ss, env)
  15493. def type_check(self, p):
  15494. match p:
  15495. case Module(body):
  15496. env = {}
  15497. for s in body:
  15498. match s:
  15499. case FunctionDef(name, params, bod, dl, returns, comment):
  15500. params_t = [t for (x,t) in params]
  15501. env[name] = FunctionType(params_t, returns)
  15502. self.check_stmts(body, int, env)
  15503. \end{lstlisting}
  15504. \end{tcolorbox}
  15505. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15506. \label{fig:type-check-Llambda-part2}
  15507. \end{figure}
  15508. \fi}
  15509. \clearpage
  15510. \section{Assignment and Lexically Scoped Functions}
  15511. \label{sec:assignment-scoping}
  15512. The combination of lexically scoped functions and assignment to
  15513. variables raises a challenge with the flat-closure approach to
  15514. implementing lexically scoped functions. Consider the following
  15515. example in which function \code{f} has a free variable \code{x} that
  15516. is changed after \code{f} is created but before the call to \code{f}.
  15517. % loop_test_11.rkt
  15518. {\if\edition\racketEd
  15519. \begin{lstlisting}
  15520. (let ([x 0])
  15521. (let ([y 0])
  15522. (let ([z 20])
  15523. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15524. (begin
  15525. (set! x 10)
  15526. (set! y 12)
  15527. (f y))))))
  15528. \end{lstlisting}
  15529. \fi}
  15530. {\if\edition\pythonEd
  15531. % box_free_assign.py
  15532. \begin{lstlisting}
  15533. def g(z : int) -> int:
  15534. x = 0
  15535. y = 0
  15536. f : Callable[[int],int] = lambda a: a + x + z
  15537. x = 10
  15538. y = 12
  15539. return f(y)
  15540. print( g(20) )
  15541. \end{lstlisting}
  15542. \fi} The correct output for this example is \code{42} because the call
  15543. to \code{f} is required to use the current value of \code{x} (which is
  15544. \code{10}). Unfortunately, the closure conversion pass
  15545. (section~\ref{sec:closure-conversion}) generates code for the
  15546. \code{lambda} that copies the old value of \code{x} into a
  15547. closure. Thus, if we naively applied closure conversion, the output of
  15548. this program would be \code{32}.
  15549. A first attempt at solving this problem would be to save a pointer to
  15550. \code{x} in the closure and change the occurrences of \code{x} inside
  15551. the lambda to dereference the pointer. Of course, this would require
  15552. assigning \code{x} to the stack and not to a register. However, the
  15553. problem goes a bit deeper.
  15554. Consider the following example that returns a function that refers to
  15555. a local variable of the enclosing function:
  15556. \begin{center}
  15557. \begin{minipage}{\textwidth}
  15558. {\if\edition\racketEd
  15559. \begin{lstlisting}
  15560. (define (f []) : Integer
  15561. (let ([x 0])
  15562. (let ([g (lambda: () : Integer x)])
  15563. (begin
  15564. (set! x 42)
  15565. g))))
  15566. ((f))
  15567. \end{lstlisting}
  15568. \fi}
  15569. {\if\edition\pythonEd
  15570. % counter.py
  15571. \begin{lstlisting}
  15572. def f():
  15573. x = 0
  15574. g = lambda: x
  15575. x = 42
  15576. return g
  15577. print( f()() )
  15578. \end{lstlisting}
  15579. \fi}
  15580. \end{minipage}
  15581. \end{center}
  15582. In this example, the lifetime of \code{x} extends beyond the lifetime
  15583. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15584. stack frame for the call to \code{f}, it would be gone by the time we
  15585. called \code{g}, leaving us with dangling pointers for
  15586. \code{x}. This example demonstrates that when a variable occurs free
  15587. inside a function, its lifetime becomes indefinite. Thus, the value of
  15588. the variable needs to live on the heap. The verb
  15589. \emph{box}\index{subject}{box} is often used for allocating a single
  15590. value on the heap, producing a pointer, and
  15591. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15592. %
  15593. We introduce a new pass named \code{convert\_assignments} to address
  15594. this challenge.
  15595. %
  15596. \python{But before diving into that, we have one more
  15597. problem to discuss.}
  15598. \if\edition\pythonEd
  15599. \section{Uniquify Variables}
  15600. \label{sec:uniquify-lambda}
  15601. With the addition of \code{lambda} we have a complication to deal
  15602. with: name shadowing. Consider the following program with a function
  15603. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15604. \code{lambda} expressions. The first \code{lambda} has a parameter
  15605. that is also named \code{x}.
  15606. \begin{lstlisting}
  15607. def f(x:int, y:int) -> Callable[[int], int]:
  15608. g : Callable[[int],int] = (lambda x: x + y)
  15609. h : Callable[[int],int] = (lambda y: x + y)
  15610. x = input_int()
  15611. return g
  15612. print(f(0, 10)(32))
  15613. \end{lstlisting}
  15614. Many of our compiler passes rely on being able to connect variable
  15615. uses with their definitions using just the name of the variable,
  15616. including new passes in this chapter. However, in the above example
  15617. the name of the variable does not uniquely determine its
  15618. definition. To solve this problem we recommend implementing a pass
  15619. named \code{uniquify} that renames every variable in the program to
  15620. make sure they are all unique.
  15621. The following shows the result of \code{uniquify} for the above
  15622. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15623. and the \code{x} parameter of the \code{lambda} is renamed to
  15624. \code{x\_4}.
  15625. \begin{lstlisting}
  15626. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15627. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15628. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15629. x_0 = input_int()
  15630. return g_2
  15631. def main() -> int :
  15632. print(f(0, 10)(32))
  15633. return 0
  15634. \end{lstlisting}
  15635. \fi
  15636. %% \section{Reveal Functions}
  15637. %% \label{sec:reveal-functions-r5}
  15638. %% \racket{To support the \code{procedure-arity} operator we need to
  15639. %% communicate the arity of a function to the point of closure
  15640. %% creation.}
  15641. %% %
  15642. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15643. %% function at runtime. Thus, we need to communicate the arity of a
  15644. %% function to the point of closure creation.}
  15645. %% %
  15646. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15647. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15648. %% \[
  15649. %% \begin{array}{lcl}
  15650. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15651. %% \end{array}
  15652. %% \]
  15653. \section{Assignment Conversion}
  15654. \label{sec:convert-assignments}
  15655. The purpose of the \code{convert\_assignments} pass is to address the
  15656. challenge regarding the interaction between variable assignments and
  15657. closure conversion. First we identify which variables need to be
  15658. boxed, and then we transform the program to box those variables. In
  15659. general, boxing introduces runtime overhead that we would like to
  15660. avoid, so we should box as few variables as possible. We recommend
  15661. boxing the variables in the intersection of the following two sets of
  15662. variables:
  15663. \begin{enumerate}
  15664. \item The variables that are free in a \code{lambda}.
  15665. \item The variables that appear on the left-hand side of an
  15666. assignment.
  15667. \end{enumerate}
  15668. The first condition is a must but the second condition is
  15669. conservative. It is possible to develop a more liberal condition using
  15670. static program analysis.
  15671. Consider again the first example from
  15672. section~\ref{sec:assignment-scoping}:
  15673. %
  15674. {\if\edition\racketEd
  15675. \begin{lstlisting}
  15676. (let ([x 0])
  15677. (let ([y 0])
  15678. (let ([z 20])
  15679. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15680. (begin
  15681. (set! x 10)
  15682. (set! y 12)
  15683. (f y))))))
  15684. \end{lstlisting}
  15685. \fi}
  15686. {\if\edition\pythonEd
  15687. \begin{lstlisting}
  15688. def g(z : int) -> int:
  15689. x = 0
  15690. y = 0
  15691. f : Callable[[int],int] = lambda a: a + x + z
  15692. x = 10
  15693. y = 12
  15694. return f(y)
  15695. print( g(20) )
  15696. \end{lstlisting}
  15697. \fi}
  15698. %
  15699. \noindent The variables \code{x} and \code{y} are assigned to. The
  15700. variables \code{x} and \code{z} occur free inside the
  15701. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15702. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15703. transformations: initialize \code{x} with a tuple whose elements are
  15704. uninitialized, replace reads from \code{x} with tuple reads, and
  15705. replace each assignment to \code{x} with a tuple write. The output of
  15706. \code{convert\_assignments} for this example is as follows:
  15707. %
  15708. {\if\edition\racketEd
  15709. \begin{lstlisting}
  15710. (define (main) : Integer
  15711. (let ([x0 (vector 0)])
  15712. (let ([y1 0])
  15713. (let ([z2 20])
  15714. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15715. (+ a3 (+ (vector-ref x0 0) z2)))])
  15716. (begin
  15717. (vector-set! x0 0 10)
  15718. (set! y1 12)
  15719. (f4 y1)))))))
  15720. \end{lstlisting}
  15721. \fi}
  15722. %
  15723. {\if\edition\pythonEd
  15724. \begin{lstlisting}
  15725. def g(z : int)-> int:
  15726. x = (uninitialized(int),)
  15727. x[0] = 0
  15728. y = 0
  15729. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15730. x[0] = 10
  15731. y = 12
  15732. return f(y)
  15733. def main() -> int:
  15734. print(g(20))
  15735. return 0
  15736. \end{lstlisting}
  15737. \fi}
  15738. To compute the free variables of all the \code{lambda} expressions, we
  15739. recommend defining the following two auxiliary functions:
  15740. \begin{enumerate}
  15741. \item \code{free\_variables} computes the free variables of an expression, and
  15742. \item \code{free\_in\_lambda} collects all the variables that are
  15743. free in any of the \code{lambda} expressions, using
  15744. \code{free\_variables} in the case for each \code{lambda}.
  15745. \end{enumerate}
  15746. {\if\edition\racketEd
  15747. %
  15748. To compute the variables that are assigned to, we recommend updating
  15749. the \code{collect-set!} function that we introduced in
  15750. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15751. as \code{Lambda}.
  15752. %
  15753. \fi}
  15754. {\if\edition\pythonEd
  15755. %
  15756. To compute the variables that are assigned to, we recommend defining
  15757. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15758. the set of variables that occur in the left-hand side of an assignment
  15759. statement, and otherwise returns the empty set.
  15760. %
  15761. \fi}
  15762. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15763. free in a \code{lambda} and that are assigned to in the enclosing
  15764. function definition.
  15765. Next we discuss the \code{convert\_assignments} pass. In the case for
  15766. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15767. $\VAR{x}$ to a tuple read.
  15768. %
  15769. {\if\edition\racketEd
  15770. \begin{lstlisting}
  15771. (Var |$x$|)
  15772. |$\Rightarrow$|
  15773. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15774. \end{lstlisting}
  15775. \fi}
  15776. %
  15777. {\if\edition\pythonEd
  15778. \begin{lstlisting}
  15779. Name(|$x$|)
  15780. |$\Rightarrow$|
  15781. Subscript(Name(|$x$|), Constant(0), Load())
  15782. \end{lstlisting}
  15783. \fi}
  15784. %
  15785. \noindent In the case for assignment, recursively process the
  15786. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15787. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15788. as follows:
  15789. %
  15790. {\if\edition\racketEd
  15791. \begin{lstlisting}
  15792. (SetBang |$x$| |$\itm{rhs}$|)
  15793. |$\Rightarrow$|
  15794. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15795. \end{lstlisting}
  15796. \fi}
  15797. {\if\edition\pythonEd
  15798. \begin{lstlisting}
  15799. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15800. |$\Rightarrow$|
  15801. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15802. \end{lstlisting}
  15803. \fi}
  15804. %
  15805. {\if\edition\racketEd
  15806. The case for \code{Lambda} is nontrivial, but it is similar to the
  15807. case for function definitions, which we discuss next.
  15808. \fi}
  15809. %
  15810. To translate a function definition, we first compute $\mathit{AF}$,
  15811. the intersection of the variables that are free in a \code{lambda} and
  15812. that are assigned to. We then apply assignment conversion to the body
  15813. of the function definition. Finally, we box the parameters of this
  15814. function definition that are in $\mathit{AF}$. For example,
  15815. the parameter \code{x} of the following function \code{g}
  15816. needs to be boxed:
  15817. {\if\edition\racketEd
  15818. \begin{lstlisting}
  15819. (define (g [x : Integer]) : Integer
  15820. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15821. (begin
  15822. (set! x 10)
  15823. (f 32))))
  15824. \end{lstlisting}
  15825. \fi}
  15826. %
  15827. {\if\edition\pythonEd
  15828. \begin{lstlisting}
  15829. def g(x : int) -> int:
  15830. f : Callable[[int],int] = lambda a: a + x
  15831. x = 10
  15832. return f(32)
  15833. \end{lstlisting}
  15834. \fi}
  15835. %
  15836. \noindent We box parameter \code{x} by creating a local variable named
  15837. \code{x} that is initialized to a tuple whose contents is the value of
  15838. the parameter, which has been renamed to \code{x\_0}.
  15839. %
  15840. {\if\edition\racketEd
  15841. \begin{lstlisting}
  15842. (define (g [x_0 : Integer]) : Integer
  15843. (let ([x (vector x_0)])
  15844. (let ([f (lambda: ([a : Integer]) : Integer
  15845. (+ a (vector-ref x 0)))])
  15846. (begin
  15847. (vector-set! x 0 10)
  15848. (f 32)))))
  15849. \end{lstlisting}
  15850. \fi}
  15851. %
  15852. {\if\edition\pythonEd
  15853. \begin{lstlisting}
  15854. def g(x_0 : int)-> int:
  15855. x = (x_0,)
  15856. f : Callable[[int], int] = (lambda a: a + x[0])
  15857. x[0] = 10
  15858. return f(32)
  15859. \end{lstlisting}
  15860. \fi}
  15861. \section{Closure Conversion}
  15862. \label{sec:closure-conversion}
  15863. \index{subject}{closure conversion}
  15864. The compiling of lexically scoped functions into top-level function
  15865. definitions and flat closures is accomplished in the pass
  15866. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15867. and before \code{limit\_functions}.
  15868. As usual, we implement the pass as a recursive function over the
  15869. AST. The interesting cases are for \key{lambda} and function
  15870. application. We transform a \key{lambda} expression into an expression
  15871. that creates a closure, that is, a tuple for which the first element
  15872. is a function pointer and the rest of the elements are the values of
  15873. the free variables of the \key{lambda}.
  15874. %
  15875. However, we use the \code{Closure} AST node instead of using a tuple
  15876. so that we can record the arity.
  15877. %
  15878. In the generated code that follows, \itm{fvs} is the free variables of
  15879. the lambda and \itm{name} is a unique symbol generated to identify the
  15880. lambda.
  15881. %
  15882. \racket{The \itm{arity} is the number of parameters (the length of
  15883. \itm{ps}).}
  15884. %
  15885. {\if\edition\racketEd
  15886. \begin{lstlisting}
  15887. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15888. |$\Rightarrow$|
  15889. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15890. \end{lstlisting}
  15891. \fi}
  15892. %
  15893. {\if\edition\pythonEd
  15894. \begin{lstlisting}
  15895. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15896. |$\Rightarrow$|
  15897. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15898. \end{lstlisting}
  15899. \fi}
  15900. %
  15901. In addition to transforming each \key{Lambda} AST node into a
  15902. tuple, we create a top-level function definition for each
  15903. \key{Lambda}, as shown next.\\
  15904. \begin{minipage}{0.8\textwidth}
  15905. {\if\edition\racketEd
  15906. \begin{lstlisting}
  15907. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15908. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15909. ...
  15910. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15911. |\itm{body'}|)...))
  15912. \end{lstlisting}
  15913. \fi}
  15914. {\if\edition\pythonEd
  15915. \begin{lstlisting}
  15916. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15917. |$\itm{fvs}_1$| = clos[1]
  15918. |$\ldots$|
  15919. |$\itm{fvs}_n$| = clos[|$n$|]
  15920. |\itm{body'}|
  15921. \end{lstlisting}
  15922. \fi}
  15923. \end{minipage}\\
  15924. The \code{clos} parameter refers to the closure. Translate the type
  15925. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15926. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15927. \itm{closTy} is a tuple type for which the first element type is
  15928. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15929. the element types are the types of the free variables in the
  15930. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15931. is nontrivial to give a type to the function in the closure's type.%
  15932. %
  15933. \footnote{To give an accurate type to a closure, we would need to add
  15934. existential types to the type checker~\citep{Minamide:1996ys}.}
  15935. %
  15936. %% The dummy type is considered to be equal to any other type during type
  15937. %% checking.
  15938. The free variables become local variables that are initialized with
  15939. their values in the closure.
  15940. Closure conversion turns every function into a tuple, so the type
  15941. annotations in the program must also be translated. We recommend
  15942. defining an auxiliary recursive function for this purpose. Function
  15943. types should be translated as follows:
  15944. %
  15945. {\if\edition\racketEd
  15946. \begin{lstlisting}
  15947. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15948. |$\Rightarrow$|
  15949. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15950. \end{lstlisting}
  15951. \fi}
  15952. {\if\edition\pythonEd
  15953. \begin{lstlisting}
  15954. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15955. |$\Rightarrow$|
  15956. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15957. \end{lstlisting}
  15958. \fi}
  15959. %
  15960. This type indicates that the first thing in the tuple is a
  15961. function. The first parameter of the function is a tuple (a closure)
  15962. and the rest of the parameters are the ones from the original
  15963. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15964. omits the types of the free variables because (1) those types are not
  15965. available in this context, and (2) we do not need them in the code that
  15966. is generated for function application. So this type describes only the
  15967. first component of the closure tuple. At runtime the tuple may have
  15968. more components, but we ignore them at this point.
  15969. We transform function application into code that retrieves the
  15970. function from the closure and then calls the function, passing the
  15971. closure as the first argument. We place $e'$ in a temporary variable
  15972. to avoid code duplication.
  15973. \begin{center}
  15974. \begin{minipage}{\textwidth}
  15975. {\if\edition\racketEd
  15976. \begin{lstlisting}
  15977. (Apply |$e$| |$\itm{es}$|)
  15978. |$\Rightarrow$|
  15979. (Let |$\itm{tmp}$| |$e'$|
  15980. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15981. \end{lstlisting}
  15982. \fi}
  15983. %
  15984. {\if\edition\pythonEd
  15985. \begin{lstlisting}
  15986. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15987. |$\Rightarrow$|
  15988. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15989. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15990. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15991. \end{lstlisting}
  15992. \fi}
  15993. \end{minipage}
  15994. \end{center}
  15995. There is also the question of what to do with references to top-level
  15996. function definitions. To maintain a uniform translation of function
  15997. application, we turn function references into closures.
  15998. \begin{tabular}{lll}
  15999. \begin{minipage}{0.3\textwidth}
  16000. {\if\edition\racketEd
  16001. \begin{lstlisting}
  16002. (FunRef |$f$| |$n$|)
  16003. \end{lstlisting}
  16004. \fi}
  16005. {\if\edition\pythonEd
  16006. \begin{lstlisting}
  16007. FunRef(|$f$|, |$n$|)
  16008. \end{lstlisting}
  16009. \fi}
  16010. \end{minipage}
  16011. &
  16012. $\Rightarrow$
  16013. &
  16014. \begin{minipage}{0.5\textwidth}
  16015. {\if\edition\racketEd
  16016. \begin{lstlisting}
  16017. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16018. \end{lstlisting}
  16019. \fi}
  16020. {\if\edition\pythonEd
  16021. \begin{lstlisting}
  16022. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16023. \end{lstlisting}
  16024. \fi}
  16025. \end{minipage}
  16026. \end{tabular} \\
  16027. We no longer need the annotated assignment statement \code{AnnAssign}
  16028. to support the type checking of \code{lambda} expressions, so we
  16029. translate it to a regular \code{Assign} statement.
  16030. The top-level function definitions need to be updated to take an extra
  16031. closure parameter, but that parameter is ignored in the body of those
  16032. functions.
  16033. \section{An Example Translation}
  16034. \label{sec:example-lambda}
  16035. Figure~\ref{fig:lexical-functions-example} shows the result of
  16036. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16037. program demonstrating lexical scoping that we discussed at the
  16038. beginning of this chapter.
  16039. \begin{figure}[tbp]
  16040. \begin{tcolorbox}[colback=white]
  16041. \begin{minipage}{0.8\textwidth}
  16042. {\if\edition\racketEd
  16043. % tests/lambda_test_6.rkt
  16044. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16045. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16046. (let ([y8 4])
  16047. (lambda: ([z9 : Integer]) : Integer
  16048. (+ x7 (+ y8 z9)))))
  16049. (define (main) : Integer
  16050. (let ([g0 ((fun-ref f6 1) 5)])
  16051. (let ([h1 ((fun-ref f6 1) 3)])
  16052. (+ (g0 11) (h1 15)))))
  16053. \end{lstlisting}
  16054. $\Rightarrow$
  16055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16056. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16057. (let ([y8 4])
  16058. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16059. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16060. (let ([x7 (vector-ref fvs3 1)])
  16061. (let ([y8 (vector-ref fvs3 2)])
  16062. (+ x7 (+ y8 z9)))))
  16063. (define (main) : Integer
  16064. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16065. ((vector-ref clos5 0) clos5 5))])
  16066. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16067. ((vector-ref clos6 0) clos6 3))])
  16068. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16069. \end{lstlisting}
  16070. \fi}
  16071. %
  16072. {\if\edition\pythonEd
  16073. % free_var.py
  16074. \begin{lstlisting}
  16075. def f(x : int) -> Callable[[int], int]:
  16076. y = 4
  16077. return lambda z: x + y + z
  16078. g = f(5)
  16079. h = f(3)
  16080. print( g(11) + h(15) )
  16081. \end{lstlisting}
  16082. $\Rightarrow$
  16083. \begin{lstlisting}
  16084. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16085. x = fvs_1[1]
  16086. y = fvs_1[2]
  16087. return x + y[0] + z
  16088. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16089. y = (777,)
  16090. y[0] = 4
  16091. return (lambda_0, x, y)
  16092. def main() -> int:
  16093. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16094. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16095. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16096. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16097. return 0
  16098. \end{lstlisting}
  16099. \fi}
  16100. \end{minipage}
  16101. \end{tcolorbox}
  16102. \caption{Example of closure conversion.}
  16103. \label{fig:lexical-functions-example}
  16104. \end{figure}
  16105. \begin{exercise}\normalfont\normalsize
  16106. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16107. Create five new programs that use \key{lambda} functions and make use of
  16108. lexical scoping. Test your compiler on these new programs and all
  16109. your previously created test programs.
  16110. \end{exercise}
  16111. \section{Expose Allocation}
  16112. \label{sec:expose-allocation-r5}
  16113. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16114. that allocates and initializes a tuple, similar to the translation of
  16115. the tuple creation in section~\ref{sec:expose-allocation}.
  16116. The only difference is replacing the use of
  16117. \ALLOC{\itm{len}}{\itm{type}} with
  16118. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16119. \section{Explicate Control and \LangCLam{}}
  16120. \label{sec:explicate-r5}
  16121. The output language of \code{explicate\_control} is \LangCLam{}; the
  16122. definition of its abstract syntax is shown in
  16123. figure~\ref{fig:Clam-syntax}.
  16124. %
  16125. \racket{The only differences with respect to \LangCFun{} are the
  16126. addition of the \code{AllocateClosure} form to the grammar for
  16127. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16128. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16129. similar to the handling of other expressions such as primitive
  16130. operators.}
  16131. %
  16132. \python{The differences with respect to \LangCFun{} are the
  16133. additions of \code{Uninitialized}, \code{AllocateClosure},
  16134. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16135. \code{explicate\_control} pass is similar to the handling of other
  16136. expressions such as primitive operators.}
  16137. \newcommand{\ClambdaASTRacket}{
  16138. \begin{array}{lcl}
  16139. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16140. \itm{op} &::= & \code{procedure-arity}
  16141. \end{array}
  16142. }
  16143. \newcommand{\ClambdaASTPython}{
  16144. \begin{array}{lcl}
  16145. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16146. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16147. &\MID& \ARITY{\Atm}
  16148. \end{array}
  16149. }
  16150. \begin{figure}[tp]
  16151. \begin{tcolorbox}[colback=white]
  16152. \small
  16153. {\if\edition\racketEd
  16154. \[
  16155. \begin{array}{l}
  16156. \gray{\CvarASTRacket} \\ \hline
  16157. \gray{\CifASTRacket} \\ \hline
  16158. \gray{\CloopASTRacket} \\ \hline
  16159. \gray{\CtupASTRacket} \\ \hline
  16160. \gray{\CfunASTRacket} \\ \hline
  16161. \ClambdaASTRacket \\
  16162. \begin{array}{lcl}
  16163. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16164. \end{array}
  16165. \end{array}
  16166. \]
  16167. \fi}
  16168. {\if\edition\pythonEd
  16169. \[
  16170. \begin{array}{l}
  16171. \gray{\CifASTPython} \\ \hline
  16172. \gray{\CtupASTPython} \\ \hline
  16173. \gray{\CfunASTPython} \\ \hline
  16174. \ClambdaASTPython \\
  16175. \begin{array}{lcl}
  16176. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16177. \end{array}
  16178. \end{array}
  16179. \]
  16180. \fi}
  16181. \end{tcolorbox}
  16182. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16183. \label{fig:Clam-syntax}
  16184. \end{figure}
  16185. \section{Select Instructions}
  16186. \label{sec:select-instructions-Llambda}
  16187. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16188. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16189. (section~\ref{sec:select-instructions-gc}). The only difference is
  16190. that you should place the \itm{arity} in the tag that is stored at
  16191. position $0$ of the vector. Recall that in
  16192. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16193. was not used. We store the arity in the $5$ bits starting at position
  16194. $58$.
  16195. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16196. instructions that access the tag from position $0$ of the vector and
  16197. extract the $5$ bits starting at position $58$ from the tag.}
  16198. %
  16199. \python{Compile a call to the \code{arity} operator to a sequence of
  16200. instructions that access the tag from position $0$ of the tuple
  16201. (representing a closure) and extract the $5$-bits starting at position
  16202. $58$ from the tag.}
  16203. \begin{figure}[p]
  16204. \begin{tcolorbox}[colback=white]
  16205. {\if\edition\racketEd
  16206. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16207. \node (Lfun) at (0,2) {\large \LangLam{}};
  16208. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16209. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16210. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16211. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16212. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16213. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16214. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16215. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16216. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16217. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16218. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16219. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16220. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16221. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16222. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16223. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16224. \path[->,bend left=15] (Lfun) edge [above] node
  16225. {\ttfamily\footnotesize shrink} (Lfun-2);
  16226. \path[->,bend left=15] (Lfun-2) edge [above] node
  16227. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16228. \path[->,bend left=15] (Lfun-3) edge [above] node
  16229. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16230. \path[->,bend left=15] (F1-0) edge [left] node
  16231. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16232. \path[->,bend left=15] (F1-1) edge [below] node
  16233. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16234. \path[->,bend right=15] (F1-2) edge [above] node
  16235. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16236. \path[->,bend right=15] (F1-3) edge [above] node
  16237. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16238. \path[->,bend left=15] (F1-4) edge [right] node
  16239. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16240. \path[->,bend right=15] (F1-5) edge [below] node
  16241. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16242. \path[->,bend left=15] (F1-6) edge [above] node
  16243. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16244. \path[->] (C3-2) edge [right] node
  16245. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16246. \path[->,bend right=15] (x86-2) edge [right] node
  16247. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16248. \path[->,bend right=15] (x86-2-1) edge [below] node
  16249. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16250. \path[->,bend right=15] (x86-2-2) edge [right] node
  16251. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16252. \path[->,bend left=15] (x86-3) edge [above] node
  16253. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16254. \path[->,bend left=15] (x86-4) edge [right] node
  16255. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16256. \end{tikzpicture}
  16257. \fi}
  16258. {\if\edition\pythonEd
  16259. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16260. \node (Lfun) at (0,2) {\large \LangLam{}};
  16261. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16262. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16263. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16264. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16265. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16266. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16267. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16268. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16269. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16270. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16271. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16272. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16273. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16274. \path[->,bend left=15] (Lfun) edge [above] node
  16275. {\ttfamily\footnotesize shrink} (Lfun-2);
  16276. \path[->,bend left=15] (Lfun-2) edge [above] node
  16277. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16278. \path[->,bend left=15] (Lfun-3) edge [above] node
  16279. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16280. \path[->,bend left=15] (F1-0) edge [left] node
  16281. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16282. \path[->,bend left=15] (F1-1) edge [below] node
  16283. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16284. \path[->,bend left=15] (F1-2) edge [below] node
  16285. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16286. \path[->,bend right=15] (F1-3) edge [above] node
  16287. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16288. \path[->,bend right=15] (F1-5) edge [right] node
  16289. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16290. \path[->,bend left=15] (F1-6) edge [right] node
  16291. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16292. \path[->,bend right=15] (C3-2) edge [right] node
  16293. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16294. \path[->,bend right=15] (x86-2) edge [below] node
  16295. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16296. \path[->,bend right=15] (x86-3) edge [below] node
  16297. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16298. \path[->,bend left=15] (x86-4) edge [above] node
  16299. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16300. \end{tikzpicture}
  16301. \fi}
  16302. \end{tcolorbox}
  16303. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16304. functions.}
  16305. \label{fig:Llambda-passes}
  16306. \end{figure}
  16307. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16308. needed for the compilation of \LangLam{}.
  16309. \clearpage
  16310. \section{Challenge: Optimize Closures}
  16311. \label{sec:optimize-closures}
  16312. In this chapter we compile lexically scoped functions into a
  16313. relatively efficient representation: flat closures. However, even this
  16314. representation comes with some overhead. For example, consider the
  16315. following program with a function \code{tail\_sum} that does not have
  16316. any free variables and where all the uses of \code{tail\_sum} are in
  16317. applications in which we know that only \code{tail\_sum} is being applied
  16318. (and not any other functions):
  16319. \begin{center}
  16320. \begin{minipage}{0.95\textwidth}
  16321. {\if\edition\racketEd
  16322. \begin{lstlisting}
  16323. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16324. (if (eq? n 0)
  16325. s
  16326. (tail_sum (- n 1) (+ n s))))
  16327. (+ (tail_sum 3 0) 36)
  16328. \end{lstlisting}
  16329. \fi}
  16330. {\if\edition\pythonEd
  16331. \begin{lstlisting}
  16332. def tail_sum(n : int, s : int) -> int:
  16333. if n == 0:
  16334. return s
  16335. else:
  16336. return tail_sum(n - 1, n + s)
  16337. print( tail_sum(3, 0) + 36)
  16338. \end{lstlisting}
  16339. \fi}
  16340. \end{minipage}
  16341. \end{center}
  16342. As described in this chapter, we uniformly apply closure conversion to
  16343. all functions, obtaining the following output for this program:
  16344. \begin{center}
  16345. \begin{minipage}{0.95\textwidth}
  16346. {\if\edition\racketEd
  16347. \begin{lstlisting}
  16348. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16349. (if (eq? n2 0)
  16350. s3
  16351. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16352. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16353. (define (main) : Integer
  16354. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16355. ((vector-ref clos6 0) clos6 3 0)) 27))
  16356. \end{lstlisting}
  16357. \fi}
  16358. {\if\edition\pythonEd
  16359. \begin{lstlisting}
  16360. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16361. if n_0 == 0:
  16362. return s_1
  16363. else:
  16364. return (let clos_2 = (tail_sum,)
  16365. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16366. def main() -> int :
  16367. print((let clos_4 = (tail_sum,)
  16368. in clos_4[0](clos_4, 3, 0)) + 36)
  16369. return 0
  16370. \end{lstlisting}
  16371. \fi}
  16372. \end{minipage}
  16373. \end{center}
  16374. If this program were compiled according to the previous chapter, there
  16375. would be no allocation and the calls to \code{tail\_sum} would be
  16376. direct calls. In contrast, the program presented here allocates memory
  16377. for each closure and the calls to \code{tail\_sum} are indirect. These
  16378. two differences incur considerable overhead in a program such as this,
  16379. in which the allocations and indirect calls occur inside a tight loop.
  16380. One might think that this problem is trivial to solve: can't we just
  16381. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16382. and compile them to direct calls instead of treating it like a call to
  16383. a closure? We would also drop the new \code{fvs} parameter of
  16384. \code{tail\_sum}.
  16385. %
  16386. However, this problem is not so trivial, because a global function may
  16387. \emph{escape} and become involved in applications that also involve
  16388. closures. Consider the following example in which the application
  16389. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16390. application because the \code{lambda} may flow into \code{f}, but the
  16391. \code{inc} function might also flow into \code{f}:
  16392. \begin{center}
  16393. \begin{minipage}{\textwidth}
  16394. % lambda_test_30.rkt
  16395. {\if\edition\racketEd
  16396. \begin{lstlisting}
  16397. (define (inc [x : Integer]) : Integer
  16398. (+ x 1))
  16399. (let ([y (read)])
  16400. (let ([f (if (eq? (read) 0)
  16401. inc
  16402. (lambda: ([x : Integer]) : Integer (- x y)))])
  16403. (f 41)))
  16404. \end{lstlisting}
  16405. \fi}
  16406. {\if\edition\pythonEd
  16407. \begin{lstlisting}
  16408. def add1(x : int) -> int:
  16409. return x + 1
  16410. y = input_int()
  16411. g : Callable[[int], int] = lambda x: x - y
  16412. f = add1 if input_int() == 0 else g
  16413. print( f(41) )
  16414. \end{lstlisting}
  16415. \fi}
  16416. \end{minipage}
  16417. \end{center}
  16418. If a global function name is used in any way other than as the
  16419. operator in a direct call, then we say that the function
  16420. \emph{escapes}. If a global function does not escape, then we do not
  16421. need to perform closure conversion on the function.
  16422. \begin{exercise}\normalfont\normalsize
  16423. Implement an auxiliary function for detecting which global
  16424. functions escape. Using that function, implement an improved version
  16425. of closure conversion that does not apply closure conversion to
  16426. global functions that do not escape but instead compiles them as
  16427. regular functions. Create several new test cases that check whether
  16428. your compiler properly detect whether global functions escape or not.
  16429. \end{exercise}
  16430. So far we have reduced the overhead of calling global functions, but
  16431. it would also be nice to reduce the overhead of calling a
  16432. \code{lambda} when we can determine at compile time which
  16433. \code{lambda} will be called. We refer to such calls as \emph{known
  16434. calls}. Consider the following example in which a \code{lambda} is
  16435. bound to \code{f} and then applied.
  16436. {\if\edition\racketEd
  16437. % lambda_test_9.rkt
  16438. \begin{lstlisting}
  16439. (let ([y (read)])
  16440. (let ([f (lambda: ([x : Integer]) : Integer
  16441. (+ x y))])
  16442. (f 21)))
  16443. \end{lstlisting}
  16444. \fi}
  16445. {\if\edition\pythonEd
  16446. \begin{lstlisting}
  16447. y = input_int()
  16448. f : Callable[[int],int] = lambda x: x + y
  16449. print( f(21) )
  16450. \end{lstlisting}
  16451. \fi}
  16452. %
  16453. \noindent Closure conversion compiles the application
  16454. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16455. %
  16456. {\if\edition\racketEd
  16457. \begin{lstlisting}
  16458. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16459. (let ([y2 (vector-ref fvs6 1)])
  16460. (+ x3 y2)))
  16461. (define (main) : Integer
  16462. (let ([y2 (read)])
  16463. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16464. ((vector-ref f4 0) f4 21))))
  16465. \end{lstlisting}
  16466. \fi}
  16467. {\if\edition\pythonEd
  16468. \begin{lstlisting}
  16469. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16470. y_1 = fvs_4[1]
  16471. return x_2 + y_1[0]
  16472. def main() -> int:
  16473. y_1 = (777,)
  16474. y_1[0] = input_int()
  16475. f_0 = (lambda_3, y_1)
  16476. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16477. return 0
  16478. \end{lstlisting}
  16479. \fi}
  16480. %
  16481. \noindent However, we can instead compile the application
  16482. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16483. %
  16484. {\if\edition\racketEd
  16485. \begin{lstlisting}
  16486. (define (main) : Integer
  16487. (let ([y2 (read)])
  16488. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16489. ((fun-ref lambda5 1) f4 21))))
  16490. \end{lstlisting}
  16491. \fi}
  16492. {\if\edition\pythonEd
  16493. \begin{lstlisting}
  16494. def main() -> int:
  16495. y_1 = (777,)
  16496. y_1[0] = input_int()
  16497. f_0 = (lambda_3, y_1)
  16498. print(lambda_3(f_0, 21))
  16499. return 0
  16500. \end{lstlisting}
  16501. \fi}
  16502. The problem of determining which \code{lambda} will be called from a
  16503. particular application is quite challenging in general and the topic
  16504. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16505. following exercise we recommend that you compile an application to a
  16506. direct call when the operator is a variable and \racket{the variable
  16507. is \code{let}-bound to a closure}\python{the previous assignment to
  16508. the variable is a closure}. This can be accomplished by maintaining
  16509. an environment that maps variables to function names. Extend the
  16510. environment whenever you encounter a closure on the right-hand side of
  16511. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16512. name of the global function for the closure. This pass should come
  16513. after closure conversion.
  16514. \begin{exercise}\normalfont\normalsize
  16515. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16516. compiles known calls into direct calls. Verify that your compiler is
  16517. successful in this regard on several example programs.
  16518. \end{exercise}
  16519. These exercises only scratch the surface of closure optimization. A
  16520. good next step for the interested reader is to look at the work of
  16521. \citet{Keep:2012ab}.
  16522. \section{Further Reading}
  16523. The notion of lexically scoped functions predates modern computers by
  16524. about a decade. They were invented by \citet{Church:1932aa}, who
  16525. proposed the lambda calculus as a foundation for logic. Anonymous
  16526. functions were included in the LISP~\citep{McCarthy:1960dz}
  16527. programming language but were initially dynamically scoped. The Scheme
  16528. dialect of LISP adopted lexical scoping, and
  16529. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16530. Scheme programs. However, environments were represented as linked
  16531. lists, so variable look-up was linear in the size of the
  16532. environment. \citet{Appel91} gives a detailed description of several
  16533. closure representations. In this chapter we represent environments
  16534. using flat closures, which were invented by
  16535. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  16536. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16537. closures, variable look-up is constant time but the time to create a
  16538. closure is proportional to the number of its free variables. Flat
  16539. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16540. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16541. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16542. % compilers)
  16543. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16544. \chapter{Dynamic Typing}
  16545. \label{ch:Ldyn}
  16546. \index{subject}{dynamic typing}
  16547. \setcounter{footnote}{0}
  16548. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16549. typed language that is a subset of \racket{Racket}\python{Python}. The
  16550. focus on dynamic typing is in contrast to the previous chapters, which
  16551. have studied the compilation of statically typed languages. In
  16552. dynamically typed languages such as \LangDyn{}, a particular
  16553. expression may produce a value of a different type each time it is
  16554. executed. Consider the following example with a conditional \code{if}
  16555. expression that may return a Boolean or an integer depending on the
  16556. input to the program:
  16557. % part of dynamic_test_25.rkt
  16558. {\if\edition\racketEd
  16559. \begin{lstlisting}
  16560. (not (if (eq? (read) 1) #f 0))
  16561. \end{lstlisting}
  16562. \fi}
  16563. {\if\edition\pythonEd
  16564. \begin{lstlisting}
  16565. not (False if input_int() == 1 else 0)
  16566. \end{lstlisting}
  16567. \fi}
  16568. Languages that allow expressions to produce different kinds of values
  16569. are called \emph{polymorphic}, a word composed of the Greek roots
  16570. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16571. There are several kinds of polymorphism in programming languages, such as
  16572. subtype polymorphism and parametric polymorphism
  16573. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16574. study in this chapter does not have a special name; it is the kind
  16575. that arises in dynamically typed languages.
  16576. Another characteristic of dynamically typed languages is that
  16577. their primitive operations, such as \code{not}, are often defined to operate
  16578. on many different types of values. In fact, in
  16579. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16580. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16581. given anything else it returns \FALSE{}.
  16582. Furthermore, even when primitive operations restrict their inputs to
  16583. values of a certain type, this restriction is enforced at runtime
  16584. instead of during compilation. For example, the tuple read
  16585. operation
  16586. \racket{\code{(vector-ref \#t 0)}}
  16587. \python{\code{True[0]}}
  16588. results in a runtime error because the first argument must
  16589. be a tuple, not a Boolean.
  16590. \section{The \LangDyn{} Language}
  16591. \newcommand{\LdynGrammarRacket}{
  16592. \begin{array}{rcl}
  16593. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16594. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16595. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16596. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16597. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16598. \end{array}
  16599. }
  16600. \newcommand{\LdynASTRacket}{
  16601. \begin{array}{lcl}
  16602. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16603. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16604. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16605. \end{array}
  16606. }
  16607. \begin{figure}[tp]
  16608. \centering
  16609. \begin{tcolorbox}[colback=white]
  16610. \small
  16611. {\if\edition\racketEd
  16612. \[
  16613. \begin{array}{l}
  16614. \gray{\LintGrammarRacket{}} \\ \hline
  16615. \gray{\LvarGrammarRacket{}} \\ \hline
  16616. \gray{\LifGrammarRacket{}} \\ \hline
  16617. \gray{\LwhileGrammarRacket} \\ \hline
  16618. \gray{\LtupGrammarRacket} \\ \hline
  16619. \LdynGrammarRacket \\
  16620. \begin{array}{rcl}
  16621. \LangDynM{} &::=& \Def\ldots\; \Exp
  16622. \end{array}
  16623. \end{array}
  16624. \]
  16625. \fi}
  16626. {\if\edition\pythonEd
  16627. \[
  16628. \begin{array}{rcl}
  16629. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16630. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16631. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16632. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16633. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16634. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16635. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16636. \MID \CLEN{\Exp} \\
  16637. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16638. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16639. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16640. \MID \Var\mathop{\key{=}}\Exp \\
  16641. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16642. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16643. &\MID& \CRETURN{\Exp} \\
  16644. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16645. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16646. \end{array}
  16647. \]
  16648. \fi}
  16649. \end{tcolorbox}
  16650. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16651. \label{fig:r7-concrete-syntax}
  16652. \end{figure}
  16653. \begin{figure}[tp]
  16654. \centering
  16655. \begin{tcolorbox}[colback=white]
  16656. \small
  16657. {\if\edition\racketEd
  16658. \[
  16659. \begin{array}{l}
  16660. \gray{\LintASTRacket{}} \\ \hline
  16661. \gray{\LvarASTRacket{}} \\ \hline
  16662. \gray{\LifASTRacket{}} \\ \hline
  16663. \gray{\LwhileASTRacket} \\ \hline
  16664. \gray{\LtupASTRacket} \\ \hline
  16665. \LdynASTRacket \\
  16666. \begin{array}{lcl}
  16667. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16668. \end{array}
  16669. \end{array}
  16670. \]
  16671. \fi}
  16672. {\if\edition\pythonEd
  16673. \[
  16674. \begin{array}{rcl}
  16675. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16676. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16677. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16678. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16679. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16680. &\MID & \code{Is()} \\
  16681. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16682. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16683. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16684. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16685. \MID \VAR{\Var{}} \\
  16686. &\MID& \BOOL{\itm{bool}}
  16687. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16688. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16689. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16690. &\MID& \LEN{\Exp} \\
  16691. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16692. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16693. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16694. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16695. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16696. &\MID& \RETURN{\Exp} \\
  16697. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16698. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16699. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16700. \end{array}
  16701. \]
  16702. \fi}
  16703. \end{tcolorbox}
  16704. \caption{The abstract syntax of \LangDyn{}.}
  16705. \label{fig:r7-syntax}
  16706. \end{figure}
  16707. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16708. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16709. %
  16710. There is no type checker for \LangDyn{} because it checks types only
  16711. at runtime.
  16712. The definitional interpreter for \LangDyn{} is presented in
  16713. \racket{figure~\ref{fig:interp-Ldyn}}
  16714. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16715. and definitions of its auxiliary functions are shown in
  16716. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16717. \INT{n}. Instead of simply returning the integer \code{n} (as
  16718. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16719. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16720. value} that combines an underlying value with a tag that identifies
  16721. what kind of value it is. We define the following \racket{struct}\python{class}
  16722. to represent tagged values:
  16723. %
  16724. {\if\edition\racketEd
  16725. \begin{lstlisting}
  16726. (struct Tagged (value tag) #:transparent)
  16727. \end{lstlisting}
  16728. \fi}
  16729. {\if\edition\pythonEd
  16730. \begin{minipage}{\textwidth}
  16731. \begin{lstlisting}
  16732. @dataclass(eq=True)
  16733. class Tagged(Value):
  16734. value : Value
  16735. tag : str
  16736. def __str__(self):
  16737. return str(self.value)
  16738. \end{lstlisting}
  16739. \end{minipage}
  16740. \fi}
  16741. %
  16742. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16743. \code{Vector}, and \code{Procedure}.}
  16744. %
  16745. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16746. \code{'tuple'}, and \code{'function'}.}
  16747. %
  16748. Tags are closely related to types but do not always capture all the
  16749. information that a type does.
  16750. %
  16751. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16752. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16753. Any)} is tagged with \code{Procedure}.}
  16754. %
  16755. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16756. is tagged with \code{'tuple'} and a function of type
  16757. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16758. is tagged with \code{'function'}.}
  16759. Next consider the match case for accessing the element of a tuple.
  16760. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16761. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16762. argument is a tuple and the second is an integer.
  16763. \racket{
  16764. If they are not, a \code{trapped-error} is raised. Recall from
  16765. section~\ref{sec:interp_Lint} that when a definition interpreter
  16766. raises a \code{trapped-error} error, the compiled code must also
  16767. signal an error by exiting with return code \code{255}. A
  16768. \code{trapped-error} is also raised if the index is not less than the
  16769. length of the vector.
  16770. }
  16771. %
  16772. \python{If they are not, an exception is raised. The compiled code
  16773. must also signal an error by exiting with return code \code{255}. A
  16774. exception is also raised if the index is not less than the length of the
  16775. tuple or if it is negative.}
  16776. \begin{figure}[tbp]
  16777. \begin{tcolorbox}[colback=white]
  16778. {\if\edition\racketEd
  16779. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16780. (define ((interp-Ldyn-exp env) ast)
  16781. (define recur (interp-Ldyn-exp env))
  16782. (match ast
  16783. [(Var x) (dict-ref env x)]
  16784. [(Int n) (Tagged n 'Integer)]
  16785. [(Bool b) (Tagged b 'Boolean)]
  16786. [(Lambda xs rt body)
  16787. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16788. [(Prim 'vector es)
  16789. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16790. [(Prim 'vector-ref (list e1 e2))
  16791. (define vec (recur e1)) (define i (recur e2))
  16792. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16793. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16794. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16795. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16796. [(Prim 'vector-set! (list e1 e2 e3))
  16797. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16798. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16799. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16800. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16801. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16802. (Tagged (void) 'Void)]
  16803. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16804. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16805. [(Prim 'or (list e1 e2))
  16806. (define v1 (recur e1))
  16807. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16808. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16809. [(Prim op (list e1))
  16810. #:when (set-member? type-predicates op)
  16811. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16812. [(Prim op es)
  16813. (define args (map recur es))
  16814. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16815. (unless (for/or ([expected-tags (op-tags op)])
  16816. (equal? expected-tags tags))
  16817. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16818. (tag-value
  16819. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16820. [(If q t f)
  16821. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16822. [(Apply f es)
  16823. (define new-f (recur f)) (define args (map recur es))
  16824. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16825. (match f-val
  16826. [`(function ,xs ,body ,lam-env)
  16827. (unless (eq? (length xs) (length args))
  16828. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16829. (define new-env (append (map cons xs args) lam-env))
  16830. ((interp-Ldyn-exp new-env) body)]
  16831. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16832. \end{lstlisting}
  16833. \fi}
  16834. {\if\edition\pythonEd
  16835. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16836. class InterpLdyn(InterpLlambda):
  16837. def interp_exp(self, e, env):
  16838. match e:
  16839. case Constant(n):
  16840. return self.tag(super().interp_exp(e, env))
  16841. case Tuple(es, Load()):
  16842. return self.tag(super().interp_exp(e, env))
  16843. case Lambda(params, body):
  16844. return self.tag(super().interp_exp(e, env))
  16845. case Call(Name('input_int'), []):
  16846. return self.tag(super().interp_exp(e, env))
  16847. case BinOp(left, Add(), right):
  16848. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16849. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16850. case BinOp(left, Sub(), right):
  16851. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16852. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16853. case UnaryOp(USub(), e1):
  16854. v = self.interp_exp(e1, env)
  16855. return self.tag(- self.untag(v, 'int', e))
  16856. case IfExp(test, body, orelse):
  16857. v = self.interp_exp(test, env)
  16858. if self.untag(v, 'bool', e):
  16859. return self.interp_exp(body, env)
  16860. else:
  16861. return self.interp_exp(orelse, env)
  16862. case UnaryOp(Not(), e1):
  16863. v = self.interp_exp(e1, env)
  16864. return self.tag(not self.untag(v, 'bool', e))
  16865. case BoolOp(And(), 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.interp_exp(right, env)
  16870. else:
  16871. return self.tag(False)
  16872. case BoolOp(Or(), values):
  16873. left = values[0]; right = values[1]
  16874. l = self.interp_exp(left, env)
  16875. if self.untag(l, 'bool', e):
  16876. return self.tag(True)
  16877. else:
  16878. return self.interp_exp(right, env)
  16879. case Compare(left, [cmp], [right]):
  16880. l = self.interp_exp(left, env)
  16881. r = self.interp_exp(right, env)
  16882. if l.tag == r.tag:
  16883. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16884. else:
  16885. raise Exception('interp Compare unexpected '
  16886. + repr(l) + ' ' + repr(r))
  16887. case Subscript(tup, index, Load()):
  16888. t = self.interp_exp(tup, env)
  16889. n = self.interp_exp(index, env)
  16890. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16891. case Call(Name('len'), [tup]):
  16892. t = self.interp_exp(tup, env)
  16893. return self.tag(len(self.untag(t, 'tuple', e)))
  16894. case _:
  16895. return self.tag(super().interp_exp(e, env))
  16896. \end{lstlisting}
  16897. \fi}
  16898. \end{tcolorbox}
  16899. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16900. \label{fig:interp-Ldyn}
  16901. \end{figure}
  16902. {\if\edition\pythonEd
  16903. \begin{figure}[tbp]
  16904. \begin{tcolorbox}[colback=white]
  16905. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16906. class InterpLdyn(InterpLlambda):
  16907. def interp_stmts(self, ss, env):
  16908. if len(ss) == 0:
  16909. return
  16910. match ss[0]:
  16911. case If(test, body, orelse):
  16912. v = self.interp_exp(test, env)
  16913. if self.untag(v, 'bool', ss[0]):
  16914. return self.interp_stmts(body + ss[1:], env)
  16915. else:
  16916. return self.interp_stmts(orelse + ss[1:], env)
  16917. case While(test, body, []):
  16918. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16919. self.interp_stmts(body, env)
  16920. return self.interp_stmts(ss[1:], env)
  16921. case Assign([Subscript(tup, index)], value):
  16922. tup = self.interp_exp(tup, env)
  16923. index = self.interp_exp(index, env)
  16924. tup_v = self.untag(tup, 'tuple', ss[0])
  16925. index_v = self.untag(index, 'int', ss[0])
  16926. tup_v[index_v] = self.interp_exp(value, env)
  16927. return self.interp_stmts(ss[1:], env)
  16928. case FunctionDef(name, params, bod, dl, returns, comment):
  16929. ps = [x for (x,t) in params]
  16930. env[name] = self.tag(Function(name, ps, bod, env))
  16931. return self.interp_stmts(ss[1:], env)
  16932. case _:
  16933. return super().interp_stmts(ss, env)
  16934. \end{lstlisting}
  16935. \end{tcolorbox}
  16936. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16937. \label{fig:interp-Ldyn-2}
  16938. \end{figure}
  16939. \fi}
  16940. \begin{figure}[tbp]
  16941. \begin{tcolorbox}[colback=white]
  16942. {\if\edition\racketEd
  16943. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16944. (define (interp-op op)
  16945. (match op
  16946. ['+ fx+]
  16947. ['- fx-]
  16948. ['read read-fixnum]
  16949. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16950. ['< (lambda (v1 v2)
  16951. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16952. ['<= (lambda (v1 v2)
  16953. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16954. ['> (lambda (v1 v2)
  16955. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16956. ['>= (lambda (v1 v2)
  16957. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16958. ['boolean? boolean?]
  16959. ['integer? fixnum?]
  16960. ['void? void?]
  16961. ['vector? vector?]
  16962. ['vector-length vector-length]
  16963. ['procedure? (match-lambda
  16964. [`(functions ,xs ,body ,env) #t] [else #f])]
  16965. [else (error 'interp-op "unknown operator" op)]))
  16966. (define (op-tags op)
  16967. (match op
  16968. ['+ '((Integer Integer))]
  16969. ['- '((Integer Integer) (Integer))]
  16970. ['read '(())]
  16971. ['not '((Boolean))]
  16972. ['< '((Integer Integer))]
  16973. ['<= '((Integer Integer))]
  16974. ['> '((Integer Integer))]
  16975. ['>= '((Integer Integer))]
  16976. ['vector-length '((Vector))]))
  16977. (define type-predicates
  16978. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16979. (define (tag-value v)
  16980. (cond [(boolean? v) (Tagged v 'Boolean)]
  16981. [(fixnum? v) (Tagged v 'Integer)]
  16982. [(procedure? v) (Tagged v 'Procedure)]
  16983. [(vector? v) (Tagged v 'Vector)]
  16984. [(void? v) (Tagged v 'Void)]
  16985. [else (error 'tag-value "unidentified value ~a" v)]))
  16986. (define (check-tag val expected ast)
  16987. (define tag (Tagged-tag val))
  16988. (unless (eq? tag expected)
  16989. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16990. \end{lstlisting}
  16991. \fi}
  16992. {\if\edition\pythonEd
  16993. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16994. class InterpLdyn(InterpLlambda):
  16995. def tag(self, v):
  16996. if v is True or v is False:
  16997. return Tagged(v, 'bool')
  16998. elif isinstance(v, int):
  16999. return Tagged(v, 'int')
  17000. elif isinstance(v, Function):
  17001. return Tagged(v, 'function')
  17002. elif isinstance(v, tuple):
  17003. return Tagged(v, 'tuple')
  17004. elif isinstance(v, type(None)):
  17005. return Tagged(v, 'none')
  17006. else:
  17007. raise Exception('tag: unexpected ' + repr(v))
  17008. def untag(self, v, expected_tag, ast):
  17009. match v:
  17010. case Tagged(val, tag) if tag == expected_tag:
  17011. return val
  17012. case _:
  17013. raise Exception('expected Tagged value with '
  17014. + expected_tag + ', not ' + ' ' + repr(v))
  17015. def apply_fun(self, fun, args, e):
  17016. f = self.untag(fun, 'function', e)
  17017. return super().apply_fun(f, args, e)
  17018. \end{lstlisting}
  17019. \fi}
  17020. \end{tcolorbox}
  17021. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17022. \label{fig:interp-Ldyn-aux}
  17023. \end{figure}
  17024. \clearpage
  17025. \section{Representation of Tagged Values}
  17026. The interpreter for \LangDyn{} introduced a new kind of value: the
  17027. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17028. represent tagged values at the bit level. Because almost every
  17029. operation in \LangDyn{} involves manipulating tagged values, the
  17030. representation must be efficient. Recall that all our values are 64
  17031. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17032. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17033. $011$ for procedures, and $101$ for the void value\python{,
  17034. \key{None}}. We define the following auxiliary function for mapping
  17035. types to tag codes:
  17036. %
  17037. {\if\edition\racketEd
  17038. \begin{align*}
  17039. \itm{tagof}(\key{Integer}) &= 001 \\
  17040. \itm{tagof}(\key{Boolean}) &= 100 \\
  17041. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17042. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17043. \itm{tagof}(\key{Void}) &= 101
  17044. \end{align*}
  17045. \fi}
  17046. {\if\edition\pythonEd
  17047. \begin{align*}
  17048. \itm{tagof}(\key{IntType()}) &= 001 \\
  17049. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17050. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17051. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17052. \itm{tagof}(\key{type(None)}) &= 101
  17053. \end{align*}
  17054. \fi}
  17055. %
  17056. This stealing of 3 bits comes at some price: integers are now restricted
  17057. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17058. affect tuples and procedures because those values are addresses, and
  17059. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17060. they are always $000$. Thus, we do not lose information by overwriting
  17061. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17062. to recover the original address.
  17063. To make tagged values into first-class entities, we can give them a
  17064. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17065. operations such as \code{Inject} and \code{Project} for creating and
  17066. using them, yielding the statically typed \LangAny{} intermediate
  17067. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17068. section~\ref{sec:compile-r7}; in th next section we describe the
  17069. \LangAny{} language in greater detail.
  17070. \section{The \LangAny{} Language}
  17071. \label{sec:Rany-lang}
  17072. \newcommand{\LanyASTRacket}{
  17073. \begin{array}{lcl}
  17074. \Type &::= & \ANYTY \\
  17075. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17076. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17077. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17078. \itm{op} &::= & \code{any-vector-length}
  17079. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17080. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17081. \MID \code{procedure?} \MID \code{void?} \\
  17082. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17083. \end{array}
  17084. }
  17085. \newcommand{\LanyASTPython}{
  17086. \begin{array}{lcl}
  17087. \Type &::= & \key{AnyType()} \\
  17088. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17089. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17090. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17091. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17092. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17093. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17094. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17095. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17096. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17097. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17098. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17099. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17100. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17101. \end{array}
  17102. }
  17103. \begin{figure}[tp]
  17104. \centering
  17105. \begin{tcolorbox}[colback=white]
  17106. \small
  17107. {\if\edition\racketEd
  17108. \[
  17109. \begin{array}{l}
  17110. \gray{\LintOpAST} \\ \hline
  17111. \gray{\LvarASTRacket{}} \\ \hline
  17112. \gray{\LifASTRacket{}} \\ \hline
  17113. \gray{\LwhileASTRacket{}} \\ \hline
  17114. \gray{\LtupASTRacket{}} \\ \hline
  17115. \gray{\LfunASTRacket} \\ \hline
  17116. \gray{\LlambdaASTRacket} \\ \hline
  17117. \LanyASTRacket \\
  17118. \begin{array}{lcl}
  17119. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17120. \end{array}
  17121. \end{array}
  17122. \]
  17123. \fi}
  17124. {\if\edition\pythonEd
  17125. \[
  17126. \begin{array}{l}
  17127. \gray{\LintASTPython} \\ \hline
  17128. \gray{\LvarASTPython{}} \\ \hline
  17129. \gray{\LifASTPython{}} \\ \hline
  17130. \gray{\LwhileASTPython{}} \\ \hline
  17131. \gray{\LtupASTPython{}} \\ \hline
  17132. \gray{\LfunASTPython} \\ \hline
  17133. \gray{\LlambdaASTPython} \\ \hline
  17134. \LanyASTPython \\
  17135. \begin{array}{lcl}
  17136. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17137. \end{array}
  17138. \end{array}
  17139. \]
  17140. \fi}
  17141. \end{tcolorbox}
  17142. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17143. \label{fig:Lany-syntax}
  17144. \end{figure}
  17145. The definition of the abstract syntax of \LangAny{} is given in
  17146. figure~\ref{fig:Lany-syntax}.
  17147. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17148. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17149. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17150. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17151. converts the tagged value produced by expression $e$ into a value of
  17152. type $T$ or halts the program if the type tag does not match $T$.
  17153. %
  17154. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17155. restricted to be a flat type (the nonterminal $\FType$) which
  17156. simplifies the implementation and complies with the needs for
  17157. compiling \LangDyn{}.
  17158. The \racket{\code{any-vector}} operators
  17159. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17160. operations so that they can be applied to a value of type
  17161. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17162. tuple operations in that the index is not restricted to a literal
  17163. integer in the grammar but is allowed to be any expression.
  17164. \racket{The type predicates such as
  17165. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17166. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17167. the predicate and return {\FALSE} otherwise.}
  17168. The type checker for \LangAny{} is shown in
  17169. figure~\ref{fig:type-check-Lany}
  17170. %
  17171. \racket{ and uses the auxiliary functions presented in
  17172. figure~\ref{fig:type-check-Lany-aux}}.
  17173. %
  17174. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17175. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17176. \begin{figure}[btp]
  17177. \begin{tcolorbox}[colback=white]
  17178. {\if\edition\racketEd
  17179. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17180. (define type-check-Lany-class
  17181. (class type-check-Llambda-class
  17182. (super-new)
  17183. (inherit check-type-equal?)
  17184. (define/override (type-check-exp env)
  17185. (lambda (e)
  17186. (define recur (type-check-exp env))
  17187. (match e
  17188. [(Inject e1 ty)
  17189. (unless (flat-ty? ty)
  17190. (error 'type-check "may only inject from flat type, not ~a" ty))
  17191. (define-values (new-e1 e-ty) (recur e1))
  17192. (check-type-equal? e-ty ty e)
  17193. (values (Inject new-e1 ty) 'Any)]
  17194. [(Project e1 ty)
  17195. (unless (flat-ty? ty)
  17196. (error 'type-check "may only project to flat type, not ~a" ty))
  17197. (define-values (new-e1 e-ty) (recur e1))
  17198. (check-type-equal? e-ty 'Any e)
  17199. (values (Project new-e1 ty) ty)]
  17200. [(Prim 'any-vector-length (list e1))
  17201. (define-values (e1^ t1) (recur e1))
  17202. (check-type-equal? t1 'Any e)
  17203. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17204. [(Prim 'any-vector-ref (list e1 e2))
  17205. (define-values (e1^ t1) (recur e1))
  17206. (define-values (e2^ t2) (recur e2))
  17207. (check-type-equal? t1 'Any e)
  17208. (check-type-equal? t2 'Integer e)
  17209. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17210. [(Prim 'any-vector-set! (list e1 e2 e3))
  17211. (define-values (e1^ t1) (recur e1))
  17212. (define-values (e2^ t2) (recur e2))
  17213. (define-values (e3^ t3) (recur e3))
  17214. (check-type-equal? t1 'Any e)
  17215. (check-type-equal? t2 'Integer e)
  17216. (check-type-equal? t3 'Any e)
  17217. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17218. [(Prim pred (list e1))
  17219. #:when (set-member? (type-predicates) pred)
  17220. (define-values (new-e1 e-ty) (recur e1))
  17221. (check-type-equal? e-ty 'Any e)
  17222. (values (Prim pred (list new-e1)) 'Boolean)]
  17223. [(Prim 'eq? (list arg1 arg2))
  17224. (define-values (e1 t1) (recur arg1))
  17225. (define-values (e2 t2) (recur arg2))
  17226. (match* (t1 t2)
  17227. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17228. [(other wise) (check-type-equal? t1 t2 e)])
  17229. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17230. [else ((super type-check-exp env) e)])))
  17231. ))
  17232. \end{lstlisting}
  17233. \fi}
  17234. {\if\edition\pythonEd
  17235. \begin{lstlisting}
  17236. class TypeCheckLany(TypeCheckLlambda):
  17237. def type_check_exp(self, e, env):
  17238. match e:
  17239. case Inject(value, typ):
  17240. self.check_exp(value, typ, env)
  17241. return AnyType()
  17242. case Project(value, typ):
  17243. self.check_exp(value, AnyType(), env)
  17244. return typ
  17245. case Call(Name('any_tuple_load'), [tup, index]):
  17246. self.check_exp(tup, AnyType(), env)
  17247. self.check_exp(index, IntType(), env)
  17248. return AnyType()
  17249. case Call(Name('any_len'), [tup]):
  17250. self.check_exp(tup, AnyType(), env)
  17251. return IntType()
  17252. case Call(Name('arity'), [fun]):
  17253. ty = self.type_check_exp(fun, env)
  17254. match ty:
  17255. case FunctionType(ps, rt):
  17256. return IntType()
  17257. case TupleType([FunctionType(ps,rs)]):
  17258. return IntType()
  17259. case _:
  17260. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17261. case Call(Name('make_any'), [value, tag]):
  17262. self.type_check_exp(value, env)
  17263. self.check_exp(tag, IntType(), env)
  17264. return AnyType()
  17265. case AnnLambda(params, returns, body):
  17266. new_env = {x:t for (x,t) in env.items()}
  17267. for (x,t) in params:
  17268. new_env[x] = t
  17269. return_t = self.type_check_exp(body, new_env)
  17270. self.check_type_equal(returns, return_t, e)
  17271. return FunctionType([t for (x,t) in params], return_t)
  17272. case _:
  17273. return super().type_check_exp(e, env)
  17274. \end{lstlisting}
  17275. \fi}
  17276. \end{tcolorbox}
  17277. \caption{Type checker for the \LangAny{} language.}
  17278. \label{fig:type-check-Lany}
  17279. \end{figure}
  17280. {\if\edition\racketEd
  17281. \begin{figure}[tbp]
  17282. \begin{tcolorbox}[colback=white]
  17283. \begin{lstlisting}
  17284. (define/override (operator-types)
  17285. (append
  17286. '((integer? . ((Any) . Boolean))
  17287. (vector? . ((Any) . Boolean))
  17288. (procedure? . ((Any) . Boolean))
  17289. (void? . ((Any) . Boolean)))
  17290. (super operator-types)))
  17291. (define/public (type-predicates)
  17292. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17293. (define/public (flat-ty? ty)
  17294. (match ty
  17295. [(or `Integer `Boolean `Void) #t]
  17296. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17297. [`(,ts ... -> ,rt)
  17298. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17299. [else #f]))
  17300. \end{lstlisting}
  17301. \end{tcolorbox}
  17302. \caption{Auxiliary methods for type checking \LangAny{}.}
  17303. \label{fig:type-check-Lany-aux}
  17304. \end{figure}
  17305. \fi}
  17306. \begin{figure}[btp]
  17307. \begin{tcolorbox}[colback=white]
  17308. {\if\edition\racketEd
  17309. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17310. (define interp-Lany-class
  17311. (class interp-Llambda-class
  17312. (super-new)
  17313. (define/override (interp-op op)
  17314. (match op
  17315. ['boolean? (match-lambda
  17316. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17317. [else #f])]
  17318. ['integer? (match-lambda
  17319. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17320. [else #f])]
  17321. ['vector? (match-lambda
  17322. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17323. [else #f])]
  17324. ['procedure? (match-lambda
  17325. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17326. [else #f])]
  17327. ['eq? (match-lambda*
  17328. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17329. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17330. [ls (apply (super interp-op op) ls)])]
  17331. ['any-vector-ref (lambda (v i)
  17332. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17333. ['any-vector-set! (lambda (v i a)
  17334. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17335. ['any-vector-length (lambda (v)
  17336. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17337. [else (super interp-op op)]))
  17338. (define/override ((interp-exp env) e)
  17339. (define recur (interp-exp env))
  17340. (match e
  17341. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17342. [(Project e ty2) (apply-project (recur e) ty2)]
  17343. [else ((super interp-exp env) e)]))
  17344. ))
  17345. (define (interp-Lany p)
  17346. (send (new interp-Lany-class) interp-program p))
  17347. \end{lstlisting}
  17348. \fi}
  17349. {\if\edition\pythonEd
  17350. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17351. class InterpLany(InterpLlambda):
  17352. def interp_exp(self, e, env):
  17353. match e:
  17354. case Inject(value, typ):
  17355. v = self.interp_exp(value, env)
  17356. return Tagged(v, self.type_to_tag(typ))
  17357. case Project(value, typ):
  17358. v = self.interp_exp(value, env)
  17359. match v:
  17360. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17361. return val
  17362. case _:
  17363. raise Exception('interp project to ' + repr(typ)
  17364. + ' unexpected ' + repr(v))
  17365. case Call(Name('any_tuple_load'), [tup, index]):
  17366. tv = self.interp_exp(tup, env)
  17367. n = self.interp_exp(index, env)
  17368. match tv:
  17369. case Tagged(v, tag):
  17370. return v[n]
  17371. case _:
  17372. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17373. case Call(Name('any_len'), [value]):
  17374. v = self.interp_exp(value, env)
  17375. match v:
  17376. case Tagged(value, tag):
  17377. return len(value)
  17378. case _:
  17379. raise Exception('interp any_len unexpected ' + repr(v))
  17380. case Call(Name('arity'), [fun]):
  17381. f = self.interp_exp(fun, env)
  17382. return self.arity(f)
  17383. case _:
  17384. return super().interp_exp(e, env)
  17385. \end{lstlisting}
  17386. \fi}
  17387. \end{tcolorbox}
  17388. \caption{Interpreter for \LangAny{}.}
  17389. \label{fig:interp-Lany}
  17390. \end{figure}
  17391. \begin{figure}[tbp]
  17392. \begin{tcolorbox}[colback=white]
  17393. {\if\edition\racketEd
  17394. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17395. (define/public (apply-inject v tg) (Tagged v tg))
  17396. (define/public (apply-project v ty2)
  17397. (define tag2 (any-tag ty2))
  17398. (match v
  17399. [(Tagged v1 tag1)
  17400. (cond
  17401. [(eq? tag1 tag2)
  17402. (match ty2
  17403. [`(Vector ,ts ...)
  17404. (define l1 ((interp-op 'vector-length) v1))
  17405. (cond
  17406. [(eq? l1 (length ts)) v1]
  17407. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17408. l1 (length ts))])]
  17409. [`(,ts ... -> ,rt)
  17410. (match v1
  17411. [`(function ,xs ,body ,env)
  17412. (cond [(eq? (length xs) (length ts)) v1]
  17413. [else
  17414. (error 'apply-project "arity mismatch ~a != ~a"
  17415. (length xs) (length ts))])]
  17416. [else (error 'apply-project "expected function not ~a" v1)])]
  17417. [else v1])]
  17418. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17419. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17420. \end{lstlisting}
  17421. \fi}
  17422. {\if\edition\pythonEd
  17423. \begin{lstlisting}
  17424. class InterpLany(InterpLlambda):
  17425. def type_to_tag(self, typ):
  17426. match typ:
  17427. case FunctionType(params, rt):
  17428. return 'function'
  17429. case TupleType(fields):
  17430. return 'tuple'
  17431. case t if t == int:
  17432. return 'int'
  17433. case t if t == bool:
  17434. return 'bool'
  17435. case IntType():
  17436. return 'int'
  17437. case BoolType():
  17438. return 'int'
  17439. case _:
  17440. raise Exception('type_to_tag unexpected ' + repr(typ))
  17441. def arity(self, v):
  17442. match v:
  17443. case Function(name, params, body, env):
  17444. return len(params)
  17445. case ClosureTuple(args, arity):
  17446. return arity
  17447. case _:
  17448. raise Exception('Lany arity unexpected ' + repr(v))
  17449. \end{lstlisting}
  17450. \fi}
  17451. \end{tcolorbox}
  17452. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17453. \label{fig:interp-Lany-aux}
  17454. \end{figure}
  17455. \clearpage
  17456. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17457. \label{sec:compile-r7}
  17458. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17459. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17460. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17461. is that given any subexpression $e$ in the \LangDyn{} program, the
  17462. pass will produce an expression $e'$ in \LangAny{} that has type
  17463. \ANYTY{}. For example, the first row in
  17464. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17465. \TRUE{}, which must be injected to produce an expression of type
  17466. \ANYTY{}.
  17467. %
  17468. The compilation of addition is shown in the second row of
  17469. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17470. representative of many primitive operations: the arguments have type
  17471. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17472. be performed.
  17473. The compilation of \key{lambda} (third row of
  17474. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17475. produce type annotations: we simply use \ANYTY{}.
  17476. %
  17477. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17478. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17479. this pass has to account for some differences in behavior between
  17480. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17481. permissive than \LangAny{} regarding what kind of values can be used
  17482. in various places. For example, the condition of an \key{if} does
  17483. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17484. of the same type (in that case the result is \code{\#f}).}
  17485. \begin{figure}[btp]
  17486. \centering
  17487. \begin{tcolorbox}[colback=white]
  17488. {\if\edition\racketEd
  17489. \begin{tabular}{lll}
  17490. \begin{minipage}{0.27\textwidth}
  17491. \begin{lstlisting}
  17492. #t
  17493. \end{lstlisting}
  17494. \end{minipage}
  17495. &
  17496. $\Rightarrow$
  17497. &
  17498. \begin{minipage}{0.65\textwidth}
  17499. \begin{lstlisting}
  17500. (inject #t Boolean)
  17501. \end{lstlisting}
  17502. \end{minipage}
  17503. \\[2ex]\hline
  17504. \begin{minipage}{0.27\textwidth}
  17505. \begin{lstlisting}
  17506. (+ |$e_1$| |$e_2$|)
  17507. \end{lstlisting}
  17508. \end{minipage}
  17509. &
  17510. $\Rightarrow$
  17511. &
  17512. \begin{minipage}{0.65\textwidth}
  17513. \begin{lstlisting}
  17514. (inject
  17515. (+ (project |$e'_1$| Integer)
  17516. (project |$e'_2$| Integer))
  17517. Integer)
  17518. \end{lstlisting}
  17519. \end{minipage}
  17520. \\[2ex]\hline
  17521. \begin{minipage}{0.27\textwidth}
  17522. \begin{lstlisting}
  17523. (lambda (|$x_1 \ldots$|) |$e$|)
  17524. \end{lstlisting}
  17525. \end{minipage}
  17526. &
  17527. $\Rightarrow$
  17528. &
  17529. \begin{minipage}{0.65\textwidth}
  17530. \begin{lstlisting}
  17531. (inject
  17532. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17533. (Any|$\ldots$|Any -> Any))
  17534. \end{lstlisting}
  17535. \end{minipage}
  17536. \\[2ex]\hline
  17537. \begin{minipage}{0.27\textwidth}
  17538. \begin{lstlisting}
  17539. (|$e_0$| |$e_1 \ldots e_n$|)
  17540. \end{lstlisting}
  17541. \end{minipage}
  17542. &
  17543. $\Rightarrow$
  17544. &
  17545. \begin{minipage}{0.65\textwidth}
  17546. \begin{lstlisting}
  17547. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17548. \end{lstlisting}
  17549. \end{minipage}
  17550. \\[2ex]\hline
  17551. \begin{minipage}{0.27\textwidth}
  17552. \begin{lstlisting}
  17553. (vector-ref |$e_1$| |$e_2$|)
  17554. \end{lstlisting}
  17555. \end{minipage}
  17556. &
  17557. $\Rightarrow$
  17558. &
  17559. \begin{minipage}{0.65\textwidth}
  17560. \begin{lstlisting}
  17561. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17562. \end{lstlisting}
  17563. \end{minipage}
  17564. \\[2ex]\hline
  17565. \begin{minipage}{0.27\textwidth}
  17566. \begin{lstlisting}
  17567. (if |$e_1$| |$e_2$| |$e_3$|)
  17568. \end{lstlisting}
  17569. \end{minipage}
  17570. &
  17571. $\Rightarrow$
  17572. &
  17573. \begin{minipage}{0.65\textwidth}
  17574. \begin{lstlisting}
  17575. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17576. \end{lstlisting}
  17577. \end{minipage}
  17578. \\[2ex]\hline
  17579. \begin{minipage}{0.27\textwidth}
  17580. \begin{lstlisting}
  17581. (eq? |$e_1$| |$e_2$|)
  17582. \end{lstlisting}
  17583. \end{minipage}
  17584. &
  17585. $\Rightarrow$
  17586. &
  17587. \begin{minipage}{0.65\textwidth}
  17588. \begin{lstlisting}
  17589. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17590. \end{lstlisting}
  17591. \end{minipage}
  17592. \\[2ex]\hline
  17593. \begin{minipage}{0.27\textwidth}
  17594. \begin{lstlisting}
  17595. (not |$e_1$|)
  17596. \end{lstlisting}
  17597. \end{minipage}
  17598. &
  17599. $\Rightarrow$
  17600. &
  17601. \begin{minipage}{0.65\textwidth}
  17602. \begin{lstlisting}
  17603. (if (eq? |$e'_1$| (inject #f Boolean))
  17604. (inject #t Boolean) (inject #f Boolean))
  17605. \end{lstlisting}
  17606. \end{minipage}
  17607. \end{tabular}
  17608. \fi}
  17609. {\if\edition\pythonEd
  17610. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17611. \begin{minipage}{0.23\textwidth}
  17612. \begin{lstlisting}
  17613. True
  17614. \end{lstlisting}
  17615. \end{minipage}
  17616. &
  17617. $\Rightarrow$
  17618. &
  17619. \begin{minipage}{0.7\textwidth}
  17620. \begin{lstlisting}
  17621. Inject(True, BoolType())
  17622. \end{lstlisting}
  17623. \end{minipage}
  17624. \\[2ex]\hline
  17625. \begin{minipage}{0.23\textwidth}
  17626. \begin{lstlisting}
  17627. |$e_1$| + |$e_2$|
  17628. \end{lstlisting}
  17629. \end{minipage}
  17630. &
  17631. $\Rightarrow$
  17632. &
  17633. \begin{minipage}{0.7\textwidth}
  17634. \begin{lstlisting}
  17635. Inject(Project(|$e'_1$|, IntType())
  17636. + Project(|$e'_2$|, IntType()),
  17637. IntType())
  17638. \end{lstlisting}
  17639. \end{minipage}
  17640. \\[2ex]\hline
  17641. \begin{minipage}{0.23\textwidth}
  17642. \begin{lstlisting}
  17643. lambda |$x_1 \ldots$|: |$e$|
  17644. \end{lstlisting}
  17645. \end{minipage}
  17646. &
  17647. $\Rightarrow$
  17648. &
  17649. \begin{minipage}{0.7\textwidth}
  17650. \begin{lstlisting}
  17651. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17652. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17653. \end{lstlisting}
  17654. \end{minipage}
  17655. \\[2ex]\hline
  17656. \begin{minipage}{0.23\textwidth}
  17657. \begin{lstlisting}
  17658. |$e_0$|(|$e_1 \ldots e_n$|)
  17659. \end{lstlisting}
  17660. \end{minipage}
  17661. &
  17662. $\Rightarrow$
  17663. &
  17664. \begin{minipage}{0.7\textwidth}
  17665. \begin{lstlisting}
  17666. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17667. AnyType())), |$e'_1, \ldots, e'_n$|)
  17668. \end{lstlisting}
  17669. \end{minipage}
  17670. \\[2ex]\hline
  17671. \begin{minipage}{0.23\textwidth}
  17672. \begin{lstlisting}
  17673. |$e_1$|[|$e_2$|]
  17674. \end{lstlisting}
  17675. \end{minipage}
  17676. &
  17677. $\Rightarrow$
  17678. &
  17679. \begin{minipage}{0.7\textwidth}
  17680. \begin{lstlisting}
  17681. Call(Name('any_tuple_load'),
  17682. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17683. \end{lstlisting}
  17684. \end{minipage}
  17685. %% \begin{minipage}{0.23\textwidth}
  17686. %% \begin{lstlisting}
  17687. %% |$e_2$| if |$e_1$| else |$e_3$|
  17688. %% \end{lstlisting}
  17689. %% \end{minipage}
  17690. %% &
  17691. %% $\Rightarrow$
  17692. %% &
  17693. %% \begin{minipage}{0.7\textwidth}
  17694. %% \begin{lstlisting}
  17695. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17696. %% \end{lstlisting}
  17697. %% \end{minipage}
  17698. %% \\[2ex]\hline
  17699. %% \begin{minipage}{0.23\textwidth}
  17700. %% \begin{lstlisting}
  17701. %% (eq? |$e_1$| |$e_2$|)
  17702. %% \end{lstlisting}
  17703. %% \end{minipage}
  17704. %% &
  17705. %% $\Rightarrow$
  17706. %% &
  17707. %% \begin{minipage}{0.7\textwidth}
  17708. %% \begin{lstlisting}
  17709. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17710. %% \end{lstlisting}
  17711. %% \end{minipage}
  17712. %% \\[2ex]\hline
  17713. %% \begin{minipage}{0.23\textwidth}
  17714. %% \begin{lstlisting}
  17715. %% (not |$e_1$|)
  17716. %% \end{lstlisting}
  17717. %% \end{minipage}
  17718. %% &
  17719. %% $\Rightarrow$
  17720. %% &
  17721. %% \begin{minipage}{0.7\textwidth}
  17722. %% \begin{lstlisting}
  17723. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17724. %% (inject #t Boolean) (inject #f Boolean))
  17725. %% \end{lstlisting}
  17726. %% \end{minipage}
  17727. %% \\[2ex]\hline
  17728. \\\hline
  17729. \end{tabular}
  17730. \fi}
  17731. \end{tcolorbox}
  17732. \caption{Cast insertion}
  17733. \label{fig:compile-r7-Lany}
  17734. \end{figure}
  17735. \section{Reveal Casts}
  17736. \label{sec:reveal-casts-Lany}
  17737. % TODO: define R'_6
  17738. In the \code{reveal\_casts} pass, we recommend compiling
  17739. \code{Project} into a conditional expression that checks whether the
  17740. value's tag matches the target type; if it does, the value is
  17741. converted to a value of the target type by removing the tag; if it
  17742. does not, the program exits.
  17743. %
  17744. {\if\edition\racketEd
  17745. %
  17746. To perform these actions we need a new primitive operation,
  17747. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17748. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17749. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17750. underlying value from a tagged value. The \code{ValueOf} form
  17751. includes the type for the underlying value that is used by the type
  17752. checker.
  17753. %
  17754. \fi}
  17755. %
  17756. {\if\edition\pythonEd
  17757. %
  17758. To perform these actions we need two new AST classes: \code{TagOf} and
  17759. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17760. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17761. the underlying value from a tagged value. The \code{ValueOf}
  17762. operation includes the type for the underlying value which is used by
  17763. the type checker.
  17764. %
  17765. \fi}
  17766. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17767. \code{Project} can be translated as follows.
  17768. \begin{center}
  17769. \begin{minipage}{1.0\textwidth}
  17770. {\if\edition\racketEd
  17771. \begin{lstlisting}
  17772. (Project |$e$| |$\FType$|)
  17773. |$\Rightarrow$|
  17774. (Let |$\itm{tmp}$| |$e'$|
  17775. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17776. (Int |$\itm{tagof}(\FType)$|)))
  17777. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17778. (Exit)))
  17779. \end{lstlisting}
  17780. \fi}
  17781. {\if\edition\pythonEd
  17782. \begin{lstlisting}
  17783. Project(|$e$|, |$\FType$|)
  17784. |$\Rightarrow$|
  17785. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17786. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17787. [Constant(|$\itm{tagof}(\FType)$|)]),
  17788. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17789. Call(Name('exit'), [])))
  17790. \end{lstlisting}
  17791. \fi}
  17792. \end{minipage}
  17793. \end{center}
  17794. If the target type of the projection is a tuple or function type, then
  17795. there is a bit more work to do. For tuples, check that the length of
  17796. the tuple type matches the length of the tuple. For functions, check
  17797. that the number of parameters in the function type matches the
  17798. function's arity.
  17799. Regarding \code{Inject}, we recommend compiling it to a slightly
  17800. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17801. takes a tag instead of a type.
  17802. \begin{center}
  17803. \begin{minipage}{1.0\textwidth}
  17804. {\if\edition\racketEd
  17805. \begin{lstlisting}
  17806. (Inject |$e$| |$\FType$|)
  17807. |$\Rightarrow$|
  17808. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17809. \end{lstlisting}
  17810. \fi}
  17811. {\if\edition\pythonEd
  17812. \begin{lstlisting}
  17813. Inject(|$e$|, |$\FType$|)
  17814. |$\Rightarrow$|
  17815. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17816. \end{lstlisting}
  17817. \fi}
  17818. \end{minipage}
  17819. \end{center}
  17820. {\if\edition\pythonEd
  17821. %
  17822. The introduction of \code{make\_any} makes it difficult to use
  17823. bidirectional type checking because we no longer have an expected type
  17824. to use for type checking the expression $e'$. Thus, we run into
  17825. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17826. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17827. annotated lambda) whose parameters have type annotations and that
  17828. records the return type.
  17829. %
  17830. \fi}
  17831. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17832. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17833. translation of \code{Project}.}
  17834. {\if\edition\racketEd
  17835. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17836. combine the projection action with the vector operation. Also, the
  17837. read and write operations allow arbitrary expressions for the index, so
  17838. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17839. cannot guarantee that the index is within bounds. Thus, we insert code
  17840. to perform bounds checking at runtime. The translation for
  17841. \code{any-vector-ref} is as follows, and the other two operations are
  17842. translated in a similar way:
  17843. \begin{center}
  17844. \begin{minipage}{0.95\textwidth}
  17845. \begin{lstlisting}
  17846. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17847. |$\Rightarrow$|
  17848. (Let |$v$| |$e'_1$|
  17849. (Let |$i$| |$e'_2$|
  17850. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17851. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17852. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17853. (Exit))
  17854. (Exit))))
  17855. \end{lstlisting}
  17856. \end{minipage}
  17857. \end{center}
  17858. \fi}
  17859. %
  17860. {\if\edition\pythonEd
  17861. %
  17862. The \code{any\_tuple\_load} operation combines the projection action
  17863. with the load operation. Also, the load operation allows arbitrary
  17864. expressions for the index so the type checker for \LangAny{}
  17865. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17866. within bounds. Thus, we insert code to perform bounds checking at
  17867. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17868. \begin{lstlisting}
  17869. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17870. |$\Rightarrow$|
  17871. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17872. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17873. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17874. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17875. Call(Name('exit'), [])),
  17876. Call(Name('exit'), [])))
  17877. \end{lstlisting}
  17878. \fi}
  17879. {\if\edition\pythonEd
  17880. \section{Assignment Conversion}
  17881. \label{sec:convert-assignments-Lany}
  17882. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17883. \code{AnnLambda} AST classes.
  17884. \section{Closure Conversion}
  17885. \label{sec:closure-conversion-Lany}
  17886. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17887. \code{AnnLambda} AST classes.
  17888. \fi}
  17889. \section{Remove Complex Operands}
  17890. \label{sec:rco-Lany}
  17891. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17892. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17893. %
  17894. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17895. complex expressions. Their subexpressions must be atomic.}
  17896. \section{Explicate Control and \LangCAny{}}
  17897. \label{sec:explicate-Lany}
  17898. The output of \code{explicate\_control} is the \LangCAny{} language,
  17899. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17900. %
  17901. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17902. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17903. note that the index argument of \code{vector-ref} and
  17904. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17905. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17906. %
  17907. \python{
  17908. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17909. and \code{explicate\_pred} as appropriately to handle the new expressions
  17910. in \LangCAny{}.
  17911. }
  17912. \newcommand{\CanyASTPython}{
  17913. \begin{array}{lcl}
  17914. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17915. &\MID& \key{TagOf}\LP \Atm \RP
  17916. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17917. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17918. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17919. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17920. \end{array}
  17921. }
  17922. \newcommand{\CanyASTRacket}{
  17923. \begin{array}{lcl}
  17924. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17925. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17926. &\MID& \VALUEOF{\Atm}{\FType} \\
  17927. \Tail &::= & \LP\key{Exit}\RP
  17928. \end{array}
  17929. }
  17930. \begin{figure}[tp]
  17931. \begin{tcolorbox}[colback=white]
  17932. \small
  17933. {\if\edition\racketEd
  17934. \[
  17935. \begin{array}{l}
  17936. \gray{\CvarASTRacket} \\ \hline
  17937. \gray{\CifASTRacket} \\ \hline
  17938. \gray{\CloopASTRacket} \\ \hline
  17939. \gray{\CtupASTRacket} \\ \hline
  17940. \gray{\CfunASTRacket} \\ \hline
  17941. \gray{\ClambdaASTRacket} \\ \hline
  17942. \CanyASTRacket \\
  17943. \begin{array}{lcl}
  17944. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17945. \end{array}
  17946. \end{array}
  17947. \]
  17948. \fi}
  17949. {\if\edition\pythonEd
  17950. \[
  17951. \begin{array}{l}
  17952. \gray{\CifASTPython} \\ \hline
  17953. \gray{\CtupASTPython} \\ \hline
  17954. \gray{\CfunASTPython} \\ \hline
  17955. \gray{\ClambdaASTPython} \\ \hline
  17956. \CanyASTPython \\
  17957. \begin{array}{lcl}
  17958. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17959. \end{array}
  17960. \end{array}
  17961. \]
  17962. \fi}
  17963. \end{tcolorbox}
  17964. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17965. \label{fig:c5-syntax}
  17966. \end{figure}
  17967. \section{Select Instructions}
  17968. \label{sec:select-Lany}
  17969. In the \code{select\_instructions} pass, we translate the primitive
  17970. operations on the \ANYTY{} type to x86 instructions that manipulate
  17971. the three tag bits of the tagged value. In the following descriptions,
  17972. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17973. of translating $e$ into an x86 argument:
  17974. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17975. We recommend compiling the
  17976. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17977. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17978. shifts the destination to the left by the number of bits specified its
  17979. source argument (in this case three, the length of the tag), and it
  17980. preserves the sign of the integer. We use the \key{orq} instruction to
  17981. combine the tag and the value to form the tagged value. \\
  17982. %
  17983. {\if\edition\racketEd
  17984. \begin{lstlisting}
  17985. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17986. |$\Rightarrow$|
  17987. movq |$e'$|, |\itm{lhs'}|
  17988. salq $3, |\itm{lhs'}|
  17989. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17990. \end{lstlisting}
  17991. \fi}
  17992. %
  17993. {\if\edition\pythonEd
  17994. \begin{lstlisting}
  17995. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17996. |$\Rightarrow$|
  17997. movq |$e'$|, |\itm{lhs'}|
  17998. salq $3, |\itm{lhs'}|
  17999. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18000. \end{lstlisting}
  18001. \fi}
  18002. %
  18003. The instruction selection for tuples and procedures is different
  18004. because their is no need to shift them to the left. The rightmost 3
  18005. bits are already zeros, so we simply combine the value and the tag
  18006. using \key{orq}. \\
  18007. %
  18008. {\if\edition\racketEd
  18009. \begin{center}
  18010. \begin{minipage}{\textwidth}
  18011. \begin{lstlisting}
  18012. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18013. |$\Rightarrow$|
  18014. movq |$e'$|, |\itm{lhs'}|
  18015. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18016. \end{lstlisting}
  18017. \end{minipage}
  18018. \end{center}
  18019. \fi}
  18020. %
  18021. {\if\edition\pythonEd
  18022. \begin{lstlisting}
  18023. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18024. |$\Rightarrow$|
  18025. movq |$e'$|, |\itm{lhs'}|
  18026. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18027. \end{lstlisting}
  18028. \fi}
  18029. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18030. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18031. operation extracts the type tag from a value of type \ANYTY{}. The
  18032. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18033. bitwise-and of the value with $111$ ($7$ decimal).
  18034. %
  18035. {\if\edition\racketEd
  18036. \begin{lstlisting}
  18037. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18038. |$\Rightarrow$|
  18039. movq |$e'$|, |\itm{lhs'}|
  18040. andq $7, |\itm{lhs'}|
  18041. \end{lstlisting}
  18042. \fi}
  18043. %
  18044. {\if\edition\pythonEd
  18045. \begin{lstlisting}
  18046. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18047. |$\Rightarrow$|
  18048. movq |$e'$|, |\itm{lhs'}|
  18049. andq $7, |\itm{lhs'}|
  18050. \end{lstlisting}
  18051. \fi}
  18052. \paragraph{\code{ValueOf}}
  18053. The instructions for \key{ValueOf} also differ, depending on whether
  18054. the type $T$ is a pointer (tuple or function) or not (integer or
  18055. Boolean). The following shows the instruction selection for integers
  18056. and Booleans, in which we produce an untagged value by shifting it to
  18057. the right by 3 bits:
  18058. %
  18059. {\if\edition\racketEd
  18060. \begin{lstlisting}
  18061. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18062. |$\Rightarrow$|
  18063. movq |$e'$|, |\itm{lhs'}|
  18064. sarq $3, |\itm{lhs'}|
  18065. \end{lstlisting}
  18066. \fi}
  18067. %
  18068. {\if\edition\pythonEd
  18069. \begin{lstlisting}
  18070. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18071. |$\Rightarrow$|
  18072. movq |$e'$|, |\itm{lhs'}|
  18073. sarq $3, |\itm{lhs'}|
  18074. \end{lstlisting}
  18075. \fi}
  18076. %
  18077. In the case for tuples and procedures, we zero out the rightmost 3
  18078. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18079. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18080. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18081. Finally, we apply \code{andq} with the tagged value to get the desired
  18082. result.
  18083. %
  18084. {\if\edition\racketEd
  18085. \begin{lstlisting}
  18086. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18087. |$\Rightarrow$|
  18088. movq $|$-8$|, |\itm{lhs'}|
  18089. andq |$e'$|, |\itm{lhs'}|
  18090. \end{lstlisting}
  18091. \fi}
  18092. %
  18093. {\if\edition\pythonEd
  18094. \begin{lstlisting}
  18095. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18096. |$\Rightarrow$|
  18097. movq $|$-8$|, |\itm{lhs'}|
  18098. andq |$e'$|, |\itm{lhs'}|
  18099. \end{lstlisting}
  18100. \fi}
  18101. %% \paragraph{Type Predicates} We leave it to the reader to
  18102. %% devise a sequence of instructions to implement the type predicates
  18103. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18104. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18105. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18106. operation combines the effect of \code{ValueOf} with accessing the
  18107. length of a tuple from the tag stored at the zero index of the tuple.
  18108. {\if\edition\racketEd
  18109. \begin{lstlisting}
  18110. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18111. |$\Longrightarrow$|
  18112. movq $|$-8$|, %r11
  18113. andq |$e_1'$|, %r11
  18114. movq 0(%r11), %r11
  18115. andq $126, %r11
  18116. sarq $1, %r11
  18117. movq %r11, |$\itm{lhs'}$|
  18118. \end{lstlisting}
  18119. \fi}
  18120. {\if\edition\pythonEd
  18121. \begin{lstlisting}
  18122. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18123. |$\Longrightarrow$|
  18124. movq $|$-8$|, %r11
  18125. andq |$e_1'$|, %r11
  18126. movq 0(%r11), %r11
  18127. andq $126, %r11
  18128. sarq $1, %r11
  18129. movq %r11, |$\itm{lhs'}$|
  18130. \end{lstlisting}
  18131. \fi}
  18132. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18133. This operation combines the effect of \code{ValueOf} with reading an
  18134. element of the tuple (see
  18135. section~\ref{sec:select-instructions-gc}). However, the index may be
  18136. an arbitrary atom, so instead of computing the offset at compile time,
  18137. we must generate instructions to compute the offset at runtime as
  18138. follows. Note the use of the new instruction \code{imulq}.
  18139. \begin{center}
  18140. \begin{minipage}{0.96\textwidth}
  18141. {\if\edition\racketEd
  18142. \begin{lstlisting}
  18143. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18144. |$\Longrightarrow$|
  18145. movq |$\neg 111$|, %r11
  18146. andq |$e_1'$|, %r11
  18147. movq |$e_2'$|, %rax
  18148. addq $1, %rax
  18149. imulq $8, %rax
  18150. addq %rax, %r11
  18151. movq 0(%r11) |$\itm{lhs'}$|
  18152. \end{lstlisting}
  18153. \fi}
  18154. %
  18155. {\if\edition\pythonEd
  18156. \begin{lstlisting}
  18157. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18158. |$\Longrightarrow$|
  18159. movq $|$-8$|, %r11
  18160. andq |$e_1'$|, %r11
  18161. movq |$e_2'$|, %rax
  18162. addq $1, %rax
  18163. imulq $8, %rax
  18164. addq %rax, %r11
  18165. movq 0(%r11) |$\itm{lhs'}$|
  18166. \end{lstlisting}
  18167. \fi}
  18168. \end{minipage}
  18169. \end{center}
  18170. % $ pacify font lock
  18171. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18172. %% The code generation for
  18173. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18174. %% analogous to the above translation for reading from a tuple.
  18175. \section{Register Allocation for \LangAny{}}
  18176. \label{sec:register-allocation-Lany}
  18177. \index{subject}{register allocation}
  18178. There is an interesting interaction between tagged values and garbage
  18179. collection that has an impact on register allocation. A variable of
  18180. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18181. that needs to be inspected and copied during garbage collection. Thus,
  18182. we need to treat variables of type \ANYTY{} in a similar way to
  18183. variables of tuple type for purposes of register allocation,
  18184. with particular attention to the following:
  18185. \begin{itemize}
  18186. \item If a variable of type \ANYTY{} is live during a function call,
  18187. then it must be spilled. This can be accomplished by changing
  18188. \code{build\_interference} to mark all variables of type \ANYTY{}
  18189. that are live after a \code{callq} to be interfering with all the
  18190. registers.
  18191. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18192. the root stack instead of the normal procedure call stack.
  18193. \end{itemize}
  18194. Another concern regarding the root stack is that the garbage collector
  18195. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18196. tagged value that points to a tuple, and (3) a tagged value that is
  18197. not a tuple. We enable this differentiation by choosing not to use the
  18198. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18199. reserved for identifying plain old pointers to tuples. That way, if
  18200. one of the first three bits is set, then we have a tagged value and
  18201. inspecting the tag can differentiate between tuples ($010$) and the
  18202. other kinds of values.
  18203. %% \begin{exercise}\normalfont
  18204. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18205. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18206. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18207. %% compiler on these new programs and all of your previously created test
  18208. %% programs.
  18209. %% \end{exercise}
  18210. \begin{exercise}\normalfont\normalsize
  18211. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18212. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18213. by removing type annotations. Add five more test programs that
  18214. specifically rely on the language being dynamically typed. That is,
  18215. they should not be legal programs in a statically typed language, but
  18216. nevertheless they should be valid \LangDyn{} programs that run to
  18217. completion without error.
  18218. \end{exercise}
  18219. \begin{figure}[p]
  18220. \begin{tcolorbox}[colback=white]
  18221. {\if\edition\racketEd
  18222. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18223. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18224. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18225. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18226. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18227. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18228. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18229. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18230. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18231. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18232. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18233. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18234. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18235. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18236. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18237. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18238. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18239. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18240. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18241. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18242. \path[->,bend left=15] (Lfun) edge [above] node
  18243. {\ttfamily\footnotesize shrink} (Lfun-2);
  18244. \path[->,bend left=15] (Lfun-2) edge [above] node
  18245. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18246. \path[->,bend left=15] (Lfun-3) edge [above] node
  18247. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18248. \path[->,bend left=15] (Lfun-4) edge [left] node
  18249. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18250. \path[->,bend left=15] (Lfun-5) edge [below] node
  18251. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18252. \path[->,bend left=15] (Lfun-6) edge [below] node
  18253. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18254. \path[->,bend right=15] (Lfun-7) edge [above] node
  18255. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18256. \path[->,bend right=15] (F1-2) edge [right] node
  18257. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18258. \path[->,bend right=15] (F1-3) edge [below] node
  18259. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18260. \path[->,bend right=15] (F1-4) edge [below] node
  18261. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18262. \path[->,bend left=15] (F1-5) edge [above] node
  18263. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18264. \path[->,bend left=15] (F1-6) edge [below] node
  18265. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18266. \path[->,bend left=15] (C3-2) edge [right] node
  18267. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18268. \path[->,bend right=15] (x86-2) edge [right] node
  18269. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18270. \path[->,bend right=15] (x86-2-1) edge [below] node
  18271. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18272. \path[->,bend right=15] (x86-2-2) edge [right] node
  18273. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18274. \path[->,bend left=15] (x86-3) edge [above] node
  18275. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18276. \path[->,bend left=15] (x86-4) edge [right] node
  18277. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18278. \end{tikzpicture}
  18279. \fi}
  18280. {\if\edition\pythonEd
  18281. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18282. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18283. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18284. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18285. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18286. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18287. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18288. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18289. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18290. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18291. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18292. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18293. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18294. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18295. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18296. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18297. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18298. \path[->,bend left=15] (Lfun) edge [above] node
  18299. {\ttfamily\footnotesize shrink} (Lfun-2);
  18300. \path[->,bend left=15] (Lfun-2) edge [above] node
  18301. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18302. \path[->,bend left=15] (Lfun-3) edge [above] node
  18303. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18304. \path[->,bend left=15] (Lfun-4) edge [left] node
  18305. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18306. \path[->,bend left=15] (Lfun-5) edge [below] node
  18307. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18308. \path[->,bend right=15] (Lfun-6) edge [above] node
  18309. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18310. \path[->,bend right=15] (Lfun-7) edge [above] node
  18311. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18312. \path[->,bend right=15] (F1-2) edge [right] node
  18313. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18314. \path[->,bend right=15] (F1-3) edge [below] node
  18315. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18316. \path[->,bend left=15] (F1-5) edge [above] node
  18317. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18318. \path[->,bend left=15] (F1-6) edge [below] node
  18319. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18320. \path[->,bend right=15] (C3-2) edge [right] node
  18321. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18322. \path[->,bend right=15] (x86-2) edge [below] node
  18323. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18324. \path[->,bend right=15] (x86-3) edge [below] node
  18325. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18326. \path[->,bend left=15] (x86-4) edge [above] node
  18327. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18328. \end{tikzpicture}
  18329. \fi}
  18330. \end{tcolorbox}
  18331. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18332. \label{fig:Ldyn-passes}
  18333. \end{figure}
  18334. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18335. for the compilation of \LangDyn{}.
  18336. % Further Reading
  18337. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18338. %% {\if\edition\pythonEd
  18339. %% \chapter{Objects}
  18340. %% \label{ch:Lobject}
  18341. %% \index{subject}{objects}
  18342. %% \index{subject}{classes}
  18343. %% \setcounter{footnote}{0}
  18344. %% \fi}
  18345. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18346. \chapter{Gradual Typing}
  18347. \label{ch:Lgrad}
  18348. \index{subject}{gradual typing}
  18349. \setcounter{footnote}{0}
  18350. This chapter studies the language \LangGrad{}, in which the programmer
  18351. can choose between static and dynamic type checking in different parts
  18352. of a program, thereby mixing the statically typed \LangLam{} language
  18353. with the dynamically typed \LangDyn{}. There are several approaches to
  18354. mixing static and dynamic typing, including multilanguage
  18355. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18356. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18357. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18358. programmer controls the amount of static versus dynamic checking by
  18359. adding or removing type annotations on parameters and
  18360. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18361. The definition of the concrete syntax of \LangGrad{} is shown in
  18362. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  18363. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18364. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18365. annotations are optional, which is specified in the grammar using the
  18366. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18367. annotations are not optional, but we use the \CANYTY{} type when a type
  18368. annotation is absent.
  18369. %
  18370. Both the type checker and the interpreter for \LangGrad{} require some
  18371. interesting changes to enable gradual typing, which we discuss in the
  18372. next two sections.
  18373. \newcommand{\LgradGrammarRacket}{
  18374. \begin{array}{lcl}
  18375. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18376. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18377. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18378. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18379. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18380. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18381. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18382. \end{array}
  18383. }
  18384. \newcommand{\LgradASTRacket}{
  18385. \begin{array}{lcl}
  18386. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18387. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18388. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18389. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18390. \itm{op} &::=& \code{procedure-arity} \\
  18391. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18392. \end{array}
  18393. }
  18394. \newcommand{\LgradGrammarPython}{
  18395. \begin{array}{lcl}
  18396. \Type &::=& \key{Any}
  18397. \MID \key{int}
  18398. \MID \key{bool}
  18399. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18400. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18401. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18402. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18403. \MID \CARITY{\Exp} \\
  18404. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18405. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18406. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18407. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18408. \end{array}
  18409. }
  18410. \newcommand{\LgradASTPython}{
  18411. \begin{array}{lcl}
  18412. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18413. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18414. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18415. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18416. &\MID& \ARITY{\Exp} \\
  18417. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18418. \MID \RETURN{\Exp} \\
  18419. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18420. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18421. \end{array}
  18422. }
  18423. \begin{figure}[tp]
  18424. \centering
  18425. \begin{tcolorbox}[colback=white]
  18426. \small
  18427. {\if\edition\racketEd
  18428. \[
  18429. \begin{array}{l}
  18430. \gray{\LintGrammarRacket{}} \\ \hline
  18431. \gray{\LvarGrammarRacket{}} \\ \hline
  18432. \gray{\LifGrammarRacket{}} \\ \hline
  18433. \gray{\LwhileGrammarRacket} \\ \hline
  18434. \gray{\LtupGrammarRacket} \\ \hline
  18435. \LgradGrammarRacket \\
  18436. \begin{array}{lcl}
  18437. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18438. \end{array}
  18439. \end{array}
  18440. \]
  18441. \fi}
  18442. {\if\edition\pythonEd
  18443. \[
  18444. \begin{array}{l}
  18445. \gray{\LintGrammarPython{}} \\ \hline
  18446. \gray{\LvarGrammarPython{}} \\ \hline
  18447. \gray{\LifGrammarPython{}} \\ \hline
  18448. \gray{\LwhileGrammarPython} \\ \hline
  18449. \gray{\LtupGrammarPython} \\ \hline
  18450. \LgradGrammarPython \\
  18451. \begin{array}{lcl}
  18452. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18453. \end{array}
  18454. \end{array}
  18455. \]
  18456. \fi}
  18457. \end{tcolorbox}
  18458. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18459. \label{fig:Lgrad-concrete-syntax}
  18460. \end{figure}
  18461. \begin{figure}[tp]
  18462. \centering
  18463. \begin{tcolorbox}[colback=white]
  18464. \small
  18465. {\if\edition\racketEd
  18466. \[
  18467. \begin{array}{l}
  18468. \gray{\LintOpAST} \\ \hline
  18469. \gray{\LvarASTRacket{}} \\ \hline
  18470. \gray{\LifASTRacket{}} \\ \hline
  18471. \gray{\LwhileASTRacket{}} \\ \hline
  18472. \gray{\LtupASTRacket{}} \\ \hline
  18473. \LgradASTRacket \\
  18474. \begin{array}{lcl}
  18475. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18476. \end{array}
  18477. \end{array}
  18478. \]
  18479. \fi}
  18480. {\if\edition\pythonEd
  18481. \[
  18482. \begin{array}{l}
  18483. \gray{\LintASTPython{}} \\ \hline
  18484. \gray{\LvarASTPython{}} \\ \hline
  18485. \gray{\LifASTPython{}} \\ \hline
  18486. \gray{\LwhileASTPython} \\ \hline
  18487. \gray{\LtupASTPython} \\ \hline
  18488. \LgradASTPython \\
  18489. \begin{array}{lcl}
  18490. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18491. \end{array}
  18492. \end{array}
  18493. \]
  18494. \fi}
  18495. \end{tcolorbox}
  18496. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18497. \label{fig:Lgrad-syntax}
  18498. \end{figure}
  18499. % TODO: more road map -Jeremy
  18500. %\clearpage
  18501. \section{Type Checking \LangGrad{}}
  18502. \label{sec:gradual-type-check}
  18503. We begin by discussing the type checking of a partially typed variant
  18504. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18505. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18506. statically typed, so there is nothing special happening there with
  18507. respect to type checking. On the other hand, the \code{inc} function
  18508. does not have type annotations, so the type checker assigns the type
  18509. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18510. \code{+} operator inside \code{inc}. It expects both arguments to have
  18511. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18512. a gradually typed language, such differences are allowed so long as
  18513. the types are \emph{consistent}; that is, they are equal except in
  18514. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18515. is consistent with every other type. Figure~\ref{fig:consistent}
  18516. shows the definition of the
  18517. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18518. %
  18519. So the type checker allows the \code{+} operator to be applied
  18520. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18521. %
  18522. Next consider the call to the \code{map} function shown in
  18523. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18524. tuple. The \code{inc} function has type
  18525. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18526. but parameter \code{f} of \code{map} has type
  18527. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18528. The type checker for \LangGrad{} accepts this call because the two types are
  18529. consistent.
  18530. \begin{figure}[btp]
  18531. % gradual_test_9.rkt
  18532. \begin{tcolorbox}[colback=white]
  18533. {\if\edition\racketEd
  18534. \begin{lstlisting}
  18535. (define (map [f : (Integer -> Integer)]
  18536. [v : (Vector Integer Integer)])
  18537. : (Vector Integer Integer)
  18538. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18539. (define (inc x) (+ x 1))
  18540. (vector-ref (map inc (vector 0 41)) 1)
  18541. \end{lstlisting}
  18542. \fi}
  18543. {\if\edition\pythonEd
  18544. \begin{lstlisting}
  18545. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18546. return f(v[0]), f(v[1])
  18547. def inc(x):
  18548. return x + 1
  18549. t = map(inc, (0, 41))
  18550. print(t[1])
  18551. \end{lstlisting}
  18552. \fi}
  18553. \end{tcolorbox}
  18554. \caption{A partially typed version of the \code{map} example.}
  18555. \label{fig:gradual-map}
  18556. \end{figure}
  18557. \begin{figure}[tbp]
  18558. \begin{tcolorbox}[colback=white]
  18559. {\if\edition\racketEd
  18560. \begin{lstlisting}
  18561. (define/public (consistent? t1 t2)
  18562. (match* (t1 t2)
  18563. [('Integer 'Integer) #t]
  18564. [('Boolean 'Boolean) #t]
  18565. [('Void 'Void) #t]
  18566. [('Any t2) #t]
  18567. [(t1 'Any) #t]
  18568. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18569. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18570. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18571. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18572. (consistent? rt1 rt2))]
  18573. [(other wise) #f]))
  18574. \end{lstlisting}
  18575. \fi}
  18576. {\if\edition\pythonEd
  18577. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18578. def consistent(self, t1, t2):
  18579. match (t1, t2):
  18580. case (AnyType(), _):
  18581. return True
  18582. case (_, AnyType()):
  18583. return True
  18584. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18585. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18586. case (TupleType(ts1), TupleType(ts2)):
  18587. return all(map(self.consistent, ts1, ts2))
  18588. case (_, _):
  18589. return t1 == t2
  18590. \end{lstlisting}
  18591. \fi}
  18592. \end{tcolorbox}
  18593. \caption{The consistency method on types.}
  18594. \label{fig:consistent}
  18595. \end{figure}
  18596. It is also helpful to consider how gradual typing handles programs with an
  18597. error, such as applying \code{map} to a function that sometimes
  18598. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18599. type checker for \LangGrad{} accepts this program because the type of
  18600. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18601. \code{map}; that is,
  18602. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18603. is consistent with
  18604. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18605. One might say that a gradual type checker is optimistic in that it
  18606. accepts programs that might execute without a runtime type error.
  18607. %
  18608. The definition of the type checker for \LangGrad{} is shown in
  18609. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18610. and \ref{fig:type-check-Lgradual-3}.
  18611. %% \begin{figure}[tp]
  18612. %% \centering
  18613. %% \fbox{
  18614. %% \begin{minipage}{0.96\textwidth}
  18615. %% \small
  18616. %% \[
  18617. %% \begin{array}{lcl}
  18618. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18619. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18620. %% \end{array}
  18621. %% \]
  18622. %% \end{minipage}
  18623. %% }
  18624. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18625. %% \label{fig:Lgrad-prime-syntax}
  18626. %% \end{figure}
  18627. \begin{figure}[tbp]
  18628. \begin{tcolorbox}[colback=white]
  18629. {\if\edition\racketEd
  18630. \begin{lstlisting}
  18631. (define (map [f : (Integer -> Integer)]
  18632. [v : (Vector Integer Integer)])
  18633. : (Vector Integer Integer)
  18634. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18635. (define (inc x) (+ x 1))
  18636. (define (true) #t)
  18637. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18638. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18639. \end{lstlisting}
  18640. \fi}
  18641. {\if\edition\pythonEd
  18642. \begin{lstlisting}
  18643. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18644. return f(v[0]), f(v[1])
  18645. def inc(x):
  18646. return x + 1
  18647. def true():
  18648. return True
  18649. def maybe_inc(x):
  18650. return inc(x) if input_int() == 0 else true()
  18651. t = map(maybe_inc, (0, 41))
  18652. print( t[1] )
  18653. \end{lstlisting}
  18654. \fi}
  18655. \end{tcolorbox}
  18656. \caption{A variant of the \code{map} example with an error.}
  18657. \label{fig:map-maybe_inc}
  18658. \end{figure}
  18659. Running this program with input \code{1} triggers an
  18660. error when the \code{maybe\_inc} function returns
  18661. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18662. performs checking at runtime to ensure the integrity of the static
  18663. types, such as the
  18664. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18665. annotation on
  18666. parameter \code{f} of \code{map}.
  18667. Here we give a preview of how the runtime checking is accomplished;
  18668. the following sections provide the details.
  18669. The runtime checking is carried out by a new \code{Cast} AST node that
  18670. is generated in a new pass named \code{cast\_insert}. The output of
  18671. \code{cast\_insert} is a program in the \LangCast{} language, which
  18672. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18673. %
  18674. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18675. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18676. inserted every time the type checker encounters two types that are
  18677. consistent but not equal. In the \code{inc} function, \code{x} is
  18678. cast to \INTTY{} and the result of the \code{+} is cast to
  18679. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18680. is cast from
  18681. \racket{\code{(Any -> Any)}}
  18682. \python{\code{Callable[[Any], Any]}}
  18683. to
  18684. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18685. %
  18686. In the next section we see how to interpret the \code{Cast} node.
  18687. \begin{figure}[btp]
  18688. \begin{tcolorbox}[colback=white]
  18689. {\if\edition\racketEd
  18690. \begin{lstlisting}
  18691. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18692. : (Vector Integer Integer)
  18693. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18694. (define (inc [x : Any]) : Any
  18695. (cast (+ (cast x Any Integer) 1) Integer Any))
  18696. (define (true) : Any (cast #t Boolean Any))
  18697. (define (maybe_inc [x : Any]) : Any
  18698. (if (eq? 0 (read)) (inc x) (true)))
  18699. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18700. (vector 0 41)) 0)
  18701. \end{lstlisting}
  18702. \fi}
  18703. {\if\edition\pythonEd
  18704. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18705. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18706. return f(v[0]), f(v[1])
  18707. def inc(x : Any) -> Any:
  18708. return Cast(Cast(x, Any, int) + 1, int, Any)
  18709. def true() -> Any:
  18710. return Cast(True, bool, Any)
  18711. def maybe_inc(x : Any) -> Any:
  18712. return inc(x) if input_int() == 0 else true()
  18713. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18714. (0, 41))
  18715. print(t[1])
  18716. \end{lstlisting}
  18717. \fi}
  18718. \end{tcolorbox}
  18719. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18720. and \code{maybe\_inc} example.}
  18721. \label{fig:map-cast}
  18722. \end{figure}
  18723. {\if\edition\pythonEd
  18724. \begin{figure}[tbp]
  18725. \begin{tcolorbox}[colback=white]
  18726. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18727. class TypeCheckLgrad(TypeCheckLlambda):
  18728. def type_check_exp(self, e, env) -> Type:
  18729. match e:
  18730. case Name(id):
  18731. return env[id]
  18732. case Constant(value) if isinstance(value, bool):
  18733. return BoolType()
  18734. case Constant(value) if isinstance(value, int):
  18735. return IntType()
  18736. case Call(Name('input_int'), []):
  18737. return IntType()
  18738. case BinOp(left, op, right):
  18739. left_type = self.type_check_exp(left, env)
  18740. self.check_consistent(left_type, IntType(), left)
  18741. right_type = self.type_check_exp(right, env)
  18742. self.check_consistent(right_type, IntType(), right)
  18743. return IntType()
  18744. case IfExp(test, body, orelse):
  18745. test_t = self.type_check_exp(test, env)
  18746. self.check_consistent(test_t, BoolType(), test)
  18747. body_t = self.type_check_exp(body, env)
  18748. orelse_t = self.type_check_exp(orelse, env)
  18749. self.check_consistent(body_t, orelse_t, e)
  18750. return self.join_types(body_t, orelse_t)
  18751. case Call(func, args):
  18752. func_t = self.type_check_exp(func, env)
  18753. args_t = [self.type_check_exp(arg, env) for arg in args]
  18754. match func_t:
  18755. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18756. for (arg_t, param_t) in zip(args_t, params_t):
  18757. self.check_consistent(param_t, arg_t, e)
  18758. return return_t
  18759. case AnyType():
  18760. return AnyType()
  18761. case _:
  18762. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18763. ...
  18764. case _:
  18765. raise Exception('type_check_exp: unexpected ' + repr(e))
  18766. \end{lstlisting}
  18767. \end{tcolorbox}
  18768. \caption{Type checking expressions in the \LangGrad{} language.}
  18769. \label{fig:type-check-Lgradual-1}
  18770. \end{figure}
  18771. \begin{figure}[tbp]
  18772. \begin{tcolorbox}[colback=white]
  18773. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18774. def check_exp(self, e, expected_ty, env):
  18775. match e:
  18776. case Lambda(params, body):
  18777. match expected_ty:
  18778. case FunctionType(params_t, return_t):
  18779. new_env = env.copy().update(zip(params, params_t))
  18780. e.has_type = expected_ty
  18781. body_ty = self.type_check_exp(body, new_env)
  18782. self.check_consistent(body_ty, return_t)
  18783. case AnyType():
  18784. new_env = env.copy().update((p, AnyType()) for p in params)
  18785. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18786. body_ty = self.type_check_exp(body, new_env)
  18787. case _:
  18788. raise Exception('lambda does not have type ' + str(expected_ty))
  18789. case _:
  18790. e_ty = self.type_check_exp(e, env)
  18791. self.check_consistent(e_ty, expected_ty, e)
  18792. \end{lstlisting}
  18793. \end{tcolorbox}
  18794. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18795. \label{fig:type-check-Lgradual-2}
  18796. \end{figure}
  18797. \begin{figure}[tbp]
  18798. \begin{tcolorbox}[colback=white]
  18799. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18800. def type_check_stmt(self, s, env, return_type):
  18801. match s:
  18802. case Assign([Name(id)], value):
  18803. value_ty = self.type_check_exp(value, env)
  18804. if id in env:
  18805. self.check_consistent(env[id], value_ty, value)
  18806. else:
  18807. env[id] = value_ty
  18808. ...
  18809. case _:
  18810. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18811. def type_check_stmts(self, ss, env, return_type):
  18812. for s in ss:
  18813. self.type_check_stmt(s, env, return_type)
  18814. \end{lstlisting}
  18815. \end{tcolorbox}
  18816. \caption{Type checking statements in the \LangGrad{} language.}
  18817. \label{fig:type-check-Lgradual-3}
  18818. \end{figure}
  18819. \begin{figure}[tbp]
  18820. \begin{tcolorbox}[colback=white]
  18821. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18822. def join_types(self, t1, t2):
  18823. match (t1, t2):
  18824. case (AnyType(), _):
  18825. return t2
  18826. case (_, AnyType()):
  18827. return t1
  18828. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18829. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18830. self.join_types(rt1,rt2))
  18831. case (TupleType(ts1), TupleType(ts2)):
  18832. return TupleType(list(map(self.join_types, ts1, ts2)))
  18833. case (_, _):
  18834. return t1
  18835. def check_consistent(self, t1, t2, e):
  18836. if not self.consistent(t1, t2):
  18837. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18838. + ' in ' + repr(e))
  18839. \end{lstlisting}
  18840. \end{tcolorbox}
  18841. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18842. \label{fig:type-check-Lgradual-aux}
  18843. \end{figure}
  18844. \fi}
  18845. {\if\edition\racketEd
  18846. \begin{figure}[tbp]
  18847. \begin{tcolorbox}[colback=white]
  18848. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18849. (define/override (type-check-exp env)
  18850. (lambda (e)
  18851. (define recur (type-check-exp env))
  18852. (match e
  18853. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18854. (define-values (new-es ts)
  18855. (for/lists (exprs types) ([e es])
  18856. (recur e)))
  18857. (define t-ret (type-check-op op ts e))
  18858. (values (Prim op new-es) t-ret)]
  18859. [(Prim 'eq? (list e1 e2))
  18860. (define-values (e1^ t1) (recur e1))
  18861. (define-values (e2^ t2) (recur e2))
  18862. (check-consistent? t1 t2 e)
  18863. (define T (meet t1 t2))
  18864. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18865. [(Prim 'and (list e1 e2))
  18866. (recur (If e1 e2 (Bool #f)))]
  18867. [(Prim 'or (list e1 e2))
  18868. (define tmp (gensym 'tmp))
  18869. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18870. [(If e1 e2 e3)
  18871. (define-values (e1^ T1) (recur e1))
  18872. (define-values (e2^ T2) (recur e2))
  18873. (define-values (e3^ T3) (recur e3))
  18874. (check-consistent? T1 'Boolean e)
  18875. (check-consistent? T2 T3 e)
  18876. (define Tif (meet T2 T3))
  18877. (values (If e1^ e2^ e3^) Tif)]
  18878. [(SetBang x e1)
  18879. (define-values (e1^ T1) (recur e1))
  18880. (define varT (dict-ref env x))
  18881. (check-consistent? T1 varT e)
  18882. (values (SetBang x e1^) 'Void)]
  18883. [(WhileLoop e1 e2)
  18884. (define-values (e1^ T1) (recur e1))
  18885. (check-consistent? T1 'Boolean e)
  18886. (define-values (e2^ T2) ((type-check-exp env) e2))
  18887. (values (WhileLoop e1^ e2^) 'Void)]
  18888. [(Prim 'vector-length (list e1))
  18889. (define-values (e1^ t) (recur e1))
  18890. (match t
  18891. [`(Vector ,ts ...)
  18892. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18893. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18894. \end{lstlisting}
  18895. \end{tcolorbox}
  18896. \caption{Type checker for the \LangGrad{} language, part 1.}
  18897. \label{fig:type-check-Lgradual-1}
  18898. \end{figure}
  18899. \begin{figure}[tbp]
  18900. \begin{tcolorbox}[colback=white]
  18901. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18902. [(Prim 'vector-ref (list e1 e2))
  18903. (define-values (e1^ t1) (recur e1))
  18904. (define-values (e2^ t2) (recur e2))
  18905. (check-consistent? t2 'Integer e)
  18906. (match t1
  18907. [`(Vector ,ts ...)
  18908. (match e2^
  18909. [(Int i)
  18910. (unless (and (0 . <= . i) (i . < . (length ts)))
  18911. (error 'type-check "invalid index ~a in ~a" i e))
  18912. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18913. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18914. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18915. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18916. [(Prim 'vector-set! (list e1 e2 e3) )
  18917. (define-values (e1^ t1) (recur e1))
  18918. (define-values (e2^ t2) (recur e2))
  18919. (define-values (e3^ t3) (recur e3))
  18920. (check-consistent? t2 'Integer e)
  18921. (match t1
  18922. [`(Vector ,ts ...)
  18923. (match e2^
  18924. [(Int i)
  18925. (unless (and (0 . <= . i) (i . < . (length ts)))
  18926. (error 'type-check "invalid index ~a in ~a" i e))
  18927. (check-consistent? (list-ref ts i) t3 e)
  18928. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18929. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18930. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18931. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18932. [(Apply e1 e2s)
  18933. (define-values (e1^ T1) (recur e1))
  18934. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18935. (match T1
  18936. [`(,T1ps ... -> ,T1rt)
  18937. (for ([T2 T2s] [Tp T1ps])
  18938. (check-consistent? T2 Tp e))
  18939. (values (Apply e1^ e2s^) T1rt)]
  18940. [`Any (values (Apply e1^ e2s^) 'Any)]
  18941. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18942. [(Lambda params Tr e1)
  18943. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18944. (match p
  18945. [`[,x : ,T] (values x T)]
  18946. [(? symbol? x) (values x 'Any)])))
  18947. (define-values (e1^ T1)
  18948. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18949. (check-consistent? Tr T1 e)
  18950. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18951. `(,@Ts -> ,Tr))]
  18952. [else ((super type-check-exp env) e)]
  18953. )))
  18954. \end{lstlisting}
  18955. \end{tcolorbox}
  18956. \caption{Type checker for the \LangGrad{} language, part 2.}
  18957. \label{fig:type-check-Lgradual-2}
  18958. \end{figure}
  18959. \begin{figure}[tbp]
  18960. \begin{tcolorbox}[colback=white]
  18961. \begin{lstlisting}
  18962. (define/override (type-check-def env)
  18963. (lambda (e)
  18964. (match e
  18965. [(Def f params rt info body)
  18966. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18967. (match p
  18968. [`[,x : ,T] (values x T)]
  18969. [(? symbol? x) (values x 'Any)])))
  18970. (define new-env (append (map cons xs ps) env))
  18971. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18972. (check-consistent? ty^ rt e)
  18973. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18974. [else (error 'type-check "ill-formed function definition ~a" e)]
  18975. )))
  18976. (define/override (type-check-program e)
  18977. (match e
  18978. [(Program info body)
  18979. (define-values (body^ ty) ((type-check-exp '()) body))
  18980. (check-consistent? ty 'Integer e)
  18981. (ProgramDefsExp info '() body^)]
  18982. [(ProgramDefsExp info ds body)
  18983. (define new-env (for/list ([d ds])
  18984. (cons (Def-name d) (fun-def-type d))))
  18985. (define ds^ (for/list ([d ds])
  18986. ((type-check-def new-env) d)))
  18987. (define-values (body^ ty) ((type-check-exp new-env) body))
  18988. (check-consistent? ty 'Integer e)
  18989. (ProgramDefsExp info ds^ body^)]
  18990. [else (super type-check-program e)]))
  18991. \end{lstlisting}
  18992. \end{tcolorbox}
  18993. \caption{Type checker for the \LangGrad{} language, part 3.}
  18994. \label{fig:type-check-Lgradual-3}
  18995. \end{figure}
  18996. \begin{figure}[tbp]
  18997. \begin{tcolorbox}[colback=white]
  18998. \begin{lstlisting}
  18999. (define/public (join t1 t2)
  19000. (match* (t1 t2)
  19001. [('Integer 'Integer) 'Integer]
  19002. [('Boolean 'Boolean) 'Boolean]
  19003. [('Void 'Void) 'Void]
  19004. [('Any t2) t2]
  19005. [(t1 'Any) t1]
  19006. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19007. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19008. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19009. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19010. -> ,(join rt1 rt2))]))
  19011. (define/public (meet t1 t2)
  19012. (match* (t1 t2)
  19013. [('Integer 'Integer) 'Integer]
  19014. [('Boolean 'Boolean) 'Boolean]
  19015. [('Void 'Void) 'Void]
  19016. [('Any t2) 'Any]
  19017. [(t1 'Any) 'Any]
  19018. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19019. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19020. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19021. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19022. -> ,(meet rt1 rt2))]))
  19023. (define/public (check-consistent? t1 t2 e)
  19024. (unless (consistent? t1 t2)
  19025. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19026. (define explicit-prim-ops
  19027. (set-union
  19028. (type-predicates)
  19029. (set 'procedure-arity 'eq? 'not 'and 'or
  19030. 'vector 'vector-length 'vector-ref 'vector-set!
  19031. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19032. (define/override (fun-def-type d)
  19033. (match d
  19034. [(Def f params rt info body)
  19035. (define ps
  19036. (for/list ([p params])
  19037. (match p
  19038. [`[,x : ,T] T]
  19039. [(? symbol?) 'Any]
  19040. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19041. `(,@ps -> ,rt)]
  19042. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19043. \end{lstlisting}
  19044. \end{tcolorbox}
  19045. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19046. \label{fig:type-check-Lgradual-aux}
  19047. \end{figure}
  19048. \fi}
  19049. \clearpage
  19050. \section{Interpreting \LangCast{}}
  19051. \label{sec:interp-casts}
  19052. The runtime behavior of casts involving simple types such as
  19053. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19054. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19055. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19056. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19057. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19058. operator, by checking the value's tag and either retrieving
  19059. the underlying integer or signaling an error if the tag is not the
  19060. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19061. %
  19062. Things get more interesting with casts involving
  19063. \racket{function and tuple types}\python{function, tuple, and array types}.
  19064. Consider the cast of the function \code{maybe\_inc} from
  19065. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19066. to
  19067. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19068. shown in figure~\ref{fig:map-maybe_inc}.
  19069. When the \code{maybe\_inc} function flows through
  19070. this cast at runtime, we don't know whether it will return
  19071. an integer, because that depends on the input from the user.
  19072. The \LangCast{} interpreter therefore delays the checking
  19073. of the cast until the function is applied. To do so it
  19074. wraps \code{maybe\_inc} in a new function that casts its parameter
  19075. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19076. casts the return value from \CANYTY{} to \INTTY{}.
  19077. {\if\edition\pythonEd
  19078. %
  19079. There are further complications regarding casts on mutable data
  19080. such as the \code{list} type introduced in
  19081. the challenge assignment of section~\ref{sec:arrays}.
  19082. %
  19083. \fi}
  19084. %
  19085. Consider the example presented in figure~\ref{fig:map-bang} that
  19086. defines a partially typed version of \code{map} whose parameter
  19087. \code{v} has type
  19088. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19089. and that updates \code{v} in place
  19090. instead of returning a new tuple. So, we name this function
  19091. \code{map\_inplace}. We apply \code{map\_inplace} to an
  19092. \racket{tuple}\python{array} of integers, so the type checker inserts a
  19093. cast from
  19094. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19095. to
  19096. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19097. A naive way for the \LangCast{} interpreter to cast between
  19098. \racket{tuple}\python{array} types would be a build a new
  19099. \racket{tuple}\python{array}
  19100. whose elements are the result
  19101. of casting each of the original elements to the appropriate target
  19102. type.
  19103. However, this approach is not valid for mutable data structures.
  19104. In the example of figure~\ref{fig:map-bang},
  19105. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19106. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19107. the original one.
  19108. \begin{figure}[tbp]
  19109. \begin{tcolorbox}[colback=white]
  19110. % gradual_test_11.rkt
  19111. {\if\edition\racketEd
  19112. \begin{lstlisting}
  19113. (define (map_inplace [f : (Any -> Any)]
  19114. [v : (Vector Any Any)]) : Void
  19115. (begin
  19116. (vector-set! v 0 (f (vector-ref v 0)))
  19117. (vector-set! v 1 (f (vector-ref v 1)))))
  19118. (define (inc x) (+ x 1))
  19119. (let ([v (vector 0 41)])
  19120. (begin (map_inplace inc v) (vector-ref v 1)))
  19121. \end{lstlisting}
  19122. \fi}
  19123. {\if\edition\pythonEd
  19124. \begin{lstlisting}
  19125. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19126. i = 0
  19127. while i != len(v):
  19128. v[i] = f(v[i])
  19129. i = i + 1
  19130. def inc(x : int) -> int:
  19131. return x + 1
  19132. v = [0, 41]
  19133. map_inplace(inc, v)
  19134. print( v[1] )
  19135. \end{lstlisting}
  19136. \fi}
  19137. \end{tcolorbox}
  19138. \caption{An example involving casts on arrays.}
  19139. \label{fig:map-bang}
  19140. \end{figure}
  19141. Instead the interpreter needs to create a new kind of value, a
  19142. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19143. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19144. and then applies a
  19145. cast to the resulting value. On a write, the proxy casts the argument
  19146. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19147. \racket{
  19148. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19149. \code{0} from \INTTY{} to \CANYTY{}.
  19150. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19151. from \CANYTY{} to \INTTY{}.
  19152. }
  19153. \python{
  19154. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19155. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19156. For the subscript on the left of the assignment,
  19157. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19158. }
  19159. The final category of cast that we need to consider consist of casts between
  19160. the \CANYTY{} type and higher-order types such as functions and
  19161. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  19162. variant of \code{map\_inplace} in which parameter \code{v} does not
  19163. have a type annotation, so it is given type \CANYTY{}. In the call to
  19164. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19165. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19166. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19167. \code{Inject}, but that doesn't work because
  19168. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19169. a flat type. Instead, we must first cast to
  19170. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19171. and then inject to \CANYTY{}.
  19172. \begin{figure}[tbp]
  19173. \begin{tcolorbox}[colback=white]
  19174. {\if\edition\racketEd
  19175. \begin{lstlisting}
  19176. (define (map_inplace [f : (Any -> Any)] v) : Void
  19177. (begin
  19178. (vector-set! v 0 (f (vector-ref v 0)))
  19179. (vector-set! v 1 (f (vector-ref v 1)))))
  19180. (define (inc x) (+ x 1))
  19181. (let ([v (vector 0 41)])
  19182. (begin (map_inplace inc v) (vector-ref v 1)))
  19183. \end{lstlisting}
  19184. \fi}
  19185. {\if\edition\pythonEd
  19186. \begin{lstlisting}
  19187. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19188. i = 0
  19189. while i != len(v):
  19190. v[i] = f(v[i])
  19191. i = i + 1
  19192. def inc(x):
  19193. return x + 1
  19194. v = [0, 41]
  19195. map_inplace(inc, v)
  19196. print( v[1] )
  19197. \end{lstlisting}
  19198. \fi}
  19199. \end{tcolorbox}
  19200. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  19201. \label{fig:map-any}
  19202. \end{figure}
  19203. \begin{figure}[tbp]
  19204. \begin{tcolorbox}[colback=white]
  19205. {\if\edition\racketEd
  19206. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19207. (define/public (apply_cast v s t)
  19208. (match* (s t)
  19209. [(t1 t2) #:when (equal? t1 t2) v]
  19210. [('Any t2)
  19211. (match t2
  19212. [`(,ts ... -> ,rt)
  19213. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19214. (define v^ (apply-project v any->any))
  19215. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19216. [`(Vector ,ts ...)
  19217. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19218. (define v^ (apply-project v vec-any))
  19219. (apply_cast v^ vec-any `(Vector ,@ts))]
  19220. [else (apply-project v t2)])]
  19221. [(t1 'Any)
  19222. (match t1
  19223. [`(,ts ... -> ,rt)
  19224. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19225. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19226. (apply-inject v^ (any-tag any->any))]
  19227. [`(Vector ,ts ...)
  19228. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19229. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19230. (apply-inject v^ (any-tag vec-any))]
  19231. [else (apply-inject v (any-tag t1))])]
  19232. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19233. (define x (gensym 'x))
  19234. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19235. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19236. (define cast-writes
  19237. (for/list ([t1 ts1] [t2 ts2])
  19238. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19239. `(vector-proxy ,(vector v (apply vector cast-reads)
  19240. (apply vector cast-writes)))]
  19241. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19242. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19243. `(function ,xs ,(Cast
  19244. (Apply (Value v)
  19245. (for/list ([x xs][t1 ts1][t2 ts2])
  19246. (Cast (Var x) t2 t1)))
  19247. rt1 rt2) ())]
  19248. ))
  19249. \end{lstlisting}
  19250. \fi}
  19251. {\if\edition\pythonEd
  19252. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19253. def apply_cast(self, value, src, tgt):
  19254. match (src, tgt):
  19255. case (AnyType(), FunctionType(ps2, rt2)):
  19256. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19257. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19258. case (AnyType(), TupleType(ts2)):
  19259. anytup = TupleType([AnyType() for t1 in ts2])
  19260. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19261. case (AnyType(), ListType(t2)):
  19262. anylist = ListType([AnyType() for t1 in ts2])
  19263. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19264. case (AnyType(), AnyType()):
  19265. return value
  19266. case (AnyType(), _):
  19267. return self.apply_project(value, tgt)
  19268. case (FunctionType(ps1,rt1), AnyType()):
  19269. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19270. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19271. case (TupleType(ts1), AnyType()):
  19272. anytup = TupleType([AnyType() for t1 in ts1])
  19273. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19274. case (ListType(t1), AnyType()):
  19275. anylist = ListType(AnyType())
  19276. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19277. case (_, AnyType()):
  19278. return self.apply_inject(value, src)
  19279. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19280. params = [generate_name('x') for p in ps2]
  19281. args = [Cast(Name(x), t2, t1)
  19282. for (x,t1,t2) in zip(params, ps1, ps2)]
  19283. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19284. return Function('cast', params, [Return(body)], {})
  19285. case (TupleType(ts1), TupleType(ts2)):
  19286. x = generate_name('x')
  19287. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19288. for (t1,t2) in zip(ts1,ts2)]
  19289. return ProxiedTuple(value, reads)
  19290. case (ListType(t1), ListType(t2)):
  19291. x = generate_name('x')
  19292. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19293. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19294. return ProxiedList(value, read, write)
  19295. case (t1, t2) if t1 == t2:
  19296. return value
  19297. case (t1, t2):
  19298. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19299. def apply_inject(self, value, src):
  19300. return Tagged(value, self.type_to_tag(src))
  19301. def apply_project(self, value, tgt):
  19302. match value:
  19303. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19304. return val
  19305. case _:
  19306. raise Exception('apply_project, unexpected ' + repr(value))
  19307. \end{lstlisting}
  19308. \fi}
  19309. \end{tcolorbox}
  19310. \caption{The \code{apply\_cast} auxiliary method.}
  19311. \label{fig:apply_cast}
  19312. \end{figure}
  19313. The \LangCast{} interpreter uses an auxiliary function named
  19314. \code{apply\_cast} to cast a value from a source type to a target type,
  19315. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19316. the kinds of casts that we've discussed in this section.
  19317. %
  19318. The definition of the interpreter for \LangCast{} is shown in
  19319. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19320. dispatching to \code{apply\_cast}.
  19321. \racket{To handle the addition of tuple
  19322. proxies, we update the tuple primitives in \code{interp-op} using the
  19323. functions given in figure~\ref{fig:guarded-tuple}.}
  19324. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19325. \begin{figure}[tbp]
  19326. \begin{tcolorbox}[colback=white]
  19327. {\if\edition\racketEd
  19328. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19329. (define interp-Lcast-class
  19330. (class interp-Llambda-class
  19331. (super-new)
  19332. (inherit apply-fun apply-inject apply-project)
  19333. (define/override (interp-op op)
  19334. (match op
  19335. ['vector-length guarded-vector-length]
  19336. ['vector-ref guarded-vector-ref]
  19337. ['vector-set! guarded-vector-set!]
  19338. ['any-vector-ref (lambda (v i)
  19339. (match v [`(tagged ,v^ ,tg)
  19340. (guarded-vector-ref v^ i)]))]
  19341. ['any-vector-set! (lambda (v i a)
  19342. (match v [`(tagged ,v^ ,tg)
  19343. (guarded-vector-set! v^ i a)]))]
  19344. ['any-vector-length (lambda (v)
  19345. (match v [`(tagged ,v^ ,tg)
  19346. (guarded-vector-length v^)]))]
  19347. [else (super interp-op op)]
  19348. ))
  19349. (define/override ((interp-exp env) e)
  19350. (define (recur e) ((interp-exp env) e))
  19351. (match e
  19352. [(Value v) v]
  19353. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19354. [else ((super interp-exp env) e)]))
  19355. ))
  19356. (define (interp-Lcast p)
  19357. (send (new interp-Lcast-class) interp-program p))
  19358. \end{lstlisting}
  19359. \fi}
  19360. {\if\edition\pythonEd
  19361. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19362. class InterpLcast(InterpLany):
  19363. def interp_exp(self, e, env):
  19364. match e:
  19365. case Cast(value, src, tgt):
  19366. v = self.interp_exp(value, env)
  19367. return self.apply_cast(v, src, tgt)
  19368. case ValueExp(value):
  19369. return value
  19370. ...
  19371. case _:
  19372. return super().interp_exp(e, env)
  19373. \end{lstlisting}
  19374. \fi}
  19375. \end{tcolorbox}
  19376. \caption{The interpreter for \LangCast{}.}
  19377. \label{fig:interp-Lcast}
  19378. \end{figure}
  19379. {\if\edition\racketEd
  19380. \begin{figure}[tbp]
  19381. \begin{tcolorbox}[colback=white]
  19382. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19383. (define (guarded-vector-ref vec i)
  19384. (match vec
  19385. [`(vector-proxy ,proxy)
  19386. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19387. (define rd (vector-ref (vector-ref proxy 1) i))
  19388. (apply-fun rd (list val) 'guarded-vector-ref)]
  19389. [else (vector-ref vec i)]))
  19390. (define (guarded-vector-set! vec i arg)
  19391. (match vec
  19392. [`(vector-proxy ,proxy)
  19393. (define wr (vector-ref (vector-ref proxy 2) i))
  19394. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19395. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19396. [else (vector-set! vec i arg)]))
  19397. (define (guarded-vector-length vec)
  19398. (match vec
  19399. [`(vector-proxy ,proxy)
  19400. (guarded-vector-length (vector-ref proxy 0))]
  19401. [else (vector-length vec)]))
  19402. \end{lstlisting}
  19403. %% {\if\edition\pythonEd
  19404. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19405. %% UNDER CONSTRUCTION
  19406. %% \end{lstlisting}
  19407. %% \fi}
  19408. \end{tcolorbox}
  19409. \caption{The \code{guarded-vector} auxiliary functions.}
  19410. \label{fig:guarded-tuple}
  19411. \end{figure}
  19412. \fi}
  19413. {\if\edition\pythonEd
  19414. \section{Overload Resolution}
  19415. \label{sec:gradual-resolution}
  19416. Recall that when we added support for arrays in
  19417. section~\ref{sec:arrays}, the syntax for the array operations were the
  19418. same as for tuple operations (e.g., accessing an element, getting the
  19419. length). So we performed overload resolution, with a pass named
  19420. \code{resolve}, to separate the array and tuple operations. In
  19421. particular, we introduced the primitives \code{array\_load},
  19422. \code{array\_store}, and \code{array\_len}.
  19423. For gradual typing, we further overload these operators to work on
  19424. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19425. updated with new cases for the \CANYTY{} type, translating the element
  19426. access and length operations to the primitives \code{any\_load},
  19427. \code{any\_store}, and \code{any\_len}.
  19428. \fi}
  19429. \section{Cast Insertion}
  19430. \label{sec:gradual-insert-casts}
  19431. In our discussion of type checking of \LangGrad{}, we mentioned how
  19432. the runtime aspect of type checking is carried out by the \code{Cast}
  19433. AST node, which is added to the program by a new pass named
  19434. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19435. language. We now discuss the details of this pass.
  19436. The \code{cast\_insert} pass is closely related to the type checker
  19437. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19438. In particular, the type checker allows implicit casts between
  19439. consistent types. The job of the \code{cast\_insert} pass is to make
  19440. those casts explicit. It does so by inserting
  19441. \code{Cast} nodes into the AST.
  19442. %
  19443. For the most part, the implicit casts occur in places where the type
  19444. checker checks two types for consistency. Consider the case for
  19445. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19446. checker requires that the type of the left operand is consistent with
  19447. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19448. \code{Cast} around the left operand, converting from its type to
  19449. \INTTY{}. The story is similar for the right operand. It is not always
  19450. necessary to insert a cast, e.g., if the left operand already has type
  19451. \INTTY{} then there is no need for a \code{Cast}.
  19452. Some of the implicit casts are not as straightforward. One such case
  19453. arises with the
  19454. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19455. see that the type checker requires that the two branches have
  19456. consistent types and that type of the conditional expression is the
  19457. meet of the branches' types. In the target language \LangCast{}, both
  19458. branches will need to have the same type, and that type
  19459. will be the type of the conditional expression. Thus, each branch requires
  19460. a \code{Cast} to convert from its type to the meet of the branches' types.
  19461. The case for the function call exhibits another interesting situation. If
  19462. the function expression is of type \CANYTY{}, then it needs to be cast
  19463. to a function type so that it can be used in a function call in
  19464. \LangCast{}. Which function type should it be cast to? The parameter
  19465. and return types are unknown, so we can simply use \CANYTY{} for all
  19466. of them. Furthermore, in \LangCast{} the argument types will need to
  19467. exactly match the parameter types, so we must cast all the arguments
  19468. to type \CANYTY{} (if they are not already of that type).
  19469. {\if\edition\racketEd
  19470. %
  19471. Likewise, the cases for the tuple operators \code{vector-length},
  19472. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19473. where the tuple expression is of type \CANYTY{}. Instead of
  19474. handling these situations with casts, we recommend translating
  19475. the special-purpose variants of the tuple operators that handle
  19476. tuples of type \CANYTY{}: \code{any-vector-length},
  19477. \code{any-vector-ref}, and \code{any-vector-set!}.
  19478. %
  19479. \fi}
  19480. \section{Lower Casts}
  19481. \label{sec:lower_casts}
  19482. The next step in the journey toward x86 is the \code{lower\_casts}
  19483. pass that translates the casts in \LangCast{} to the lower-level
  19484. \code{Inject} and \code{Project} operators and new operators for
  19485. proxies, extending the \LangLam{} language to \LangProxy{}.
  19486. The \LangProxy{} language can also be described as an extension of
  19487. \LangAny{}, with the addition of proxies. We recommend creating an
  19488. auxiliary function named \code{lower\_cast} that takes an expression
  19489. (in \LangCast{}), a source type, and a target type and translates it
  19490. to an expression in \LangProxy{}.
  19491. The \code{lower\_cast} function can follow a code structure similar to
  19492. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19493. the interpreter for \LangCast{}, because it must handle the same cases
  19494. as \code{apply\_cast} and it needs to mimic the behavior of
  19495. \code{apply\_cast}. The most interesting cases concern
  19496. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19497. {\if\edition\racketEd
  19498. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19499. type to another tuple type is accomplished by creating a proxy that
  19500. intercepts the operations on the underlying tuple. Here we make the
  19501. creation of the proxy explicit with the \code{vector-proxy} AST
  19502. node. It takes three arguments: the first is an expression for the
  19503. tuple, the second is tuple of functions for casting an element that is
  19504. being read from the tuple, and the third is a tuple of functions for
  19505. casting an element that is being written to the array. You can create
  19506. the functions for reading and writing using lambda expressions. Also,
  19507. as we show in the next section, we need to differentiate these tuples
  19508. of functions from the user-created ones, so we recommend using a new
  19509. AST node named \code{raw-vector} instead of \code{vector}.
  19510. %
  19511. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19512. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19513. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19514. \fi}
  19515. {\if\edition\pythonEd
  19516. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19517. type to another array type is accomplished by creating a proxy that
  19518. intercepts the operations on the underlying array. Here we make the
  19519. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19520. takes fives arguments: the first is an expression for the array, the
  19521. second is a function for casting an element that is being read from
  19522. the array, the third is a function for casting an element that is
  19523. being written to the array, the fourth is the type of the underlying
  19524. array, and the fifth is the type of the proxied array. You can create
  19525. the functions for reading and writing using lambda expressions.
  19526. A cast between two tuple types can be handled in a similar manner. We
  19527. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19528. immutable, so there is no need for a function to cast the value during
  19529. a write. Because there is a separate element type for each slot in
  19530. the tuple, we need not just one function for casting during a read,
  19531. but instead a tuple of functions.
  19532. %
  19533. Also, as we show in the next section, we need to differentiate these
  19534. tuples from the user-created ones, so we recommend using a new AST
  19535. node named \code{RawTuple} instead of \code{Tuple} to create the
  19536. tuples of functions.
  19537. %
  19538. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19539. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19540. that involved casting an array of integers to an array of \CANYTY{}.
  19541. \fi}
  19542. \begin{figure}[tbp]
  19543. \begin{tcolorbox}[colback=white]
  19544. {\if\edition\racketEd
  19545. \begin{lstlisting}
  19546. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19547. (begin
  19548. (vector-set! v 0 (f (vector-ref v 0)))
  19549. (vector-set! v 1 (f (vector-ref v 1)))))
  19550. (define (inc [x : Any]) : Any
  19551. (inject (+ (project x Integer) 1) Integer))
  19552. (let ([v (vector 0 41)])
  19553. (begin
  19554. (map_inplace inc (vector-proxy v
  19555. (raw-vector (lambda: ([x9 : Integer]) : Any
  19556. (inject x9 Integer))
  19557. (lambda: ([x9 : Integer]) : Any
  19558. (inject x9 Integer)))
  19559. (raw-vector (lambda: ([x9 : Any]) : Integer
  19560. (project x9 Integer))
  19561. (lambda: ([x9 : Any]) : Integer
  19562. (project x9 Integer)))))
  19563. (vector-ref v 1)))
  19564. \end{lstlisting}
  19565. \fi}
  19566. {\if\edition\pythonEd
  19567. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19568. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19569. i = 0
  19570. while i != array_len(v):
  19571. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19572. i = (i + 1)
  19573. def inc(x : int) -> int:
  19574. return (x + 1)
  19575. def main() -> int:
  19576. v = [0, 41]
  19577. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19578. print(array_load(v, 1))
  19579. return 0
  19580. \end{lstlisting}
  19581. \fi}
  19582. \end{tcolorbox}
  19583. \caption{Output of \code{lower\_casts} on the example shown in
  19584. figure~\ref{fig:map-bang}.}
  19585. \label{fig:map-bang-lower-cast}
  19586. \end{figure}
  19587. A cast from one function type to another function type is accomplished
  19588. by generating a \code{lambda} whose parameter and return types match
  19589. the target function type. The body of the \code{lambda} should cast
  19590. the parameters from the target type to the source type. (Yes,
  19591. backward! Functions are contravariant\index{subject}{contravariant}
  19592. in the parameters.). Afterward, call the underlying function and then
  19593. cast the result from the source return type to the target return type.
  19594. Figure~\ref{fig:map-lower-cast} shows the output of the
  19595. \code{lower\_casts} pass on the \code{map} example give in
  19596. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19597. call to \code{map} is wrapped in a \code{lambda}.
  19598. \begin{figure}[tbp]
  19599. \begin{tcolorbox}[colback=white]
  19600. {\if\edition\racketEd
  19601. \begin{lstlisting}
  19602. (define (map [f : (Integer -> Integer)]
  19603. [v : (Vector Integer Integer)])
  19604. : (Vector Integer Integer)
  19605. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19606. (define (inc [x : Any]) : Any
  19607. (inject (+ (project x Integer) 1) Integer))
  19608. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19609. (project (inc (inject x9 Integer)) Integer))
  19610. (vector 0 41)) 1)
  19611. \end{lstlisting}
  19612. \fi}
  19613. {\if\edition\pythonEd
  19614. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19615. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19616. return (f(v[0]), f(v[1]),)
  19617. def inc(x : any) -> any:
  19618. return inject((project(x, int) + 1), int)
  19619. def main() -> int:
  19620. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19621. print(t[1])
  19622. return 0
  19623. \end{lstlisting}
  19624. \fi}
  19625. \end{tcolorbox}
  19626. \caption{Output of \code{lower\_casts} on the example shown in
  19627. figure~\ref{fig:gradual-map}.}
  19628. \label{fig:map-lower-cast}
  19629. \end{figure}
  19630. \section{Differentiate Proxies}
  19631. \label{sec:differentiate-proxies}
  19632. So far, the responsibility of differentiating tuples and tuple proxies
  19633. has been the job of the interpreter.
  19634. %
  19635. \racket{For example, the interpreter for \LangCast{} implements
  19636. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19637. figure~\ref{fig:guarded-tuple}.}
  19638. %
  19639. In the \code{differentiate\_proxies} pass we shift this responsibility
  19640. to the generated code.
  19641. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19642. we used the type \TUPLETYPENAME{} for both
  19643. real tuples and tuple proxies.
  19644. \python{Similarly, we use the type \code{list} for both arrays and
  19645. array proxies.}
  19646. In \LangPVec{} we return the
  19647. \TUPLETYPENAME{} type to its original
  19648. meaning, as the type of just tuples, and we introduce a new type,
  19649. \PTUPLETYNAME{}, whose values
  19650. can be either real tuples or tuple
  19651. proxies.
  19652. %
  19653. {\if\edition\pythonEd
  19654. Likewise, we return the
  19655. \ARRAYTYPENAME{} type to its original
  19656. meaning, as the type of arrays, and we introduce a new type,
  19657. \PARRAYTYNAME{}, whose values
  19658. can be either arrays or array proxies.
  19659. These new types come with a suite of new primitive operations.
  19660. \fi}
  19661. {\if\edition\racketEd
  19662. A tuple proxy is represented by a tuple containing three things: (1) the
  19663. underlying tuple, (2) a tuple of functions for casting elements that
  19664. are read from the tuple, and (3) a tuple of functions for casting
  19665. values to be written to the tuple. So, we define the following
  19666. abbreviation for the type of a tuple proxy:
  19667. \[
  19668. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19669. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19670. \]
  19671. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19672. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19673. %
  19674. Next we describe each of the new primitive operations.
  19675. \begin{description}
  19676. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19677. (\key{PVector} $T \ldots$)]\ \\
  19678. %
  19679. This operation brands a vector as a value of the \code{PVector} type.
  19680. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19681. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19682. %
  19683. This operation brands a vector proxy as value of the \code{PVector} type.
  19684. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19685. \BOOLTY{}] \ \\
  19686. %
  19687. This returns true if the value is a tuple proxy and false if it is a
  19688. real tuple.
  19689. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19690. (\key{Vector} $T \ldots$)]\ \\
  19691. %
  19692. Assuming that the input is a tuple, this operation returns the
  19693. tuple.
  19694. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19695. $\to$ \BOOLTY{}]\ \\
  19696. %
  19697. Given a tuple proxy, this operation returns the length of the tuple.
  19698. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19699. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19700. %
  19701. Given a tuple proxy, this operation returns the $i$th element of the
  19702. tuple.
  19703. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19704. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19705. Given a tuple proxy, this operation writes a value to the $i$th element
  19706. of the tuple.
  19707. \end{description}
  19708. \fi}
  19709. {\if\edition\pythonEd
  19710. %
  19711. A tuple proxy is represented by a tuple containing 1) the underlying
  19712. tuple and 2) a tuple of functions for casting elements that are read
  19713. from the tuple. The \LangPVec{} language includes the following AST
  19714. classes and primitive functions.
  19715. \begin{description}
  19716. \item[\code{InjectTuple}] \ \\
  19717. %
  19718. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19719. \item[\code{InjectTupleProxy}]\ \\
  19720. %
  19721. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19722. \item[\code{is\_tuple\_proxy}]\ \\
  19723. %
  19724. This primitive returns true if the value is a tuple proxy and false
  19725. if it is a tuple.
  19726. \item[\code{project\_tuple}]\ \\
  19727. %
  19728. Converts a tuple that is branded as \PTUPLETYNAME{}
  19729. back to a tuple.
  19730. \item[\code{proxy\_tuple\_len}]\ \\
  19731. %
  19732. Given a tuple proxy, returns the length of the underlying tuple.
  19733. \item[\code{proxy\_tuple\_load}]\ \\
  19734. %
  19735. Given a tuple proxy, returns the $i$th element of the underlying
  19736. tuple.
  19737. \end{description}
  19738. An array proxy is represented by a tuple containing 1) the underlying
  19739. array, 2) a function for casting elements that are read from the
  19740. array, and 3) a function for casting elements that are written to the
  19741. array. The \LangPVec{} language includes the following AST classes
  19742. and primitive functions.
  19743. \begin{description}
  19744. \item[\code{InjectList}]\ \\
  19745. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19746. \item[\code{InjectListProxy}]\ \\
  19747. %
  19748. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19749. \item[\code{is\_array\_proxy}]\ \\
  19750. %
  19751. Returns true if the value is a array proxy and false if it is an
  19752. array.
  19753. \item[\code{project\_array}]\ \\
  19754. %
  19755. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19756. array.
  19757. \item[\code{proxy\_array\_len}]\ \\
  19758. %
  19759. Given a array proxy, returns the length of the underlying array.
  19760. \item[\code{proxy\_array\_load}]\ \\
  19761. %
  19762. Given a array proxy, returns the $i$th element of the underlying
  19763. array.
  19764. \item[\code{proxy\_array\_store}]\ \\
  19765. %
  19766. Given an array proxy, writes a value to the $i$th element of the
  19767. underlying array.
  19768. \end{description}
  19769. \fi}
  19770. Now we discuss the translation that differentiates tuples and arrays
  19771. from proxies. First, every type annotation in the program is
  19772. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19773. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19774. places. For example, we wrap every tuple creation with an
  19775. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19776. %
  19777. {\if\edition\racketEd
  19778. \begin{minipage}{0.96\textwidth}
  19779. \begin{lstlisting}
  19780. (vector |$e_1 \ldots e_n$|)
  19781. |$\Rightarrow$|
  19782. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19783. \end{lstlisting}
  19784. \end{minipage}
  19785. \fi}
  19786. {\if\edition\pythonEd
  19787. \begin{lstlisting}
  19788. Tuple(|$e_1, \ldots, e_n$|)
  19789. |$\Rightarrow$|
  19790. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19791. \end{lstlisting}
  19792. \fi}
  19793. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19794. AST node that we introduced in the previous
  19795. section does not get injected.
  19796. {\if\edition\racketEd
  19797. \begin{lstlisting}
  19798. (raw-vector |$e_1 \ldots e_n$|)
  19799. |$\Rightarrow$|
  19800. (vector |$e'_1 \ldots e'_n$|)
  19801. \end{lstlisting}
  19802. \fi}
  19803. {\if\edition\pythonEd
  19804. \begin{lstlisting}
  19805. RawTuple(|$e_1, \ldots, e_n$|)
  19806. |$\Rightarrow$|
  19807. Tuple(|$e'_1, \ldots, e'_n$|)
  19808. \end{lstlisting}
  19809. \fi}
  19810. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19811. translates as follows:
  19812. %
  19813. {\if\edition\racketEd
  19814. \begin{lstlisting}
  19815. (vector-proxy |$e_1~e_2~e_3$|)
  19816. |$\Rightarrow$|
  19817. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19818. \end{lstlisting}
  19819. \fi}
  19820. {\if\edition\pythonEd
  19821. \begin{lstlisting}
  19822. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19823. |$\Rightarrow$|
  19824. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19825. \end{lstlisting}
  19826. \fi}
  19827. We translate the element access operations into conditional
  19828. expressions that check whether the value is a proxy and then dispatch
  19829. to either the appropriate proxy tuple operation or the regular tuple
  19830. operation.
  19831. {\if\edition\racketEd
  19832. \begin{lstlisting}
  19833. (vector-ref |$e_1$| |$i$|)
  19834. |$\Rightarrow$|
  19835. (let ([|$v~e_1$|])
  19836. (if (proxy? |$v$|)
  19837. (proxy-vector-ref |$v$| |$i$|)
  19838. (vector-ref (project-vector |$v$|) |$i$|)
  19839. \end{lstlisting}
  19840. \fi}
  19841. %
  19842. Note that in the branch for a tuple, we must apply
  19843. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19844. from the tuple.
  19845. The translation of array operations is similar to the ones for tuples.
  19846. \section{Reveal Casts}
  19847. \label{sec:reveal-casts-gradual}
  19848. {\if\edition\racketEd
  19849. Recall that the \code{reveal\_casts} pass
  19850. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19851. \code{Inject} and \code{Project} into lower-level operations.
  19852. %
  19853. In particular, \code{Project} turns into a conditional expression that
  19854. inspects the tag and retrieves the underlying value. Here we need to
  19855. augment the translation of \code{Project} to handle the situation in which
  19856. the target type is \code{PVector}. Instead of using
  19857. \code{vector-length} we need to use \code{proxy-vector-length}.
  19858. \begin{lstlisting}
  19859. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19860. |$\Rightarrow$|
  19861. (let |$\itm{tmp}$| |$e'$|
  19862. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19863. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19864. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19865. (exit)))
  19866. \end{lstlisting}
  19867. \fi}
  19868. %
  19869. {\if\edition\pythonEd
  19870. Recall that the $\itm{tagof}$ function determines the bits used to
  19871. identify values of different types and it is used in the \code{reveal\_casts}
  19872. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19873. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19874. decimal), just like the tuple and array types.
  19875. \fi}
  19876. %
  19877. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19878. \section{Closure Conversion}
  19879. \label{sec:closure-conversion-gradual}
  19880. The auxiliary function that translates type annotations needs to be
  19881. updated to handle the \PTUPLETYNAME{}
  19882. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19883. %
  19884. Otherwise, the only other changes are adding cases that copy the new
  19885. AST nodes.
  19886. \section{Select Instructions}
  19887. \label{sec:select-instructions-gradual}
  19888. Recall that the \code{select\_instructions} pass is responsible for
  19889. lowering the primitive operations into x86 instructions. So, we need
  19890. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19891. to x86. To do so, the first question we need to answer is how to
  19892. differentiate between tuple and tuples proxies\python{, and likewise for
  19893. arrays and array proxies}. We need just one bit to accomplish this;
  19894. we use the bit in position $63$ of the 64-bit tag at the front of
  19895. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19896. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19897. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19898. it that way.
  19899. {\if\edition\racketEd
  19900. \begin{lstlisting}
  19901. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19902. |$\Rightarrow$|
  19903. movq |$e'_1$|, |$\itm{lhs'}$|
  19904. \end{lstlisting}
  19905. \fi}
  19906. {\if\edition\pythonEd
  19907. \begin{lstlisting}
  19908. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19909. |$\Rightarrow$|
  19910. movq |$e'_1$|, |$\itm{lhs'}$|
  19911. \end{lstlisting}
  19912. \fi}
  19913. \python{The translation for \code{InjectList} is also a move instruction.}
  19914. \noindent On the other hand,
  19915. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19916. $63$ to $1$.
  19917. %
  19918. {\if\edition\racketEd
  19919. \begin{lstlisting}
  19920. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19921. |$\Rightarrow$|
  19922. movq |$e'_1$|, %r11
  19923. movq |$(1 << 63)$|, %rax
  19924. orq 0(%r11), %rax
  19925. movq %rax, 0(%r11)
  19926. movq %r11, |$\itm{lhs'}$|
  19927. \end{lstlisting}
  19928. \fi}
  19929. {\if\edition\pythonEd
  19930. \begin{lstlisting}
  19931. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19932. |$\Rightarrow$|
  19933. movq |$e'_1$|, %r11
  19934. movq |$(1 << 63)$|, %rax
  19935. orq 0(%r11), %rax
  19936. movq %rax, 0(%r11)
  19937. movq %r11, |$\itm{lhs'}$|
  19938. \end{lstlisting}
  19939. \fi}
  19940. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19941. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19942. The \racket{\code{proxy?} operation consumes}%
  19943. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19944. consume}
  19945. the information so carefully stashed away by the injections. It
  19946. isolates bit $63$ to tell whether the value is a proxy.
  19947. %
  19948. {\if\edition\racketEd
  19949. \begin{lstlisting}
  19950. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19951. |$\Rightarrow$|
  19952. movq |$e_1'$|, %r11
  19953. movq 0(%r11), %rax
  19954. sarq $63, %rax
  19955. andq $1, %rax
  19956. movq %rax, |$\itm{lhs'}$|
  19957. \end{lstlisting}
  19958. \fi}%
  19959. %
  19960. {\if\edition\pythonEd
  19961. \begin{lstlisting}
  19962. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19963. |$\Rightarrow$|
  19964. movq |$e_1'$|, %r11
  19965. movq 0(%r11), %rax
  19966. sarq $63, %rax
  19967. andq $1, %rax
  19968. movq %rax, |$\itm{lhs'}$|
  19969. \end{lstlisting}
  19970. \fi}%
  19971. %
  19972. The \racket{\code{project-vector} operation is}
  19973. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19974. straightforward to translate, so we leave that to the reader.
  19975. Regarding the element access operations for tuples\python{ and arrays}, the
  19976. runtime provides procedures that implement them (they are recursive
  19977. functions!), so here we simply need to translate these tuple
  19978. operations into the appropriate function call. For example, here is
  19979. the translation for
  19980. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19981. {\if\edition\racketEd
  19982. \begin{minipage}{0.96\textwidth}
  19983. \begin{lstlisting}
  19984. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19985. |$\Rightarrow$|
  19986. movq |$e_1'$|, %rdi
  19987. movq |$e_2'$|, %rsi
  19988. callq proxy_vector_ref
  19989. movq %rax, |$\itm{lhs'}$|
  19990. \end{lstlisting}
  19991. \end{minipage}
  19992. \fi}
  19993. {\if\edition\pythonEd
  19994. \begin{lstlisting}
  19995. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19996. |$\Rightarrow$|
  19997. movq |$e_1'$|, %rdi
  19998. movq |$e_2'$|, %rsi
  19999. callq proxy_vector_ref
  20000. movq %rax, |$\itm{lhs'}$|
  20001. \end{lstlisting}
  20002. \fi}
  20003. {\if\edition\pythonEd
  20004. % TODO: revisit the names vecof for python -Jeremy
  20005. We translate
  20006. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20007. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20008. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20009. \fi}
  20010. We have another batch of operations to deal with: those for the
  20011. \CANYTY{} type. Recall that we generate an
  20012. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20013. there is a element access on something of type \CANYTY{}, and
  20014. similarly for
  20015. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20016. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20017. section~\ref{sec:select-Lany} we selected instructions for these
  20018. operations on the basis of the idea that the underlying value was a tuple or
  20019. array. But in the current setting, the underlying value is of type
  20020. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20021. functions to deal with this:
  20022. \code{proxy\_vector\_ref},
  20023. \code{proxy\_vector\_set}, and
  20024. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  20025. to determine whether the value is a proxy, and then
  20026. dispatches to the the appropriate code.
  20027. %
  20028. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20029. can be translated as follows.
  20030. We begin by projecting the underlying value out of the tagged value and
  20031. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20032. {\if\edition\racketEd
  20033. \begin{lstlisting}
  20034. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20035. |$\Rightarrow$|
  20036. movq |$\neg 111$|, %rdi
  20037. andq |$e_1'$|, %rdi
  20038. movq |$e_2'$|, %rsi
  20039. callq proxy_vector_ref
  20040. movq %rax, |$\itm{lhs'}$|
  20041. \end{lstlisting}
  20042. \fi}
  20043. {\if\edition\pythonEd
  20044. \begin{lstlisting}
  20045. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20046. |$\Rightarrow$|
  20047. movq |$\neg 111$|, %rdi
  20048. andq |$e_1'$|, %rdi
  20049. movq |$e_2'$|, %rsi
  20050. callq proxy_vector_ref
  20051. movq %rax, |$\itm{lhs'}$|
  20052. \end{lstlisting}
  20053. \fi}
  20054. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20055. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20056. are translated in a similar way. Alternatively, you could generate
  20057. instructions to open-code
  20058. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20059. and \code{proxy\_vector\_length} functions.
  20060. \begin{exercise}\normalfont\normalsize
  20061. Implement a compiler for the gradually typed \LangGrad{} language by
  20062. extending and adapting your compiler for \LangLam{}. Create ten new
  20063. partially typed test programs. In addition to testing with these
  20064. new programs, test your compiler on all the tests for \LangLam{}
  20065. and for \LangDyn{}.
  20066. %
  20067. \racket{Sometimes you may get a type checking error on the
  20068. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20069. the \CANYTY{} type around each subexpression that has caused a type
  20070. error. Although \LangDyn{} does not have explicit casts, you can
  20071. induce one by wrapping the subexpression \code{e} with a call to
  20072. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20073. %
  20074. \python{Sometimes you may get a type checking error on the
  20075. \LangDyn{} programs but you can adapt them by inserting a
  20076. temporary variable of type \CANYTY{} that is initialized with the
  20077. troublesome expression.}
  20078. \end{exercise}
  20079. \begin{figure}[p]
  20080. \begin{tcolorbox}[colback=white]
  20081. {\if\edition\racketEd
  20082. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20083. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20084. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20085. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20086. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20087. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20088. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20089. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20090. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20091. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20092. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20093. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20094. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20095. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20096. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20097. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20098. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20099. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20100. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20101. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20102. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20103. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20104. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20105. \path[->,bend left=15] (Lgradual) edge [above] node
  20106. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20107. \path[->,bend left=15] (Lgradual2) edge [above] node
  20108. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20109. \path[->,bend left=15] (Lgradual3) edge [above] node
  20110. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20111. \path[->,bend left=15] (Lgradual4) edge [left] node
  20112. {\ttfamily\footnotesize shrink} (Lgradualr);
  20113. \path[->,bend left=15] (Lgradualr) edge [above] node
  20114. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20115. \path[->,bend right=15] (Lgradualp) edge [above] node
  20116. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20117. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20118. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20119. \path[->,bend right=15] (Llambdapp) edge [above] node
  20120. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20121. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20122. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20123. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20124. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20125. \path[->,bend left=15] (F1-2) edge [above] node
  20126. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20127. \path[->,bend left=15] (F1-3) edge [left] node
  20128. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20129. \path[->,bend left=15] (F1-4) edge [below] node
  20130. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20131. \path[->,bend right=15] (F1-5) edge [above] node
  20132. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20133. \path[->,bend right=15] (F1-6) edge [above] node
  20134. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20135. \path[->,bend right=15] (C3-2) edge [right] node
  20136. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20137. \path[->,bend right=15] (x86-2) edge [right] node
  20138. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20139. \path[->,bend right=15] (x86-2-1) edge [below] node
  20140. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20141. \path[->,bend right=15] (x86-2-2) edge [right] node
  20142. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20143. \path[->,bend left=15] (x86-3) edge [above] node
  20144. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20145. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20146. \end{tikzpicture}
  20147. \fi}
  20148. {\if\edition\pythonEd
  20149. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20150. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20151. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20152. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20153. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20154. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20155. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20156. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20157. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20158. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20159. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20160. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20161. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20162. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20163. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20164. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20165. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20166. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20167. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20168. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20169. \path[->,bend left=15] (Lgradual) edge [above] node
  20170. {\ttfamily\footnotesize shrink} (Lgradual2);
  20171. \path[->,bend left=15] (Lgradual2) edge [above] node
  20172. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20173. \path[->,bend left=15] (Lgradual3) edge [above] node
  20174. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20175. \path[->,bend left=15] (Lgradual4) edge [left] node
  20176. {\ttfamily\footnotesize resolve} (Lgradualr);
  20177. \path[->,bend left=15] (Lgradualr) edge [below] node
  20178. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20179. \path[->,bend right=15] (Lgradualp) edge [above] node
  20180. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20181. \path[->,bend right=15] (Llambdapp) edge [above] node
  20182. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20183. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20184. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20185. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20186. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20187. \path[->,bend left=15] (F1-1) edge [above] node
  20188. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20189. \path[->,bend left=15] (F1-2) edge [above] node
  20190. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20191. \path[->,bend left=15] (F1-3) edge [right] node
  20192. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20193. \path[->,bend right=15] (F1-5) edge [above] node
  20194. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20195. \path[->,bend right=15] (F1-6) edge [above] node
  20196. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20197. \path[->,bend right=15] (C3-2) edge [right] node
  20198. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20199. \path[->,bend right=15] (x86-2) edge [below] node
  20200. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20201. \path[->,bend right=15] (x86-3) edge [below] node
  20202. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20203. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20204. \end{tikzpicture}
  20205. \fi}
  20206. \end{tcolorbox}
  20207. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20208. \label{fig:Lgradual-passes}
  20209. \end{figure}
  20210. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20211. needed for the compilation of \LangGrad{}.
  20212. \section{Further Reading}
  20213. This chapter just scratches the surface of gradual typing. The basic
  20214. approach described here is missing two key ingredients that one would
  20215. want in a implementation of gradual typing: blame
  20216. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20217. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20218. problem addressed by blame tracking is that when a cast on a
  20219. higher-order value fails, it often does so at a point in the program
  20220. that is far removed from the original cast. Blame tracking is a
  20221. technique for propagating extra information through casts and proxies
  20222. so that when a cast fails, the error message can point back to the
  20223. original location of the cast in the source program.
  20224. The problem addressed by space-efficient casts also relates to
  20225. higher-order casts. It turns out that in partially typed programs, a
  20226. function or tuple can flow through a great many casts at runtime. With
  20227. the approach described in this chapter, each cast adds another
  20228. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20229. considerable space, but it also makes the function calls and tuple
  20230. operations slow. For example, a partially typed version of quicksort
  20231. could, in the worst case, build a chain of proxies of length $O(n)$
  20232. around the tuple, changing the overall time complexity of the
  20233. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20234. solution to this problem by representing casts using the coercion
  20235. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20236. long chains of proxies by compressing them into a concise normal
  20237. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20238. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20239. the Grift compiler:
  20240. \begin{center}
  20241. \url{https://github.com/Gradual-Typing/Grift}
  20242. \end{center}
  20243. There are also interesting interactions between gradual typing and
  20244. other language features, such as generics, information-flow types, and
  20245. type inference, to name a few. We recommend to the reader the
  20246. online gradual typing bibliography for more material:
  20247. \begin{center}
  20248. \url{http://samth.github.io/gradual-typing-bib/}
  20249. \end{center}
  20250. % TODO: challenge problem:
  20251. % type analysis and type specialization?
  20252. % coercions?
  20253. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20254. \chapter{Generics}
  20255. \label{ch:Lpoly}
  20256. \index{subject}{parametric polymorphism}
  20257. \index{subject}{generics}
  20258. \setcounter{footnote}{0}
  20259. This chapter studies the compilation of
  20260. generics\index{subject}{generics} (aka parametric
  20261. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20262. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20263. enable programmers to make code more reusable by parameterizing
  20264. functions and data structures with respect to the types on which they
  20265. operate. For example, figure~\ref{fig:map-poly} revisits the
  20266. \code{map} example and this time gives it a more fitting type. This
  20267. \code{map} function is parameterized with respect to the element type
  20268. of the tuple. The type of \code{map} is the following generic type
  20269. specified by the \code{All} type with parameter \code{T}:
  20270. \if\edition\racketEd
  20271. \begin{lstlisting}
  20272. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20273. \end{lstlisting}
  20274. \fi
  20275. \if\edition\pythonEd
  20276. \begin{lstlisting}
  20277. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20278. \end{lstlisting}
  20279. \fi
  20280. %
  20281. The idea is that \code{map} can be used at \emph{all} choices of a
  20282. type for parameter \code{T}. In the example shown in
  20283. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20284. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20285. \code{T}, but we could have just as well applied \code{map} to a tuple
  20286. of Booleans.
  20287. %
  20288. A \emph{monomorphic} function is simply one that is not generic.
  20289. %
  20290. We use the term \emph{instantiation} for the process (within the
  20291. language implementation) of turning a generic function into a
  20292. monomorphic one, where the type parameters have been replaced by
  20293. types.
  20294. \if\edition\pythonEd
  20295. %
  20296. In Python, when writing a generic function such as \code{map}, one
  20297. does not explicitly write down its generic type (using \code{All}).
  20298. Instead, the fact that it is generic is implied by the use of type
  20299. variables (such as \code{T}) in the type annotations of its
  20300. parameters.
  20301. %
  20302. \fi
  20303. \begin{figure}[tbp]
  20304. % poly_test_2.rkt
  20305. \begin{tcolorbox}[colback=white]
  20306. \if\edition\racketEd
  20307. \begin{lstlisting}
  20308. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20309. (define (map f v)
  20310. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20311. (define (inc [x : Integer]) : Integer (+ x 1))
  20312. (vector-ref (map inc (vector 0 41)) 1)
  20313. \end{lstlisting}
  20314. \fi
  20315. \if\edition\pythonEd
  20316. \begin{lstlisting}
  20317. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20318. return (f(tup[0]), f(tup[1]))
  20319. def add1(x : int) -> int:
  20320. return x + 1
  20321. t = map(add1, (0, 41))
  20322. print(t[1])
  20323. \end{lstlisting}
  20324. \fi
  20325. \end{tcolorbox}
  20326. \caption{A generic version of the \code{map} function.}
  20327. \label{fig:map-poly}
  20328. \end{figure}
  20329. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20330. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20331. shows the definition of the abstract syntax.
  20332. %
  20333. \if\edition\racketEd
  20334. We add a second form for function definitions in which a type
  20335. declaration comes before the \code{define}. In the abstract syntax,
  20336. the return type in the \code{Def} is \CANYTY{}, but that should be
  20337. ignored in favor of the return type in the type declaration. (The
  20338. \CANYTY{} comes from using the same parser as discussed in
  20339. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20340. enables the use of an \code{All} type for a function, thereby making
  20341. it generic.
  20342. \fi
  20343. %
  20344. The grammar for types is extended to include the type of a generic
  20345. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  20346. abstract syntax)}.
  20347. \newcommand{\LpolyGrammarRacket}{
  20348. \begin{array}{lcl}
  20349. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20350. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20351. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20352. \end{array}
  20353. }
  20354. \newcommand{\LpolyASTRacket}{
  20355. \begin{array}{lcl}
  20356. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20357. \Def &::=& \DECL{\Var}{\Type} \\
  20358. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20359. \end{array}
  20360. }
  20361. \newcommand{\LpolyGrammarPython}{
  20362. \begin{array}{lcl}
  20363. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20364. \end{array}
  20365. }
  20366. \newcommand{\LpolyASTPython}{
  20367. \begin{array}{lcl}
  20368. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20369. \MID \key{GenericVar}\LP\Var\RP
  20370. \end{array}
  20371. }
  20372. \begin{figure}[tp]
  20373. \centering
  20374. \begin{tcolorbox}[colback=white]
  20375. \footnotesize
  20376. \if\edition\racketEd
  20377. \[
  20378. \begin{array}{l}
  20379. \gray{\LintGrammarRacket{}} \\ \hline
  20380. \gray{\LvarGrammarRacket{}} \\ \hline
  20381. \gray{\LifGrammarRacket{}} \\ \hline
  20382. \gray{\LwhileGrammarRacket} \\ \hline
  20383. \gray{\LtupGrammarRacket} \\ \hline
  20384. \gray{\LfunGrammarRacket} \\ \hline
  20385. \gray{\LlambdaGrammarRacket} \\ \hline
  20386. \LpolyGrammarRacket \\
  20387. \begin{array}{lcl}
  20388. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20389. \end{array}
  20390. \end{array}
  20391. \]
  20392. \fi
  20393. \if\edition\pythonEd
  20394. \[
  20395. \begin{array}{l}
  20396. \gray{\LintGrammarPython{}} \\ \hline
  20397. \gray{\LvarGrammarPython{}} \\ \hline
  20398. \gray{\LifGrammarPython{}} \\ \hline
  20399. \gray{\LwhileGrammarPython} \\ \hline
  20400. \gray{\LtupGrammarPython} \\ \hline
  20401. \gray{\LfunGrammarPython} \\ \hline
  20402. \gray{\LlambdaGrammarPython} \\\hline
  20403. \LpolyGrammarPython \\
  20404. \begin{array}{lcl}
  20405. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20406. \end{array}
  20407. \end{array}
  20408. \]
  20409. \fi
  20410. \end{tcolorbox}
  20411. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20412. (figure~\ref{fig:Llam-concrete-syntax}).}
  20413. \label{fig:Lpoly-concrete-syntax}
  20414. \end{figure}
  20415. \begin{figure}[tp]
  20416. \centering
  20417. \begin{tcolorbox}[colback=white]
  20418. \footnotesize
  20419. \if\edition\racketEd
  20420. \[
  20421. \begin{array}{l}
  20422. \gray{\LintOpAST} \\ \hline
  20423. \gray{\LvarASTRacket{}} \\ \hline
  20424. \gray{\LifASTRacket{}} \\ \hline
  20425. \gray{\LwhileASTRacket{}} \\ \hline
  20426. \gray{\LtupASTRacket{}} \\ \hline
  20427. \gray{\LfunASTRacket} \\ \hline
  20428. \gray{\LlambdaASTRacket} \\ \hline
  20429. \LpolyASTRacket \\
  20430. \begin{array}{lcl}
  20431. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20432. \end{array}
  20433. \end{array}
  20434. \]
  20435. \fi
  20436. \if\edition\pythonEd
  20437. \[
  20438. \begin{array}{l}
  20439. \gray{\LintASTPython} \\ \hline
  20440. \gray{\LvarASTPython{}} \\ \hline
  20441. \gray{\LifASTPython{}} \\ \hline
  20442. \gray{\LwhileASTPython{}} \\ \hline
  20443. \gray{\LtupASTPython{}} \\ \hline
  20444. \gray{\LfunASTPython} \\ \hline
  20445. \gray{\LlambdaASTPython} \\ \hline
  20446. \LpolyASTPython \\
  20447. \begin{array}{lcl}
  20448. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20449. \end{array}
  20450. \end{array}
  20451. \]
  20452. \fi
  20453. \end{tcolorbox}
  20454. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20455. (figure~\ref{fig:Llam-syntax}).}
  20456. \label{fig:Lpoly-syntax}
  20457. \end{figure}
  20458. By including the \code{All} type in the $\Type$ nonterminal of the
  20459. grammar we choose to make generics first class, which has interesting
  20460. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20461. not include syntax for the \code{All} type. It is inferred for functions whose
  20462. type annotations contain type variables.} Many languages with generics, such as
  20463. C++~\citep{stroustrup88:_param_types} and Standard
  20464. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20465. may be helpful to see an example of first-class generics in action. In
  20466. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20467. whose parameter is a generic function. Indeed, because the grammar for
  20468. $\Type$ includes the \code{All} type, a generic function may also be
  20469. returned from a function or stored inside a tuple. The body of
  20470. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20471. and also to an integer, which would not be possible if \code{f} were
  20472. not generic.
  20473. \begin{figure}[tbp]
  20474. \begin{tcolorbox}[colback=white]
  20475. \if\edition\racketEd
  20476. \begin{lstlisting}
  20477. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20478. (define (apply_twice f)
  20479. (if (f #t) (f 42) (f 777)))
  20480. (: id (All (T) (T -> T)))
  20481. (define (id x) x)
  20482. (apply_twice id)
  20483. \end{lstlisting}
  20484. \fi
  20485. \if\edition\pythonEd
  20486. \begin{lstlisting}
  20487. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20488. if f(True):
  20489. return f(42)
  20490. else:
  20491. return f(777)
  20492. def id(x: T) -> T:
  20493. return x
  20494. print(apply_twice(id))
  20495. \end{lstlisting}
  20496. \fi
  20497. \end{tcolorbox}
  20498. \caption{An example illustrating first-class generics.}
  20499. \label{fig:apply-twice}
  20500. \end{figure}
  20501. The type checker for \LangPoly{} shown in
  20502. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20503. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20504. \if\edition\pythonEd
  20505. %
  20506. Regarding function definitions, if the type annotations on its
  20507. parameters contain generic variables, then the function is generic and
  20508. therefore its type is an \code{All} type wrapped around a function
  20509. type. Otherwise the function is monomorphic and its type is simply
  20510. a function type.
  20511. %
  20512. \fi
  20513. The type checking of a function application is extended to handle the
  20514. case in which the operator expression is a generic function. In that case
  20515. the type arguments are deduced by matching the type of the parameters
  20516. with the types of the arguments.
  20517. %
  20518. The \code{match\_types} auxiliary function
  20519. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20520. recursively descending through a parameter type \code{param\_ty} and
  20521. the corresponding argument type \code{arg\_ty}, making sure that they
  20522. are equal except when there is a type parameter in the parameter
  20523. type. Upon encountering a type parameter for the first time, the
  20524. algorithm deduces an association of the type parameter to the
  20525. corresponding part of the argument type. If it is not the first time
  20526. that the type parameter has been encountered, the algorithm looks up
  20527. its deduced type and makes sure that it is equal to the corresponding
  20528. part of the argument type. The return type of the application is the
  20529. return type of the generic function with the type parameters
  20530. replaced by the deduced type arguments, using the
  20531. \code{substitute\_type} auxiliary function, which is also listed in
  20532. figure~\ref{fig:type-check-Lpoly-aux}.
  20533. The type checker extends type equality to handle the \code{All} type.
  20534. This is not quite as simple as for other types, such as function and
  20535. tuple types, because two \code{All} types can be syntactically
  20536. different even though they are equivalent. For example,
  20537. %
  20538. \racket{\code{(All (T) (T -> T))}}
  20539. \python{\code{All[[T], Callable[[T], T]]}}
  20540. is equivalent to
  20541. \racket{\code{(All (U) (U -> U))}}
  20542. \python{\code{All[[U], Callable[[U], U]]}}.
  20543. %
  20544. Two generic types should be considered equal if they differ only in
  20545. the choice of the names of the type parameters. The definition of type
  20546. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20547. parameters in one type to match the type parameters of the other type.
  20548. \if\edition\racketEd
  20549. %
  20550. The type checker also ensures that only defined type variables appear
  20551. in type annotations. The \code{check\_well\_formed} function for which
  20552. the definition is shown in figure~\ref{fig:well-formed-types}
  20553. recursively inspects a type, making sure that each type variable has
  20554. been defined.
  20555. %
  20556. \fi
  20557. \begin{figure}[tbp]
  20558. \begin{tcolorbox}[colback=white]
  20559. \if\edition\racketEd
  20560. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20561. (define type-check-poly-class
  20562. (class type-check-Llambda-class
  20563. (super-new)
  20564. (inherit check-type-equal?)
  20565. (define/override (type-check-apply env e1 es)
  20566. (define-values (e^ ty) ((type-check-exp env) e1))
  20567. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20568. ((type-check-exp env) e)))
  20569. (match ty
  20570. [`(,ty^* ... -> ,rt)
  20571. (for ([arg-ty ty*] [param-ty ty^*])
  20572. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20573. (values e^ es^ rt)]
  20574. [`(All ,xs (,tys ... -> ,rt))
  20575. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20576. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20577. (match_types env^^ param-ty arg-ty)))
  20578. (define targs
  20579. (for/list ([x xs])
  20580. (match (dict-ref env^^ x (lambda () #f))
  20581. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20582. x (Apply e1 es))]
  20583. [ty ty])))
  20584. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20585. [else (error 'type-check "expected a function, not ~a" ty)]))
  20586. (define/override ((type-check-exp env) e)
  20587. (match e
  20588. [(Lambda `([,xs : ,Ts] ...) rT body)
  20589. (for ([T Ts]) ((check_well_formed env) T))
  20590. ((check_well_formed env) rT)
  20591. ((super type-check-exp env) e)]
  20592. [(HasType e1 ty)
  20593. ((check_well_formed env) ty)
  20594. ((super type-check-exp env) e)]
  20595. [else ((super type-check-exp env) e)]))
  20596. (define/override ((type-check-def env) d)
  20597. (verbose 'type-check "poly/def" d)
  20598. (match d
  20599. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20600. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20601. (for ([p ps]) ((check_well_formed ts-env) p))
  20602. ((check_well_formed ts-env) rt)
  20603. (define new-env (append ts-env (map cons xs ps) env))
  20604. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20605. (check-type-equal? ty^ rt body)
  20606. (Generic ts (Def f p:t* rt info body^))]
  20607. [else ((super type-check-def env) d)]))
  20608. (define/override (type-check-program p)
  20609. (match p
  20610. [(Program info body)
  20611. (type-check-program (ProgramDefsExp info '() body))]
  20612. [(ProgramDefsExp info ds body)
  20613. (define ds^ (combine-decls-defs ds))
  20614. (define new-env (for/list ([d ds^])
  20615. (cons (def-name d) (fun-def-type d))))
  20616. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20617. (define-values (body^ ty) ((type-check-exp new-env) body))
  20618. (check-type-equal? ty 'Integer body)
  20619. (ProgramDefsExp info ds^^ body^)]))
  20620. ))
  20621. \end{lstlisting}
  20622. \fi
  20623. \if\edition\pythonEd
  20624. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20625. def type_check_exp(self, e, env):
  20626. match e:
  20627. case Call(Name(f), args) if f in builtin_functions:
  20628. return super().type_check_exp(e, env)
  20629. case Call(func, args):
  20630. func_t = self.type_check_exp(func, env)
  20631. func.has_type = func_t
  20632. match func_t:
  20633. case AllType(ps, FunctionType(p_tys, rt)):
  20634. for arg in args:
  20635. arg.has_type = self.type_check_exp(arg, env)
  20636. arg_tys = [arg.has_type for arg in args]
  20637. deduced = {}
  20638. for (p, a) in zip(p_tys, arg_tys):
  20639. self.match_types(p, a, deduced, e)
  20640. return self.substitute_type(rt, deduced)
  20641. case _:
  20642. return super().type_check_exp(e, env)
  20643. case _:
  20644. return super().type_check_exp(e, env)
  20645. def type_check(self, p):
  20646. match p:
  20647. case Module(body):
  20648. env = {}
  20649. for s in body:
  20650. match s:
  20651. case FunctionDef(name, params, bod, dl, returns, comment):
  20652. params_t = [t for (x,t) in params]
  20653. ty_params = set()
  20654. for t in params_t:
  20655. ty_params |$\mid$|= self.generic_variables(t)
  20656. ty = FunctionType(params_t, returns)
  20657. if len(ty_params) > 0:
  20658. ty = AllType(list(ty_params), ty)
  20659. env[name] = ty
  20660. self.check_stmts(body, IntType(), env)
  20661. case _:
  20662. raise Exception('type_check: unexpected ' + repr(p))
  20663. \end{lstlisting}
  20664. \fi
  20665. \end{tcolorbox}
  20666. \caption{Type checker for the \LangPoly{} language.}
  20667. \label{fig:type-check-Lpoly}
  20668. \end{figure}
  20669. \begin{figure}[tbp]
  20670. \begin{tcolorbox}[colback=white]
  20671. \if\edition\racketEd
  20672. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20673. (define/override (type-equal? t1 t2)
  20674. (match* (t1 t2)
  20675. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20676. (define env (map cons xs ys))
  20677. (type-equal? (substitute_type env T1) T2)]
  20678. [(other wise)
  20679. (super type-equal? t1 t2)]))
  20680. (define/public (match_types env pt at)
  20681. (match* (pt at)
  20682. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20683. [('Void 'Void) env] [('Any 'Any) env]
  20684. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20685. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20686. (match_types env^ pt1 at1))]
  20687. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20688. (define env^ (match_types env prt art))
  20689. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20690. (match_types env^^ pt1 at1))]
  20691. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20692. (define env^ (append (map cons pxs axs) env))
  20693. (match_types env^ pt1 at1)]
  20694. [((? symbol? x) at)
  20695. (match (dict-ref env x (lambda () #f))
  20696. [#f (error 'type-check "undefined type variable ~a" x)]
  20697. ['Type (cons (cons x at) env)]
  20698. [t^ (check-type-equal? at t^ 'matching) env])]
  20699. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20700. (define/public (substitute_type env pt)
  20701. (match pt
  20702. ['Integer 'Integer] ['Boolean 'Boolean]
  20703. ['Void 'Void] ['Any 'Any]
  20704. [`(Vector ,ts ...)
  20705. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20706. [`(,ts ... -> ,rt)
  20707. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20708. [`(All ,xs ,t)
  20709. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20710. [(? symbol? x) (dict-ref env x)]
  20711. [else (error 'type-check "expected a type not ~a" pt)]))
  20712. (define/public (combine-decls-defs ds)
  20713. (match ds
  20714. ['() '()]
  20715. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20716. (unless (equal? name f)
  20717. (error 'type-check "name mismatch, ~a != ~a" name f))
  20718. (match type
  20719. [`(All ,xs (,ps ... -> ,rt))
  20720. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20721. (cons (Generic xs (Def name params^ rt info body))
  20722. (combine-decls-defs ds^))]
  20723. [`(,ps ... -> ,rt)
  20724. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20725. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20726. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20727. [`(,(Def f params rt info body) . ,ds^)
  20728. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20729. \end{lstlisting}
  20730. \fi
  20731. \if\edition\pythonEd
  20732. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20733. def match_types(self, param_ty, arg_ty, deduced, e):
  20734. match (param_ty, arg_ty):
  20735. case (GenericVar(id), _):
  20736. if id in deduced:
  20737. self.check_type_equal(arg_ty, deduced[id], e)
  20738. else:
  20739. deduced[id] = arg_ty
  20740. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20741. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20742. new_arg_ty = self.substitute_type(arg_ty, rename)
  20743. self.match_types(ty, new_arg_ty, deduced, e)
  20744. case (TupleType(ps), TupleType(ts)):
  20745. for (p, a) in zip(ps, ts):
  20746. self.match_types(p, a, deduced, e)
  20747. case (ListType(p), ListType(a)):
  20748. self.match_types(p, a, deduced, e)
  20749. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20750. for (pp, ap) in zip(pps, aps):
  20751. self.match_types(pp, ap, deduced, e)
  20752. self.match_types(prt, art, deduced, e)
  20753. case (IntType(), IntType()):
  20754. pass
  20755. case (BoolType(), BoolType()):
  20756. pass
  20757. case _:
  20758. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20759. def substitute_type(self, ty, var_map):
  20760. match ty:
  20761. case GenericVar(id):
  20762. return var_map[id]
  20763. case AllType(ps, ty):
  20764. new_map = copy.deepcopy(var_map)
  20765. for p in ps:
  20766. new_map[p] = GenericVar(p)
  20767. return AllType(ps, self.substitute_type(ty, new_map))
  20768. case TupleType(ts):
  20769. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20770. case ListType(ty):
  20771. return ListType(self.substitute_type(ty, var_map))
  20772. case FunctionType(pts, rt):
  20773. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20774. self.substitute_type(rt, var_map))
  20775. case IntType():
  20776. return IntType()
  20777. case BoolType():
  20778. return BoolType()
  20779. case _:
  20780. raise Exception('substitute_type: unexpected ' + repr(ty))
  20781. def check_type_equal(self, t1, t2, e):
  20782. match (t1, t2):
  20783. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20784. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20785. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20786. case (_, _):
  20787. return super().check_type_equal(t1, t2, e)
  20788. \end{lstlisting}
  20789. \fi
  20790. \end{tcolorbox}
  20791. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20792. \label{fig:type-check-Lpoly-aux}
  20793. \end{figure}
  20794. \if\edition\racketEd
  20795. \begin{figure}[tbp]
  20796. \begin{tcolorbox}[colback=white]
  20797. \begin{lstlisting}
  20798. (define/public ((check_well_formed env) ty)
  20799. (match ty
  20800. ['Integer (void)]
  20801. ['Boolean (void)]
  20802. ['Void (void)]
  20803. [(? symbol? a)
  20804. (match (dict-ref env a (lambda () #f))
  20805. ['Type (void)]
  20806. [else (error 'type-check "undefined type variable ~a" a)])]
  20807. [`(Vector ,ts ...)
  20808. (for ([t ts]) ((check_well_formed env) t))]
  20809. [`(,ts ... -> ,t)
  20810. (for ([t ts]) ((check_well_formed env) t))
  20811. ((check_well_formed env) t)]
  20812. [`(All ,xs ,t)
  20813. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20814. ((check_well_formed env^) t)]
  20815. [else (error 'type-check "unrecognized type ~a" ty)]))
  20816. \end{lstlisting}
  20817. \end{tcolorbox}
  20818. \caption{Well-formed types.}
  20819. \label{fig:well-formed-types}
  20820. \end{figure}
  20821. \fi
  20822. % TODO: interpreter for R'_10
  20823. \clearpage
  20824. \section{Compiling Generics}
  20825. \label{sec:compiling-poly}
  20826. Broadly speaking, there are four approaches to compiling generics, as
  20827. follows:
  20828. \begin{description}
  20829. \item[Monomorphization] generates a different version of a generic
  20830. function for each set of type arguments with which it is used,
  20831. producing type-specialized code. This approach results in the most
  20832. efficient code but requires whole-program compilation (no separate
  20833. compilation) and may increase code size. Unfortunately,
  20834. monomorphization is incompatible with first-class generics, because
  20835. it is not always possible to determine which generic functions are
  20836. used with which type arguments during compilation. (It can be done
  20837. at runtime, with just-in-time compilation.) Monomorphization is
  20838. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20839. generic functions in NESL~\citep{Blelloch:1993aa} and
  20840. ML~\citep{Weeks:2006aa}.
  20841. \item[Uniform representation] generates one version of each generic
  20842. function and requires all values to have a common \emph{boxed} format,
  20843. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20844. generic and monomorphic code is compiled similarly to code in a
  20845. dynamically typed language (like \LangDyn{}), in which primitive
  20846. operators require their arguments to be projected from \CANYTY{} and
  20847. their results to be injected into \CANYTY{}. (In object-oriented
  20848. languages, the projection is accomplished via virtual method
  20849. dispatch.) The uniform representation approach is compatible with
  20850. separate compilation and with first-class generics. However, it
  20851. produces the least efficient code because it introduces overhead in
  20852. the entire program. This approach is used in
  20853. Java~\citep{Bracha:1998fk},
  20854. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20855. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20856. \item[Mixed representation] generates one version of each generic
  20857. function, using a boxed representation for type variables. However,
  20858. monomorphic code is compiled as usual (as in \LangLam{}), and
  20859. conversions are performed at the boundaries between monomorphic code
  20860. and polymorphic code (e.g., when a generic function is instantiated
  20861. and called). This approach is compatible with separate compilation
  20862. and first-class generics and maintains efficiency in monomorphic
  20863. code. The trade-off is increased overhead at the boundary between
  20864. monomorphic and generic code. This approach is used in
  20865. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20866. Java 5 with the addition of autoboxing.
  20867. \item[Type passing] uses the unboxed representation in both
  20868. monomorphic and generic code. Each generic function is compiled to a
  20869. single function with extra parameters that describe the type
  20870. arguments. The type information is used by the generated code to
  20871. determine how to access the unboxed values at runtime. This approach is
  20872. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20873. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20874. compilation and first-class generics and maintains the
  20875. efficiency for monomorphic code. There is runtime overhead in
  20876. polymorphic code from dispatching on type information.
  20877. \end{description}
  20878. In this chapter we use the mixed representation approach, partly
  20879. because of its favorable attributes and partly because it is
  20880. straightforward to implement using the tools that we have already
  20881. built to support gradual typing. The work of compiling generic
  20882. functions is performed in two passes, \code{resolve} and
  20883. \code{erase\_types}, that we discuss next. The output of
  20884. \code{erase\_types} is \LangCast{}
  20885. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20886. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20887. \section{Resolve Instantiation}
  20888. \label{sec:generic-resolve}
  20889. Recall that the type checker for \LangPoly{} deduces the type
  20890. arguments at call sites to a generic function. The purpose of the
  20891. \code{resolve} pass is to turn this implicit instantiation into an
  20892. explicit one, by adding \code{inst} nodes to the syntax of the
  20893. intermediate language. An \code{inst} node records the mapping of
  20894. type parameters to type arguments. The semantics of the \code{inst}
  20895. node is to instantiate the result of its first argument, a generic
  20896. function, to produce a monomorphic function. However, because the
  20897. interpreter never analyzes type annotations, instantiation can be a
  20898. no-op and simply return the generic function.
  20899. %
  20900. The output language of the \code{resolve} pass is \LangInst{},
  20901. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20902. \if\edition\racketEd
  20903. The \code{resolve} pass combines the type declaration and polymorphic
  20904. function into a single definition, using the \code{Poly} form, to make
  20905. polymorphic functions more convenient to process in the next pass of the
  20906. compiler.
  20907. \fi
  20908. \newcommand{\LinstASTRacket}{
  20909. \begin{array}{lcl}
  20910. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20911. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20912. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20913. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20914. \end{array}
  20915. }
  20916. \newcommand{\LinstASTPython}{
  20917. \begin{array}{lcl}
  20918. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20919. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20920. \end{array}
  20921. }
  20922. \begin{figure}[tp]
  20923. \centering
  20924. \begin{tcolorbox}[colback=white]
  20925. \small
  20926. \if\edition\racketEd
  20927. \[
  20928. \begin{array}{l}
  20929. \gray{\LintOpAST} \\ \hline
  20930. \gray{\LvarASTRacket{}} \\ \hline
  20931. \gray{\LifASTRacket{}} \\ \hline
  20932. \gray{\LwhileASTRacket{}} \\ \hline
  20933. \gray{\LtupASTRacket{}} \\ \hline
  20934. \gray{\LfunASTRacket} \\ \hline
  20935. \gray{\LlambdaASTRacket} \\ \hline
  20936. \LinstASTRacket \\
  20937. \begin{array}{lcl}
  20938. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20939. \end{array}
  20940. \end{array}
  20941. \]
  20942. \fi
  20943. \if\edition\pythonEd
  20944. \[
  20945. \begin{array}{l}
  20946. \gray{\LintASTPython} \\ \hline
  20947. \gray{\LvarASTPython{}} \\ \hline
  20948. \gray{\LifASTPython{}} \\ \hline
  20949. \gray{\LwhileASTPython{}} \\ \hline
  20950. \gray{\LtupASTPython{}} \\ \hline
  20951. \gray{\LfunASTPython} \\ \hline
  20952. \gray{\LlambdaASTPython} \\ \hline
  20953. \LinstASTPython \\
  20954. \begin{array}{lcl}
  20955. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20956. \end{array}
  20957. \end{array}
  20958. \]
  20959. \fi
  20960. \end{tcolorbox}
  20961. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20962. (figure~\ref{fig:Llam-syntax}).}
  20963. \label{fig:Lpoly-prime-syntax}
  20964. \end{figure}
  20965. The output of the \code{resolve} pass on the generic \code{map}
  20966. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20967. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20968. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20969. \begin{figure}[tbp]
  20970. % poly_test_2.rkt
  20971. \begin{tcolorbox}[colback=white]
  20972. \if\edition\racketEd
  20973. \begin{lstlisting}
  20974. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20975. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20976. (define (inc [x : Integer]) : Integer (+ x 1))
  20977. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20978. (Integer))
  20979. inc (vector 0 41)) 1)
  20980. \end{lstlisting}
  20981. \fi
  20982. \if\edition\pythonEd
  20983. \begin{lstlisting}
  20984. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20985. return (f(tup[0]), f(tup[1]))
  20986. def add1(x : int) -> int:
  20987. return x + 1
  20988. t = inst(map, {T: int})(add1, (0, 41))
  20989. print(t[1])
  20990. \end{lstlisting}
  20991. \fi
  20992. \end{tcolorbox}
  20993. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20994. \label{fig:map-resolve}
  20995. \end{figure}
  20996. \section{Erase Types}
  20997. \label{sec:erase_types}
  20998. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20999. represent type variables. For example, figure~\ref{fig:map-erase}
  21000. shows the output of the \code{erase\_types} pass on the generic
  21001. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21002. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21003. \code{All} types are removed from the type of \code{map}.
  21004. \begin{figure}[tbp]
  21005. \begin{tcolorbox}[colback=white]
  21006. \if\edition\racketEd
  21007. \begin{lstlisting}
  21008. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21009. : (Vector Any Any)
  21010. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21011. (define (inc [x : Integer]) : Integer (+ x 1))
  21012. (vector-ref ((cast map
  21013. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21014. ((Integer -> Integer) (Vector Integer Integer)
  21015. -> (Vector Integer Integer)))
  21016. inc (vector 0 41)) 1)
  21017. \end{lstlisting}
  21018. \fi
  21019. \if\edition\pythonEd
  21020. \begin{lstlisting}
  21021. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21022. return (f(tup[0]), f(tup[1]))
  21023. def add1(x : int) -> int:
  21024. return (x + 1)
  21025. def main() -> int:
  21026. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21027. print(t[1])
  21028. return 0
  21029. \end{lstlisting}
  21030. {\small
  21031. where\\
  21032. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21033. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21034. }
  21035. \fi
  21036. \end{tcolorbox}
  21037. \caption{The generic \code{map} example after type erasure.}
  21038. \label{fig:map-erase}
  21039. \end{figure}
  21040. This process of type erasure creates a challenge at points of
  21041. instantiation. For example, consider the instantiation of
  21042. \code{map} shown in figure~\ref{fig:map-resolve}.
  21043. The type of \code{map} is
  21044. %
  21045. \if\edition\racketEd
  21046. \begin{lstlisting}
  21047. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21048. \end{lstlisting}
  21049. \fi
  21050. \if\edition\pythonEd
  21051. \begin{lstlisting}
  21052. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21053. \end{lstlisting}
  21054. \fi
  21055. %
  21056. and it is instantiated to
  21057. %
  21058. \if\edition\racketEd
  21059. \begin{lstlisting}
  21060. ((Integer -> Integer) (Vector Integer Integer)
  21061. -> (Vector Integer Integer))
  21062. \end{lstlisting}
  21063. \fi
  21064. \if\edition\pythonEd
  21065. \begin{lstlisting}
  21066. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21067. \end{lstlisting}
  21068. \fi
  21069. %
  21070. After erasure, the type of \code{map} is
  21071. %
  21072. \if\edition\racketEd
  21073. \begin{lstlisting}
  21074. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21075. \end{lstlisting}
  21076. \fi
  21077. \if\edition\pythonEd
  21078. \begin{lstlisting}
  21079. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21080. \end{lstlisting}
  21081. \fi
  21082. %
  21083. but we need to convert it to the instantiated type. This is easy to
  21084. do in the language \LangCast{} with a single \code{cast}. In the
  21085. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21086. \code{map} has been compiled to a \code{cast} from the type of
  21087. \code{map} to the instantiated type. The source and the target type of a
  21088. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21089. the case because both the source and target are obtained from the same
  21090. generic type of \code{map}, replacing the type parameters with
  21091. \CANYTY{} in the former and with the deduced type arguments in the
  21092. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21093. To implement the \code{erase\_types} pass, we first recommend defining
  21094. a recursive function that translates types, named
  21095. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21096. follows.
  21097. %
  21098. \if\edition\racketEd
  21099. \begin{lstlisting}
  21100. |$T$|
  21101. |$\Rightarrow$|
  21102. Any
  21103. \end{lstlisting}
  21104. \fi
  21105. \if\edition\pythonEd
  21106. \begin{lstlisting}
  21107. GenericVar(|$T$|)
  21108. |$\Rightarrow$|
  21109. Any
  21110. \end{lstlisting}
  21111. \fi
  21112. %
  21113. \noindent The \code{erase\_type} function also removes the generic
  21114. \code{All} types.
  21115. %
  21116. \if\edition\racketEd
  21117. \begin{lstlisting}
  21118. (All |$xs$| |$T_1$|)
  21119. |$\Rightarrow$|
  21120. |$T'_1$|
  21121. \end{lstlisting}
  21122. \fi
  21123. \if\edition\pythonEd
  21124. \begin{lstlisting}
  21125. AllType(|$xs$|, |$T_1$|)
  21126. |$\Rightarrow$|
  21127. |$T'_1$|
  21128. \end{lstlisting}
  21129. \fi
  21130. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21131. %
  21132. In this compiler pass, apply the \code{erase\_type} function to all
  21133. the type annotations in the program.
  21134. Regarding the translation of expressions, the case for \code{Inst} is
  21135. the interesting one. We translate it into a \code{Cast}, as shown
  21136. next.
  21137. The type of the subexpression $e$ is a generic type of the form
  21138. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  21139. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  21140. cast is the erasure of $T$, the type $T_s$.
  21141. %
  21142. \if\edition\racketEd
  21143. %
  21144. The target type $T_t$ is the result of substituting the argument types
  21145. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21146. erasure.
  21147. %
  21148. \begin{lstlisting}
  21149. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21150. |$\Rightarrow$|
  21151. (Cast |$e'$| |$T_s$| |$T_t$|)
  21152. \end{lstlisting}
  21153. %
  21154. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21155. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21156. \fi
  21157. \if\edition\pythonEd
  21158. %
  21159. The target type $T_t$ is the result of substituting the deduced
  21160. argument types $d$ in $T$ followed by doing type erasure.
  21161. %
  21162. \begin{lstlisting}
  21163. Inst(|$e$|, |$d$|)
  21164. |$\Rightarrow$|
  21165. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21166. \end{lstlisting}
  21167. %
  21168. where
  21169. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21170. \fi
  21171. Finally, each generic function is translated to a regular
  21172. function in which type erasure has been applied to all the type
  21173. annotations and the body.
  21174. %% \begin{lstlisting}
  21175. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21176. %% |$\Rightarrow$|
  21177. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21178. %% \end{lstlisting}
  21179. \begin{exercise}\normalfont\normalsize
  21180. Implement a compiler for the polymorphic language \LangPoly{} by
  21181. extending and adapting your compiler for \LangGrad{}. Create six new
  21182. test programs that use polymorphic functions. Some of them should
  21183. make use of first-class generics.
  21184. \end{exercise}
  21185. \begin{figure}[tbp]
  21186. \begin{tcolorbox}[colback=white]
  21187. \if\edition\racketEd
  21188. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21189. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21190. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21191. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21192. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21193. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21194. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21195. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21196. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21197. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21198. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21199. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21200. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21201. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21202. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21203. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21204. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21205. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21206. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21207. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21208. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21209. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21210. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21211. \path[->,bend left=15] (Lpoly) edge [above] node
  21212. {\ttfamily\footnotesize resolve} (Lpolyp);
  21213. \path[->,bend left=15] (Lpolyp) edge [above] node
  21214. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21215. \path[->,bend left=15] (Lgradualp) edge [above] node
  21216. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21217. \path[->,bend left=15] (Llambdapp) edge [left] node
  21218. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21219. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21220. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21221. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21222. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21223. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21224. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21225. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21226. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21227. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21228. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21229. \path[->,bend left=15] (F1-1) edge [above] node
  21230. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21231. \path[->,bend left=15] (F1-2) edge [above] node
  21232. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21233. \path[->,bend left=15] (F1-3) edge [left] node
  21234. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21235. \path[->,bend left=15] (F1-4) edge [below] node
  21236. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21237. \path[->,bend right=15] (F1-5) edge [above] node
  21238. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21239. \path[->,bend right=15] (F1-6) edge [above] node
  21240. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21241. \path[->,bend right=15] (C3-2) edge [right] node
  21242. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21243. \path[->,bend right=15] (x86-2) edge [right] node
  21244. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21245. \path[->,bend right=15] (x86-2-1) edge [below] node
  21246. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21247. \path[->,bend right=15] (x86-2-2) edge [right] node
  21248. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21249. \path[->,bend left=15] (x86-3) edge [above] node
  21250. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21251. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21252. \end{tikzpicture}
  21253. \fi
  21254. \if\edition\pythonEd
  21255. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21256. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21257. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21258. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21259. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21260. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21261. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21262. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21263. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21264. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21265. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21266. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21267. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21268. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21269. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21270. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21271. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21272. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21273. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21274. \path[->,bend left=15] (Lgradual) edge [above] node
  21275. {\ttfamily\footnotesize shrink} (Lgradual2);
  21276. \path[->,bend left=15] (Lgradual2) edge [above] node
  21277. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21278. \path[->,bend left=15] (Lgradual3) edge [above] node
  21279. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21280. \path[->,bend left=15] (Lgradual4) edge [left] node
  21281. {\ttfamily\footnotesize resolve} (Lgradualr);
  21282. \path[->,bend left=15] (Lgradualr) edge [below] node
  21283. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21284. \path[->,bend right=15] (Llambdapp) edge [above] node
  21285. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21286. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21287. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21288. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21289. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21290. \path[->,bend right=15] (F1-1) edge [below] node
  21291. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21292. \path[->,bend right=15] (F1-2) edge [below] node
  21293. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21294. \path[->,bend left=15] (F1-3) edge [above] node
  21295. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21296. \path[->,bend left=15] (F1-5) edge [left] node
  21297. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21298. \path[->,bend left=5] (F1-6) edge [below] node
  21299. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21300. \path[->,bend right=15] (C3-2) edge [right] node
  21301. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21302. \path[->,bend right=15] (x86-2) edge [below] node
  21303. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21304. \path[->,bend right=15] (x86-3) edge [below] node
  21305. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21306. \path[->,bend left=15] (x86-4) edge [above] node
  21307. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21308. \end{tikzpicture}
  21309. \fi
  21310. \end{tcolorbox}
  21311. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21312. \label{fig:Lpoly-passes}
  21313. \end{figure}
  21314. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21315. needed to compile \LangPoly{}.
  21316. % TODO: challenge problem: specialization of instantiations
  21317. % Further Reading
  21318. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21319. \clearpage
  21320. \appendix
  21321. \chapter{Appendix}
  21322. \setcounter{footnote}{0}
  21323. \if\edition\racketEd
  21324. \section{Interpreters}
  21325. \label{appendix:interp}
  21326. \index{subject}{interpreter}
  21327. We provide interpreters for each of the source languages \LangInt{},
  21328. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21329. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21330. intermediate languages \LangCVar{} and \LangCIf{} are in
  21331. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21332. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21333. \key{interp.rkt} file.
  21334. \section{Utility Functions}
  21335. \label{appendix:utilities}
  21336. The utility functions described in this section are in the
  21337. \key{utilities.rkt} file of the support code.
  21338. \paragraph{\code{interp-tests}}
  21339. This function runs the compiler passes and the interpreters on each of
  21340. the specified tests to check whether each pass is correct. The
  21341. \key{interp-tests} function has the following parameters:
  21342. \begin{description}
  21343. \item[name (a string)] A name to identify the compiler,
  21344. \item[typechecker] A function of exactly one argument that either
  21345. raises an error using the \code{error} function when it encounters a
  21346. type error or returns \code{\#f} when it encounters a type
  21347. error. If there is no type error, the type checker returns the
  21348. program.
  21349. \item[passes] A list with one entry per pass. An entry is a list
  21350. consisting of four things:
  21351. \begin{enumerate}
  21352. \item a string giving the name of the pass;
  21353. \item the function that implements the pass (a translator from AST
  21354. to AST);
  21355. \item a function that implements the interpreter (a function from
  21356. AST to result value) for the output language; and,
  21357. \item a type checker for the output language. Type checkers for
  21358. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21359. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21360. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21361. type checker entry is optional. The support code does not provide
  21362. type checkers for the x86 languages.
  21363. \end{enumerate}
  21364. \item[source-interp] An interpreter for the source language. The
  21365. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21366. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21367. \item[tests] A list of test numbers that specifies which tests to
  21368. run (explained next).
  21369. \end{description}
  21370. %
  21371. The \key{interp-tests} function assumes that the subdirectory
  21372. \key{tests} has a collection of Racket programs whose names all start
  21373. with the family name, followed by an underscore and then the test
  21374. number, and ending with the file extension \key{.rkt}. Also, for each test
  21375. program that calls \code{read} one or more times, there is a file with
  21376. the same name except that the file extension is \key{.in}, which
  21377. provides the input for the Racket program. If the test program is
  21378. expected to fail type checking, then there should be an empty file of
  21379. the same name with extension \key{.tyerr}.
  21380. \paragraph{\code{compiler-tests}}
  21381. This function runs the compiler passes to generate x86 (a \key{.s}
  21382. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21383. It runs the machine code and checks that the output is $42$. The
  21384. parameters to the \code{compiler-tests} function are similar to those
  21385. of the \code{interp-tests} function, and they consist of
  21386. \begin{itemize}
  21387. \item a compiler name (a string),
  21388. \item a type checker,
  21389. \item description of the passes,
  21390. \item name of a test-family, and
  21391. \item a list of test numbers.
  21392. \end{itemize}
  21393. \paragraph{\code{compile-file}}
  21394. This function takes a description of the compiler passes (see the
  21395. comment for \key{interp-tests}) and returns a function that, given a
  21396. program file name (a string ending in \key{.rkt}), applies all the
  21397. passes and writes the output to a file whose name is the same as the
  21398. program file name with extension \key{.rkt} replaced by \key{.s}.
  21399. \paragraph{\code{read-program}}
  21400. This function takes a file path and parses that file (it must be a
  21401. Racket program) into an abstract syntax tree.
  21402. \paragraph{\code{parse-program}}
  21403. This function takes an S-expression representation of an abstract
  21404. syntax tree and converts it into the struct-based representation.
  21405. \paragraph{\code{assert}}
  21406. This function takes two parameters, a string (\code{msg}) and Boolean
  21407. (\code{bool}), and displays the message \key{msg} if the Boolean
  21408. \key{bool} is false.
  21409. \paragraph{\code{lookup}}
  21410. % remove discussion of lookup? -Jeremy
  21411. This function takes a key and an alist and returns the first value that is
  21412. associated with the given key, if there is one. If not, an error is
  21413. triggered. The alist may contain both immutable pairs (built with
  21414. \key{cons}) and mutable pairs (built with \key{mcons}).
  21415. %The \key{map2} function ...
  21416. \fi %\racketEd
  21417. \section{x86 Instruction Set Quick Reference}
  21418. \label{sec:x86-quick-reference}
  21419. \index{subject}{x86}
  21420. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21421. do. We write $A \to B$ to mean that the value of $A$ is written into
  21422. location $B$. Address offsets are given in bytes. The instruction
  21423. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21424. registers (such as \code{\%rax}), or memory references (such as
  21425. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21426. reference per instruction. Other operands must be immediates or
  21427. registers.
  21428. \begin{table}[tbp]
  21429. \centering
  21430. \begin{tabular}{l|l}
  21431. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21432. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21433. \texttt{negq} $A$ & $- A \to A$ \\
  21434. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21435. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21436. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21437. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21438. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21439. \texttt{retq} & Pops the return address and jumps to it \\
  21440. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21441. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21442. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21443. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21444. be an immediate) \\
  21445. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21446. matches the condition code of the instruction; otherwise go to the
  21447. next instructions. The condition codes are \key{e} for \emph{equal},
  21448. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21449. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21450. \texttt{jl} $L$ & \\
  21451. \texttt{jle} $L$ & \\
  21452. \texttt{jg} $L$ & \\
  21453. \texttt{jge} $L$ & \\
  21454. \texttt{jmp} $L$ & Jump to label $L$ \\
  21455. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21456. \texttt{movzbq} $A$, $B$ &
  21457. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21458. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21459. and the extra bytes of $B$ are set to zero.} \\
  21460. & \\
  21461. & \\
  21462. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21463. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21464. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21465. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21466. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21467. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21468. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21469. description of the condition codes. $A$ must be a single byte register
  21470. (e.g., \texttt{al} or \texttt{cl}).} \\
  21471. \texttt{setl} $A$ & \\
  21472. \texttt{setle} $A$ & \\
  21473. \texttt{setg} $A$ & \\
  21474. \texttt{setge} $A$ &
  21475. \end{tabular}
  21476. \vspace{5pt}
  21477. \caption{Quick reference for the x86 instructions used in this book.}
  21478. \label{tab:x86-instr}
  21479. \end{table}
  21480. %% \if\edition\racketEd
  21481. %% \cleardoublepage
  21482. %% \section{Concrete Syntax for Intermediate Languages}
  21483. %% The concrete syntax of \LangAny{} is defined in
  21484. %% figure~\ref{fig:Lany-concrete-syntax}.
  21485. %% \begin{figure}[tp]
  21486. %% \centering
  21487. %% \fbox{
  21488. %% \begin{minipage}{0.97\textwidth}\small
  21489. %% \[
  21490. %% \begin{array}{lcl}
  21491. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  21492. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  21493. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  21494. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  21495. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  21496. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  21497. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  21498. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  21499. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  21500. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  21501. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  21502. %% \MID \LP\key{void?}\;\Exp\RP \\
  21503. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  21504. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  21505. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  21506. %% \end{array}
  21507. %% \]
  21508. %% \end{minipage}
  21509. %% }
  21510. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  21511. %% (figure~\ref{fig:Llam-syntax}).}
  21512. %% \label{fig:Lany-concrete-syntax}
  21513. %% \end{figure}
  21514. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  21515. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  21516. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  21517. %% \ref{fig:c3-concrete-syntax}, respectively.
  21518. %% \begin{figure}[tbp]
  21519. %% \fbox{
  21520. %% \begin{minipage}{0.96\textwidth}
  21521. %% \small
  21522. %% \[
  21523. %% \begin{array}{lcl}
  21524. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  21525. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21526. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  21527. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  21528. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  21529. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  21530. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  21531. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  21532. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  21533. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  21534. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  21535. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  21536. %% \end{array}
  21537. %% \]
  21538. %% \end{minipage}
  21539. %% }
  21540. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  21541. %% \label{fig:c2-concrete-syntax}
  21542. %% \end{figure}
  21543. %% \begin{figure}[tp]
  21544. %% \fbox{
  21545. %% \begin{minipage}{0.96\textwidth}
  21546. %% \small
  21547. %% \[
  21548. %% \begin{array}{lcl}
  21549. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  21550. %% \\
  21551. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21552. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  21553. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  21554. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  21555. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  21556. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  21557. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  21558. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  21559. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  21560. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  21561. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  21562. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  21563. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  21564. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  21565. %% \LangCFunM{} & ::= & \Def\ldots
  21566. %% \end{array}
  21567. %% \]
  21568. %% \end{minipage}
  21569. %% }
  21570. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  21571. %% \label{fig:c3-concrete-syntax}
  21572. %% \end{figure}
  21573. %% \fi % racketEd
  21574. \backmatter
  21575. \addtocontents{toc}{\vspace{11pt}}
  21576. %% \addtocontents{toc}{\vspace{11pt}}
  21577. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  21578. \nocite{*}\let\bibname\refname
  21579. \addcontentsline{toc}{fmbm}{\refname}
  21580. \printbibliography
  21581. %\printindex{authors}{Author Index}
  21582. \printindex{subject}{Index}
  21583. \end{document}
  21584. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21585. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21586. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21587. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21588. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21589. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21590. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21591. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21592. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21593. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21594. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21595. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21596. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21597. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21598. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21599. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21600. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21601. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21602. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21603. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21604. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21605. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21606. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21607. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21608. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21609. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21610. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21611. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21612. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21613. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21614. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21615. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21616. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21617. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21618. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21619. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21620. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21621. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21622. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21623. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21624. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21625. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21626. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21627. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21628. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21629. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21630. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21631. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21632. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21633. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21634. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21635. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21636. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21637. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21638. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21639. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21640. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21641. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21642. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21643. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21644. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21645. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21646. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21647. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21648. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21649. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21650. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21651. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21652. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21653. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21654. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21655. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21656. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21657. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21658. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21659. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21660. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21661. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21662. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21663. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21664. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21665. % LocalWords: pseudocode underapproximation underapproximations LALR
  21666. % LocalWords: semilattices overapproximate incrementing Earley docs
  21667. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21668. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21669. % LocalWords: subparses